6ebbf871995a59a8e264c3348dfb923b83d883fe
[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       // Extract subvector is special because the value type
1400       // (result) is 256/128-bit but the source is 512-bit wide.
1401       if (VT.is128BitVector() || VT.is256BitVector())
1402         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1403
1404       if (VT.getVectorElementType() == MVT::i1)
1405         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1406
1407       // Do not attempt to custom lower other non-512-bit vectors
1408       if (!VT.is512BitVector())
1409         continue;
1410
1411       if (VT != MVT::v8i64) {
1412         setOperationAction(ISD::XOR,   VT, Promote);
1413         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1414         setOperationAction(ISD::OR,    VT, Promote);
1415         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1416         setOperationAction(ISD::AND,   VT, Promote);
1417         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1418       }
1419       setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1420       setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1421       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1422       setOperationAction(ISD::VSELECT,             VT, Legal);
1423       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1424       setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1425       setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1426     }
1427     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1428       MVT VT = (MVT::SimpleValueType)i;
1429
1430       // Do not attempt to promote non-256-bit vectors
1431       if (!VT.is512BitVector())
1432         continue;
1433
1434       setOperationAction(ISD::LOAD,   VT, Promote);
1435       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1436       setOperationAction(ISD::SELECT, VT, Promote);
1437       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1438     }
1439   }// has  AVX-512
1440
1441   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1442   // of this type with custom code.
1443   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1444            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1445     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1446                        Custom);
1447   }
1448
1449   // We want to custom lower some of our intrinsics.
1450   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1451   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1452
1453   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1454   // handle type legalization for these operations here.
1455   //
1456   // FIXME: We really should do custom legalization for addition and
1457   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1458   // than generic legalization for 64-bit multiplication-with-overflow, though.
1459   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1460     // Add/Sub/Mul with overflow operations are custom lowered.
1461     MVT VT = IntVTs[i];
1462     setOperationAction(ISD::SADDO, VT, Custom);
1463     setOperationAction(ISD::UADDO, VT, Custom);
1464     setOperationAction(ISD::SSUBO, VT, Custom);
1465     setOperationAction(ISD::USUBO, VT, Custom);
1466     setOperationAction(ISD::SMULO, VT, Custom);
1467     setOperationAction(ISD::UMULO, VT, Custom);
1468   }
1469
1470   // There are no 8-bit 3-address imul/mul instructions
1471   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1472   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1473
1474   if (!Subtarget->is64Bit()) {
1475     // These libcalls are not available in 32-bit.
1476     setLibcallName(RTLIB::SHL_I128, 0);
1477     setLibcallName(RTLIB::SRL_I128, 0);
1478     setLibcallName(RTLIB::SRA_I128, 0);
1479   }
1480
1481   // Combine sin / cos into one node or libcall if possible.
1482   if (Subtarget->hasSinCos()) {
1483     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1484     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1485     if (Subtarget->isTargetDarwin()) {
1486       // For MacOSX, we don't want to the normal expansion of a libcall to
1487       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1488       // traffic.
1489       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1490       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1491     }
1492   }
1493
1494   // We have target-specific dag combine patterns for the following nodes:
1495   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1496   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1497   setTargetDAGCombine(ISD::VSELECT);
1498   setTargetDAGCombine(ISD::SELECT);
1499   setTargetDAGCombine(ISD::SHL);
1500   setTargetDAGCombine(ISD::SRA);
1501   setTargetDAGCombine(ISD::SRL);
1502   setTargetDAGCombine(ISD::OR);
1503   setTargetDAGCombine(ISD::AND);
1504   setTargetDAGCombine(ISD::ADD);
1505   setTargetDAGCombine(ISD::FADD);
1506   setTargetDAGCombine(ISD::FSUB);
1507   setTargetDAGCombine(ISD::FMA);
1508   setTargetDAGCombine(ISD::SUB);
1509   setTargetDAGCombine(ISD::LOAD);
1510   setTargetDAGCombine(ISD::STORE);
1511   setTargetDAGCombine(ISD::ZERO_EXTEND);
1512   setTargetDAGCombine(ISD::ANY_EXTEND);
1513   setTargetDAGCombine(ISD::SIGN_EXTEND);
1514   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1515   setTargetDAGCombine(ISD::TRUNCATE);
1516   setTargetDAGCombine(ISD::SINT_TO_FP);
1517   setTargetDAGCombine(ISD::SETCC);
1518   if (Subtarget->is64Bit())
1519     setTargetDAGCombine(ISD::MUL);
1520   setTargetDAGCombine(ISD::XOR);
1521
1522   computeRegisterProperties();
1523
1524   // On Darwin, -Os means optimize for size without hurting performance,
1525   // do not reduce the limit.
1526   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1527   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1528   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1529   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1530   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1531   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1532   setPrefLoopAlignment(4); // 2^4 bytes.
1533
1534   // Predictable cmov don't hurt on atom because it's in-order.
1535   PredictableSelectIsExpensive = !Subtarget->isAtom();
1536
1537   setPrefFunctionAlignment(4); // 2^4 bytes.
1538 }
1539
1540 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1541   if (!VT.isVector()) return MVT::i8;
1542   return VT.changeVectorElementTypeToInteger();
1543 }
1544
1545 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1546 /// the desired ByVal argument alignment.
1547 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1548   if (MaxAlign == 16)
1549     return;
1550   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1551     if (VTy->getBitWidth() == 128)
1552       MaxAlign = 16;
1553   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1554     unsigned EltAlign = 0;
1555     getMaxByValAlign(ATy->getElementType(), EltAlign);
1556     if (EltAlign > MaxAlign)
1557       MaxAlign = EltAlign;
1558   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1559     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1560       unsigned EltAlign = 0;
1561       getMaxByValAlign(STy->getElementType(i), EltAlign);
1562       if (EltAlign > MaxAlign)
1563         MaxAlign = EltAlign;
1564       if (MaxAlign == 16)
1565         break;
1566     }
1567   }
1568 }
1569
1570 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1571 /// function arguments in the caller parameter area. For X86, aggregates
1572 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1573 /// are at 4-byte boundaries.
1574 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1575   if (Subtarget->is64Bit()) {
1576     // Max of 8 and alignment of type.
1577     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1578     if (TyAlign > 8)
1579       return TyAlign;
1580     return 8;
1581   }
1582
1583   unsigned Align = 4;
1584   if (Subtarget->hasSSE1())
1585     getMaxByValAlign(Ty, Align);
1586   return Align;
1587 }
1588
1589 /// getOptimalMemOpType - Returns the target specific optimal type for load
1590 /// and store operations as a result of memset, memcpy, and memmove
1591 /// lowering. If DstAlign is zero that means it's safe to destination
1592 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1593 /// means there isn't a need to check it against alignment requirement,
1594 /// probably because the source does not need to be loaded. If 'IsMemset' is
1595 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1596 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1597 /// source is constant so it does not need to be loaded.
1598 /// It returns EVT::Other if the type should be determined using generic
1599 /// target-independent logic.
1600 EVT
1601 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1602                                        unsigned DstAlign, unsigned SrcAlign,
1603                                        bool IsMemset, bool ZeroMemset,
1604                                        bool MemcpyStrSrc,
1605                                        MachineFunction &MF) const {
1606   const Function *F = MF.getFunction();
1607   if ((!IsMemset || ZeroMemset) &&
1608       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1609                                        Attribute::NoImplicitFloat)) {
1610     if (Size >= 16 &&
1611         (Subtarget->isUnalignedMemAccessFast() ||
1612          ((DstAlign == 0 || DstAlign >= 16) &&
1613           (SrcAlign == 0 || SrcAlign >= 16)))) {
1614       if (Size >= 32) {
1615         if (Subtarget->hasInt256())
1616           return MVT::v8i32;
1617         if (Subtarget->hasFp256())
1618           return MVT::v8f32;
1619       }
1620       if (Subtarget->hasSSE2())
1621         return MVT::v4i32;
1622       if (Subtarget->hasSSE1())
1623         return MVT::v4f32;
1624     } else if (!MemcpyStrSrc && Size >= 8 &&
1625                !Subtarget->is64Bit() &&
1626                Subtarget->hasSSE2()) {
1627       // Do not use f64 to lower memcpy if source is string constant. It's
1628       // better to use i32 to avoid the loads.
1629       return MVT::f64;
1630     }
1631   }
1632   if (Subtarget->is64Bit() && Size >= 8)
1633     return MVT::i64;
1634   return MVT::i32;
1635 }
1636
1637 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1638   if (VT == MVT::f32)
1639     return X86ScalarSSEf32;
1640   else if (VT == MVT::f64)
1641     return X86ScalarSSEf64;
1642   return true;
1643 }
1644
1645 bool
1646 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1647   if (Fast)
1648     *Fast = Subtarget->isUnalignedMemAccessFast();
1649   return true;
1650 }
1651
1652 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1653 /// current function.  The returned value is a member of the
1654 /// MachineJumpTableInfo::JTEntryKind enum.
1655 unsigned X86TargetLowering::getJumpTableEncoding() const {
1656   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1657   // symbol.
1658   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1659       Subtarget->isPICStyleGOT())
1660     return MachineJumpTableInfo::EK_Custom32;
1661
1662   // Otherwise, use the normal jump table encoding heuristics.
1663   return TargetLowering::getJumpTableEncoding();
1664 }
1665
1666 const MCExpr *
1667 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1668                                              const MachineBasicBlock *MBB,
1669                                              unsigned uid,MCContext &Ctx) const{
1670   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1671          Subtarget->isPICStyleGOT());
1672   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1673   // entries.
1674   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1675                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1676 }
1677
1678 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1679 /// jumptable.
1680 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1681                                                     SelectionDAG &DAG) const {
1682   if (!Subtarget->is64Bit())
1683     // This doesn't have SDLoc associated with it, but is not really the
1684     // same as a Register.
1685     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1686   return Table;
1687 }
1688
1689 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1690 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1691 /// MCExpr.
1692 const MCExpr *X86TargetLowering::
1693 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1694                              MCContext &Ctx) const {
1695   // X86-64 uses RIP relative addressing based on the jump table label.
1696   if (Subtarget->isPICStyleRIPRel())
1697     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1698
1699   // Otherwise, the reference is relative to the PIC base.
1700   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1701 }
1702
1703 // FIXME: Why this routine is here? Move to RegInfo!
1704 std::pair<const TargetRegisterClass*, uint8_t>
1705 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1706   const TargetRegisterClass *RRC = 0;
1707   uint8_t Cost = 1;
1708   switch (VT.SimpleTy) {
1709   default:
1710     return TargetLowering::findRepresentativeClass(VT);
1711   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1712     RRC = Subtarget->is64Bit() ?
1713       (const TargetRegisterClass*)&X86::GR64RegClass :
1714       (const TargetRegisterClass*)&X86::GR32RegClass;
1715     break;
1716   case MVT::x86mmx:
1717     RRC = &X86::VR64RegClass;
1718     break;
1719   case MVT::f32: case MVT::f64:
1720   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1721   case MVT::v4f32: case MVT::v2f64:
1722   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1723   case MVT::v4f64:
1724     RRC = &X86::VR128RegClass;
1725     break;
1726   }
1727   return std::make_pair(RRC, Cost);
1728 }
1729
1730 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1731                                                unsigned &Offset) const {
1732   if (!Subtarget->isTargetLinux())
1733     return false;
1734
1735   if (Subtarget->is64Bit()) {
1736     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1737     Offset = 0x28;
1738     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1739       AddressSpace = 256;
1740     else
1741       AddressSpace = 257;
1742   } else {
1743     // %gs:0x14 on i386
1744     Offset = 0x14;
1745     AddressSpace = 256;
1746   }
1747   return true;
1748 }
1749
1750 //===----------------------------------------------------------------------===//
1751 //               Return Value Calling Convention Implementation
1752 //===----------------------------------------------------------------------===//
1753
1754 #include "X86GenCallingConv.inc"
1755
1756 bool
1757 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1758                                   MachineFunction &MF, bool isVarArg,
1759                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1760                         LLVMContext &Context) const {
1761   SmallVector<CCValAssign, 16> RVLocs;
1762   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1763                  RVLocs, Context);
1764   return CCInfo.CheckReturn(Outs, RetCC_X86);
1765 }
1766
1767 SDValue
1768 X86TargetLowering::LowerReturn(SDValue Chain,
1769                                CallingConv::ID CallConv, bool isVarArg,
1770                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1771                                const SmallVectorImpl<SDValue> &OutVals,
1772                                SDLoc dl, SelectionDAG &DAG) const {
1773   MachineFunction &MF = DAG.getMachineFunction();
1774   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1775
1776   SmallVector<CCValAssign, 16> RVLocs;
1777   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1778                  RVLocs, *DAG.getContext());
1779   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1780
1781   SDValue Flag;
1782   SmallVector<SDValue, 6> RetOps;
1783   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1784   // Operand #1 = Bytes To Pop
1785   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1786                    MVT::i16));
1787
1788   // Copy the result values into the output registers.
1789   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1790     CCValAssign &VA = RVLocs[i];
1791     assert(VA.isRegLoc() && "Can only return in registers!");
1792     SDValue ValToCopy = OutVals[i];
1793     EVT ValVT = ValToCopy.getValueType();
1794
1795     // Promote values to the appropriate types
1796     if (VA.getLocInfo() == CCValAssign::SExt)
1797       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1798     else if (VA.getLocInfo() == CCValAssign::ZExt)
1799       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1800     else if (VA.getLocInfo() == CCValAssign::AExt)
1801       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1802     else if (VA.getLocInfo() == CCValAssign::BCvt)
1803       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1804
1805     // If this is x86-64, and we disabled SSE, we can't return FP values,
1806     // or SSE or MMX vectors.
1807     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1808          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1809           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1810       report_fatal_error("SSE register return with SSE disabled");
1811     }
1812     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1813     // llvm-gcc has never done it right and no one has noticed, so this
1814     // should be OK for now.
1815     if (ValVT == MVT::f64 &&
1816         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1817       report_fatal_error("SSE2 register return with SSE2 disabled");
1818
1819     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1820     // the RET instruction and handled by the FP Stackifier.
1821     if (VA.getLocReg() == X86::ST0 ||
1822         VA.getLocReg() == X86::ST1) {
1823       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1824       // change the value to the FP stack register class.
1825       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1826         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1827       RetOps.push_back(ValToCopy);
1828       // Don't emit a copytoreg.
1829       continue;
1830     }
1831
1832     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1833     // which is returned in RAX / RDX.
1834     if (Subtarget->is64Bit()) {
1835       if (ValVT == MVT::x86mmx) {
1836         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1837           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1838           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1839                                   ValToCopy);
1840           // If we don't have SSE2 available, convert to v4f32 so the generated
1841           // register is legal.
1842           if (!Subtarget->hasSSE2())
1843             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1844         }
1845       }
1846     }
1847
1848     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1849     Flag = Chain.getValue(1);
1850     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1851   }
1852
1853   // The x86-64 ABIs require that for returning structs by value we copy
1854   // the sret argument into %rax/%eax (depending on ABI) for the return.
1855   // Win32 requires us to put the sret argument to %eax as well.
1856   // We saved the argument into a virtual register in the entry block,
1857   // so now we copy the value out and into %rax/%eax.
1858   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1859       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1860     MachineFunction &MF = DAG.getMachineFunction();
1861     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1862     unsigned Reg = FuncInfo->getSRetReturnReg();
1863     assert(Reg &&
1864            "SRetReturnReg should have been set in LowerFormalArguments().");
1865     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1866
1867     unsigned RetValReg
1868         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1869           X86::RAX : X86::EAX;
1870     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1871     Flag = Chain.getValue(1);
1872
1873     // RAX/EAX now acts like a return value.
1874     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1875   }
1876
1877   RetOps[0] = Chain;  // Update chain.
1878
1879   // Add the flag if we have it.
1880   if (Flag.getNode())
1881     RetOps.push_back(Flag);
1882
1883   return DAG.getNode(X86ISD::RET_FLAG, dl,
1884                      MVT::Other, &RetOps[0], RetOps.size());
1885 }
1886
1887 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1888   if (N->getNumValues() != 1)
1889     return false;
1890   if (!N->hasNUsesOfValue(1, 0))
1891     return false;
1892
1893   SDValue TCChain = Chain;
1894   SDNode *Copy = *N->use_begin();
1895   if (Copy->getOpcode() == ISD::CopyToReg) {
1896     // If the copy has a glue operand, we conservatively assume it isn't safe to
1897     // perform a tail call.
1898     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1899       return false;
1900     TCChain = Copy->getOperand(0);
1901   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1902     return false;
1903
1904   bool HasRet = false;
1905   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1906        UI != UE; ++UI) {
1907     if (UI->getOpcode() != X86ISD::RET_FLAG)
1908       return false;
1909     HasRet = true;
1910   }
1911
1912   if (!HasRet)
1913     return false;
1914
1915   Chain = TCChain;
1916   return true;
1917 }
1918
1919 MVT
1920 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1921                                             ISD::NodeType ExtendKind) const {
1922   MVT ReturnMVT;
1923   // TODO: Is this also valid on 32-bit?
1924   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1925     ReturnMVT = MVT::i8;
1926   else
1927     ReturnMVT = MVT::i32;
1928
1929   MVT MinVT = getRegisterType(ReturnMVT);
1930   return VT.bitsLT(MinVT) ? MinVT : VT;
1931 }
1932
1933 /// LowerCallResult - Lower the result values of a call into the
1934 /// appropriate copies out of appropriate physical registers.
1935 ///
1936 SDValue
1937 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1938                                    CallingConv::ID CallConv, bool isVarArg,
1939                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1940                                    SDLoc dl, SelectionDAG &DAG,
1941                                    SmallVectorImpl<SDValue> &InVals) const {
1942
1943   // Assign locations to each value returned by this call.
1944   SmallVector<CCValAssign, 16> RVLocs;
1945   bool Is64Bit = Subtarget->is64Bit();
1946   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1947                  getTargetMachine(), RVLocs, *DAG.getContext());
1948   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1949
1950   // Copy all of the result registers out of their specified physreg.
1951   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1952     CCValAssign &VA = RVLocs[i];
1953     EVT CopyVT = VA.getValVT();
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values
1956     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1957         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1958       report_fatal_error("SSE register return with SSE disabled");
1959     }
1960
1961     SDValue Val;
1962
1963     // If this is a call to a function that returns an fp value on the floating
1964     // point stack, we must guarantee the value is popped from the stack, so
1965     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1966     // if the return value is not used. We use the FpPOP_RETVAL instruction
1967     // instead.
1968     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1969       // If we prefer to use the value in xmm registers, copy it out as f80 and
1970       // use a truncate to move it from fp stack reg to xmm reg.
1971       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1972       SDValue Ops[] = { Chain, InFlag };
1973       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1974                                          MVT::Other, MVT::Glue, Ops), 1);
1975       Val = Chain.getValue(0);
1976
1977       // Round the f80 to the right size, which also moves it to the appropriate
1978       // xmm register.
1979       if (CopyVT != VA.getValVT())
1980         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1981                           // This truncation won't change the value.
1982                           DAG.getIntPtrConstant(1));
1983     } else {
1984       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1985                                  CopyVT, InFlag).getValue(1);
1986       Val = Chain.getValue(0);
1987     }
1988     InFlag = Chain.getValue(2);
1989     InVals.push_back(Val);
1990   }
1991
1992   return Chain;
1993 }
1994
1995 //===----------------------------------------------------------------------===//
1996 //                C & StdCall & Fast Calling Convention implementation
1997 //===----------------------------------------------------------------------===//
1998 //  StdCall calling convention seems to be standard for many Windows' API
1999 //  routines and around. It differs from C calling convention just a little:
2000 //  callee should clean up the stack, not caller. Symbols should be also
2001 //  decorated in some fancy way :) It doesn't support any vector arguments.
2002 //  For info on fast calling convention see Fast Calling Convention (tail call)
2003 //  implementation LowerX86_32FastCCCallTo.
2004
2005 /// CallIsStructReturn - Determines whether a call uses struct return
2006 /// semantics.
2007 enum StructReturnType {
2008   NotStructReturn,
2009   RegStructReturn,
2010   StackStructReturn
2011 };
2012 static StructReturnType
2013 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2014   if (Outs.empty())
2015     return NotStructReturn;
2016
2017   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2018   if (!Flags.isSRet())
2019     return NotStructReturn;
2020   if (Flags.isInReg())
2021     return RegStructReturn;
2022   return StackStructReturn;
2023 }
2024
2025 /// ArgsAreStructReturn - Determines whether a function uses struct
2026 /// return semantics.
2027 static StructReturnType
2028 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2029   if (Ins.empty())
2030     return NotStructReturn;
2031
2032   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2033   if (!Flags.isSRet())
2034     return NotStructReturn;
2035   if (Flags.isInReg())
2036     return RegStructReturn;
2037   return StackStructReturn;
2038 }
2039
2040 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2041 /// by "Src" to address "Dst" with size and alignment information specified by
2042 /// the specific parameter attribute. The copy will be passed as a byval
2043 /// function parameter.
2044 static SDValue
2045 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2046                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2047                           SDLoc dl) {
2048   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2049
2050   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2051                        /*isVolatile*/false, /*AlwaysInline=*/true,
2052                        MachinePointerInfo(), MachinePointerInfo());
2053 }
2054
2055 /// IsTailCallConvention - Return true if the calling convention is one that
2056 /// supports tail call optimization.
2057 static bool IsTailCallConvention(CallingConv::ID CC) {
2058   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2059           CC == CallingConv::HiPE);
2060 }
2061
2062 /// \brief Return true if the calling convention is a C calling convention.
2063 static bool IsCCallConvention(CallingConv::ID CC) {
2064   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2065           CC == CallingConv::X86_64_SysV);
2066 }
2067
2068 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2069   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2070     return false;
2071
2072   CallSite CS(CI);
2073   CallingConv::ID CalleeCC = CS.getCallingConv();
2074   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2075     return false;
2076
2077   return true;
2078 }
2079
2080 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2081 /// a tailcall target by changing its ABI.
2082 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2083                                    bool GuaranteedTailCallOpt) {
2084   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2085 }
2086
2087 SDValue
2088 X86TargetLowering::LowerMemArgument(SDValue Chain,
2089                                     CallingConv::ID CallConv,
2090                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2091                                     SDLoc dl, SelectionDAG &DAG,
2092                                     const CCValAssign &VA,
2093                                     MachineFrameInfo *MFI,
2094                                     unsigned i) const {
2095   // Create the nodes corresponding to a load from this parameter slot.
2096   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2097   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2098                               getTargetMachine().Options.GuaranteedTailCallOpt);
2099   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2100   EVT ValVT;
2101
2102   // If value is passed by pointer we have address passed instead of the value
2103   // itself.
2104   if (VA.getLocInfo() == CCValAssign::Indirect)
2105     ValVT = VA.getLocVT();
2106   else
2107     ValVT = VA.getValVT();
2108
2109   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2110   // changed with more analysis.
2111   // In case of tail call optimization mark all arguments mutable. Since they
2112   // could be overwritten by lowering of arguments in case of a tail call.
2113   if (Flags.isByVal()) {
2114     unsigned Bytes = Flags.getByValSize();
2115     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2116     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2117     return DAG.getFrameIndex(FI, getPointerTy());
2118   } else {
2119     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2120                                     VA.getLocMemOffset(), isImmutable);
2121     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2122     return DAG.getLoad(ValVT, dl, Chain, FIN,
2123                        MachinePointerInfo::getFixedStack(FI),
2124                        false, false, false, 0);
2125   }
2126 }
2127
2128 SDValue
2129 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2130                                         CallingConv::ID CallConv,
2131                                         bool isVarArg,
2132                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2133                                         SDLoc dl,
2134                                         SelectionDAG &DAG,
2135                                         SmallVectorImpl<SDValue> &InVals)
2136                                           const {
2137   MachineFunction &MF = DAG.getMachineFunction();
2138   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2139
2140   const Function* Fn = MF.getFunction();
2141   if (Fn->hasExternalLinkage() &&
2142       Subtarget->isTargetCygMing() &&
2143       Fn->getName() == "main")
2144     FuncInfo->setForceFramePointer(true);
2145
2146   MachineFrameInfo *MFI = MF.getFrameInfo();
2147   bool Is64Bit = Subtarget->is64Bit();
2148   bool IsWindows = Subtarget->isTargetWindows();
2149   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2150
2151   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2152          "Var args not supported with calling convention fastcc, ghc or hipe");
2153
2154   // Assign locations to all of the incoming arguments.
2155   SmallVector<CCValAssign, 16> ArgLocs;
2156   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2157                  ArgLocs, *DAG.getContext());
2158
2159   // Allocate shadow area for Win64
2160   if (IsWin64)
2161     CCInfo.AllocateStack(32, 8);
2162
2163   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2164
2165   unsigned LastVal = ~0U;
2166   SDValue ArgValue;
2167   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2168     CCValAssign &VA = ArgLocs[i];
2169     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2170     // places.
2171     assert(VA.getValNo() != LastVal &&
2172            "Don't support value assigned to multiple locs yet");
2173     (void)LastVal;
2174     LastVal = VA.getValNo();
2175
2176     if (VA.isRegLoc()) {
2177       EVT RegVT = VA.getLocVT();
2178       const TargetRegisterClass *RC;
2179       if (RegVT == MVT::i32)
2180         RC = &X86::GR32RegClass;
2181       else if (Is64Bit && RegVT == MVT::i64)
2182         RC = &X86::GR64RegClass;
2183       else if (RegVT == MVT::f32)
2184         RC = &X86::FR32RegClass;
2185       else if (RegVT == MVT::f64)
2186         RC = &X86::FR64RegClass;
2187       else if (RegVT.is512BitVector())
2188         RC = &X86::VR512RegClass;
2189       else if (RegVT.is256BitVector())
2190         RC = &X86::VR256RegClass;
2191       else if (RegVT.is128BitVector())
2192         RC = &X86::VR128RegClass;
2193       else if (RegVT == MVT::x86mmx)
2194         RC = &X86::VR64RegClass;
2195       else if (RegVT == MVT::v8i1)
2196         RC = &X86::VK8RegClass;
2197       else if (RegVT == MVT::v16i1)
2198         RC = &X86::VK16RegClass;
2199       else
2200         llvm_unreachable("Unknown argument type!");
2201
2202       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2203       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2204
2205       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2206       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2207       // right size.
2208       if (VA.getLocInfo() == CCValAssign::SExt)
2209         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2210                                DAG.getValueType(VA.getValVT()));
2211       else if (VA.getLocInfo() == CCValAssign::ZExt)
2212         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::BCvt)
2215         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2216
2217       if (VA.isExtInLoc()) {
2218         // Handle MMX values passed in XMM regs.
2219         if (RegVT.isVector())
2220           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2221         else
2222           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2223       }
2224     } else {
2225       assert(VA.isMemLoc());
2226       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2227     }
2228
2229     // If value is passed via pointer - do a load.
2230     if (VA.getLocInfo() == CCValAssign::Indirect)
2231       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2232                              MachinePointerInfo(), false, false, false, 0);
2233
2234     InVals.push_back(ArgValue);
2235   }
2236
2237   // The x86-64 ABIs require that for returning structs by value we copy
2238   // the sret argument into %rax/%eax (depending on ABI) for the return.
2239   // Win32 requires us to put the sret argument to %eax as well.
2240   // Save the argument into a virtual register so that we can access it
2241   // from the return points.
2242   if (MF.getFunction()->hasStructRetAttr() &&
2243       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2244     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2245     unsigned Reg = FuncInfo->getSRetReturnReg();
2246     if (!Reg) {
2247       MVT PtrTy = getPointerTy();
2248       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2249       FuncInfo->setSRetReturnReg(Reg);
2250     }
2251     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2252     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2253   }
2254
2255   unsigned StackSize = CCInfo.getNextStackOffset();
2256   // Align stack specially for tail calls.
2257   if (FuncIsMadeTailCallSafe(CallConv,
2258                              MF.getTarget().Options.GuaranteedTailCallOpt))
2259     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2260
2261   // If the function takes variable number of arguments, make a frame index for
2262   // the start of the first vararg value... for expansion of llvm.va_start.
2263   if (isVarArg) {
2264     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2265                     CallConv != CallingConv::X86_ThisCall)) {
2266       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2267     }
2268     if (Is64Bit) {
2269       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2270
2271       // FIXME: We should really autogenerate these arrays
2272       static const uint16_t GPR64ArgRegsWin64[] = {
2273         X86::RCX, X86::RDX, X86::R8,  X86::R9
2274       };
2275       static const uint16_t GPR64ArgRegs64Bit[] = {
2276         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2277       };
2278       static const uint16_t XMMArgRegs64Bit[] = {
2279         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2280         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2281       };
2282       const uint16_t *GPR64ArgRegs;
2283       unsigned NumXMMRegs = 0;
2284
2285       if (IsWin64) {
2286         // The XMM registers which might contain var arg parameters are shadowed
2287         // in their paired GPR.  So we only need to save the GPR to their home
2288         // slots.
2289         TotalNumIntRegs = 4;
2290         GPR64ArgRegs = GPR64ArgRegsWin64;
2291       } else {
2292         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2293         GPR64ArgRegs = GPR64ArgRegs64Bit;
2294
2295         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2296                                                 TotalNumXMMRegs);
2297       }
2298       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2299                                                        TotalNumIntRegs);
2300
2301       bool NoImplicitFloatOps = Fn->getAttributes().
2302         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2303       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2304              "SSE register cannot be used when SSE is disabled!");
2305       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2306                NoImplicitFloatOps) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2309           !Subtarget->hasSSE1())
2310         // Kernel mode asks for SSE to be disabled, so don't push them
2311         // on the stack.
2312         TotalNumXMMRegs = 0;
2313
2314       if (IsWin64) {
2315         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2316         // Get to the caller-allocated home save location.  Add 8 to account
2317         // for the return address.
2318         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2319         FuncInfo->setRegSaveFrameIndex(
2320           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2321         // Fixup to set vararg frame on shadow area (4 x i64).
2322         if (NumIntRegs < 4)
2323           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2324       } else {
2325         // For X86-64, if there are vararg parameters that are passed via
2326         // registers, then we must store them to their spots on the stack so
2327         // they may be loaded by deferencing the result of va_next.
2328         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2329         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2330         FuncInfo->setRegSaveFrameIndex(
2331           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2332                                false));
2333       }
2334
2335       // Store the integer parameter registers.
2336       SmallVector<SDValue, 8> MemOps;
2337       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2338                                         getPointerTy());
2339       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2340       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2341         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2342                                   DAG.getIntPtrConstant(Offset));
2343         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2344                                      &X86::GR64RegClass);
2345         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2346         SDValue Store =
2347           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2348                        MachinePointerInfo::getFixedStack(
2349                          FuncInfo->getRegSaveFrameIndex(), Offset),
2350                        false, false, 0);
2351         MemOps.push_back(Store);
2352         Offset += 8;
2353       }
2354
2355       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2356         // Now store the XMM (fp + vector) parameter registers.
2357         SmallVector<SDValue, 11> SaveXMMOps;
2358         SaveXMMOps.push_back(Chain);
2359
2360         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2361         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2362         SaveXMMOps.push_back(ALVal);
2363
2364         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2365                                FuncInfo->getRegSaveFrameIndex()));
2366         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2367                                FuncInfo->getVarArgsFPOffset()));
2368
2369         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2370           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2371                                        &X86::VR128RegClass);
2372           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2373           SaveXMMOps.push_back(Val);
2374         }
2375         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2376                                      MVT::Other,
2377                                      &SaveXMMOps[0], SaveXMMOps.size()));
2378       }
2379
2380       if (!MemOps.empty())
2381         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2382                             &MemOps[0], MemOps.size());
2383     }
2384   }
2385
2386   // Some CCs need callee pop.
2387   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2388                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2389     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2390   } else {
2391     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2392     // If this is an sret function, the return should pop the hidden pointer.
2393     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2394         argsAreStructReturn(Ins) == StackStructReturn)
2395       FuncInfo->setBytesToPopOnReturn(4);
2396   }
2397
2398   if (!Is64Bit) {
2399     // RegSaveFrameIndex is X86-64 only.
2400     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2401     if (CallConv == CallingConv::X86_FastCall ||
2402         CallConv == CallingConv::X86_ThisCall)
2403       // fastcc functions can't have varargs.
2404       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2405   }
2406
2407   FuncInfo->setArgumentStackSize(StackSize);
2408
2409   return Chain;
2410 }
2411
2412 SDValue
2413 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2414                                     SDValue StackPtr, SDValue Arg,
2415                                     SDLoc dl, SelectionDAG &DAG,
2416                                     const CCValAssign &VA,
2417                                     ISD::ArgFlagsTy Flags) const {
2418   unsigned LocMemOffset = VA.getLocMemOffset();
2419   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2420   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2421   if (Flags.isByVal())
2422     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2423
2424   return DAG.getStore(Chain, dl, Arg, PtrOff,
2425                       MachinePointerInfo::getStack(LocMemOffset),
2426                       false, false, 0);
2427 }
2428
2429 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2430 /// optimization is performed and it is required.
2431 SDValue
2432 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2433                                            SDValue &OutRetAddr, SDValue Chain,
2434                                            bool IsTailCall, bool Is64Bit,
2435                                            int FPDiff, SDLoc dl) const {
2436   // Adjust the Return address stack slot.
2437   EVT VT = getPointerTy();
2438   OutRetAddr = getReturnAddressFrameIndex(DAG);
2439
2440   // Load the "old" Return address.
2441   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2442                            false, false, false, 0);
2443   return SDValue(OutRetAddr.getNode(), 1);
2444 }
2445
2446 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2447 /// optimization is performed and it is required (FPDiff!=0).
2448 static SDValue
2449 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2450                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2451                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2452   // Store the return address to the appropriate stack slot.
2453   if (!FPDiff) return Chain;
2454   // Calculate the new stack slot for the return address.
2455   int NewReturnAddrFI =
2456     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2457   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2458   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2459                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2460                        false, false, 0);
2461   return Chain;
2462 }
2463
2464 SDValue
2465 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2466                              SmallVectorImpl<SDValue> &InVals) const {
2467   SelectionDAG &DAG                     = CLI.DAG;
2468   SDLoc &dl                             = CLI.DL;
2469   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2470   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2471   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2472   SDValue Chain                         = CLI.Chain;
2473   SDValue Callee                        = CLI.Callee;
2474   CallingConv::ID CallConv              = CLI.CallConv;
2475   bool &isTailCall                      = CLI.IsTailCall;
2476   bool isVarArg                         = CLI.IsVarArg;
2477
2478   MachineFunction &MF = DAG.getMachineFunction();
2479   bool Is64Bit        = Subtarget->is64Bit();
2480   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2481   bool IsWindows      = Subtarget->isTargetWindows();
2482   StructReturnType SR = callIsStructReturn(Outs);
2483   bool IsSibcall      = false;
2484
2485   if (MF.getTarget().Options.DisableTailCalls)
2486     isTailCall = false;
2487
2488   if (isTailCall) {
2489     // Check if it's really possible to do a tail call.
2490     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2491                     isVarArg, SR != NotStructReturn,
2492                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2493                     Outs, OutVals, Ins, DAG);
2494
2495     // Sibcalls are automatically detected tailcalls which do not require
2496     // ABI changes.
2497     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2498       IsSibcall = true;
2499
2500     if (isTailCall)
2501       ++NumTailCalls;
2502   }
2503
2504   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2505          "Var args not supported with calling convention fastcc, ghc or hipe");
2506
2507   // Analyze operands of the call, assigning locations to each operand.
2508   SmallVector<CCValAssign, 16> ArgLocs;
2509   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2510                  ArgLocs, *DAG.getContext());
2511
2512   // Allocate shadow area for Win64
2513   if (IsWin64)
2514     CCInfo.AllocateStack(32, 8);
2515
2516   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2517
2518   // Get a count of how many bytes are to be pushed on the stack.
2519   unsigned NumBytes = CCInfo.getNextStackOffset();
2520   if (IsSibcall)
2521     // This is a sibcall. The memory operands are available in caller's
2522     // own caller's stack.
2523     NumBytes = 0;
2524   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2525            IsTailCallConvention(CallConv))
2526     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2527
2528   int FPDiff = 0;
2529   if (isTailCall && !IsSibcall) {
2530     // Lower arguments at fp - stackoffset + fpdiff.
2531     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2532     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2533
2534     FPDiff = NumBytesCallerPushed - NumBytes;
2535
2536     // Set the delta of movement of the returnaddr stackslot.
2537     // But only set if delta is greater than previous delta.
2538     if (FPDiff < X86Info->getTCReturnAddrDelta())
2539       X86Info->setTCReturnAddrDelta(FPDiff);
2540   }
2541
2542   if (!IsSibcall)
2543     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2544                                  dl);
2545
2546   SDValue RetAddrFrIdx;
2547   // Load return address for tail calls.
2548   if (isTailCall && FPDiff)
2549     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2550                                     Is64Bit, FPDiff, dl);
2551
2552   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2553   SmallVector<SDValue, 8> MemOpChains;
2554   SDValue StackPtr;
2555
2556   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2557   // of tail call optimization arguments are handle later.
2558   const X86RegisterInfo *RegInfo =
2559     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2560   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2561     CCValAssign &VA = ArgLocs[i];
2562     EVT RegVT = VA.getLocVT();
2563     SDValue Arg = OutVals[i];
2564     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2565     bool isByVal = Flags.isByVal();
2566
2567     // Promote the value if needed.
2568     switch (VA.getLocInfo()) {
2569     default: llvm_unreachable("Unknown loc info!");
2570     case CCValAssign::Full: break;
2571     case CCValAssign::SExt:
2572       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2573       break;
2574     case CCValAssign::ZExt:
2575       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2576       break;
2577     case CCValAssign::AExt:
2578       if (RegVT.is128BitVector()) {
2579         // Special case: passing MMX values in XMM registers.
2580         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2581         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2582         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2583       } else
2584         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2585       break;
2586     case CCValAssign::BCvt:
2587       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2588       break;
2589     case CCValAssign::Indirect: {
2590       // Store the argument.
2591       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2592       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2593       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2594                            MachinePointerInfo::getFixedStack(FI),
2595                            false, false, 0);
2596       Arg = SpillSlot;
2597       break;
2598     }
2599     }
2600
2601     if (VA.isRegLoc()) {
2602       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2603       if (isVarArg && IsWin64) {
2604         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2605         // shadow reg if callee is a varargs function.
2606         unsigned ShadowReg = 0;
2607         switch (VA.getLocReg()) {
2608         case X86::XMM0: ShadowReg = X86::RCX; break;
2609         case X86::XMM1: ShadowReg = X86::RDX; break;
2610         case X86::XMM2: ShadowReg = X86::R8; break;
2611         case X86::XMM3: ShadowReg = X86::R9; break;
2612         }
2613         if (ShadowReg)
2614           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2615       }
2616     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2617       assert(VA.isMemLoc());
2618       if (StackPtr.getNode() == 0)
2619         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2620                                       getPointerTy());
2621       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2622                                              dl, DAG, VA, Flags));
2623     }
2624   }
2625
2626   if (!MemOpChains.empty())
2627     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2628                         &MemOpChains[0], MemOpChains.size());
2629
2630   if (Subtarget->isPICStyleGOT()) {
2631     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2632     // GOT pointer.
2633     if (!isTailCall) {
2634       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2635                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2636     } else {
2637       // If we are tail calling and generating PIC/GOT style code load the
2638       // address of the callee into ECX. The value in ecx is used as target of
2639       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2640       // for tail calls on PIC/GOT architectures. Normally we would just put the
2641       // address of GOT into ebx and then call target@PLT. But for tail calls
2642       // ebx would be restored (since ebx is callee saved) before jumping to the
2643       // target@PLT.
2644
2645       // Note: The actual moving to ECX is done further down.
2646       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2647       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2648           !G->getGlobal()->hasProtectedVisibility())
2649         Callee = LowerGlobalAddress(Callee, DAG);
2650       else if (isa<ExternalSymbolSDNode>(Callee))
2651         Callee = LowerExternalSymbol(Callee, DAG);
2652     }
2653   }
2654
2655   if (Is64Bit && isVarArg && !IsWin64) {
2656     // From AMD64 ABI document:
2657     // For calls that may call functions that use varargs or stdargs
2658     // (prototype-less calls or calls to functions containing ellipsis (...) in
2659     // the declaration) %al is used as hidden argument to specify the number
2660     // of SSE registers used. The contents of %al do not need to match exactly
2661     // the number of registers, but must be an ubound on the number of SSE
2662     // registers used and is in the range 0 - 8 inclusive.
2663
2664     // Count the number of XMM registers allocated.
2665     static const uint16_t XMMArgRegs[] = {
2666       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2667       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2668     };
2669     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2670     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2671            && "SSE registers cannot be used when SSE is disabled");
2672
2673     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2674                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2675   }
2676
2677   // For tail calls lower the arguments to the 'real' stack slot.
2678   if (isTailCall) {
2679     // Force all the incoming stack arguments to be loaded from the stack
2680     // before any new outgoing arguments are stored to the stack, because the
2681     // outgoing stack slots may alias the incoming argument stack slots, and
2682     // the alias isn't otherwise explicit. This is slightly more conservative
2683     // than necessary, because it means that each store effectively depends
2684     // on every argument instead of just those arguments it would clobber.
2685     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2686
2687     SmallVector<SDValue, 8> MemOpChains2;
2688     SDValue FIN;
2689     int FI = 0;
2690     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2691       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2692         CCValAssign &VA = ArgLocs[i];
2693         if (VA.isRegLoc())
2694           continue;
2695         assert(VA.isMemLoc());
2696         SDValue Arg = OutVals[i];
2697         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2698         // Create frame index.
2699         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2700         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2701         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2702         FIN = DAG.getFrameIndex(FI, getPointerTy());
2703
2704         if (Flags.isByVal()) {
2705           // Copy relative to framepointer.
2706           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2707           if (StackPtr.getNode() == 0)
2708             StackPtr = DAG.getCopyFromReg(Chain, dl,
2709                                           RegInfo->getStackRegister(),
2710                                           getPointerTy());
2711           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2712
2713           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2714                                                            ArgChain,
2715                                                            Flags, DAG, dl));
2716         } else {
2717           // Store relative to framepointer.
2718           MemOpChains2.push_back(
2719             DAG.getStore(ArgChain, dl, Arg, FIN,
2720                          MachinePointerInfo::getFixedStack(FI),
2721                          false, false, 0));
2722         }
2723       }
2724     }
2725
2726     if (!MemOpChains2.empty())
2727       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2728                           &MemOpChains2[0], MemOpChains2.size());
2729
2730     // Store the return address to the appropriate stack slot.
2731     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2732                                      getPointerTy(), RegInfo->getSlotSize(),
2733                                      FPDiff, dl);
2734   }
2735
2736   // Build a sequence of copy-to-reg nodes chained together with token chain
2737   // and flag operands which copy the outgoing args into registers.
2738   SDValue InFlag;
2739   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2740     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2741                              RegsToPass[i].second, InFlag);
2742     InFlag = Chain.getValue(1);
2743   }
2744
2745   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2746     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2747     // In the 64-bit large code model, we have to make all calls
2748     // through a register, since the call instruction's 32-bit
2749     // pc-relative offset may not be large enough to hold the whole
2750     // address.
2751   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2752     // If the callee is a GlobalAddress node (quite common, every direct call
2753     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2754     // it.
2755
2756     // We should use extra load for direct calls to dllimported functions in
2757     // non-JIT mode.
2758     const GlobalValue *GV = G->getGlobal();
2759     if (!GV->hasDLLImportLinkage()) {
2760       unsigned char OpFlags = 0;
2761       bool ExtraLoad = false;
2762       unsigned WrapperKind = ISD::DELETED_NODE;
2763
2764       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2765       // external symbols most go through the PLT in PIC mode.  If the symbol
2766       // has hidden or protected visibility, or if it is static or local, then
2767       // we don't need to use the PLT - we can directly call it.
2768       if (Subtarget->isTargetELF() &&
2769           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2770           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2771         OpFlags = X86II::MO_PLT;
2772       } else if (Subtarget->isPICStyleStubAny() &&
2773                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2774                  (!Subtarget->getTargetTriple().isMacOSX() ||
2775                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2776         // PC-relative references to external symbols should go through $stub,
2777         // unless we're building with the leopard linker or later, which
2778         // automatically synthesizes these stubs.
2779         OpFlags = X86II::MO_DARWIN_STUB;
2780       } else if (Subtarget->isPICStyleRIPRel() &&
2781                  isa<Function>(GV) &&
2782                  cast<Function>(GV)->getAttributes().
2783                    hasAttribute(AttributeSet::FunctionIndex,
2784                                 Attribute::NonLazyBind)) {
2785         // If the function is marked as non-lazy, generate an indirect call
2786         // which loads from the GOT directly. This avoids runtime overhead
2787         // at the cost of eager binding (and one extra byte of encoding).
2788         OpFlags = X86II::MO_GOTPCREL;
2789         WrapperKind = X86ISD::WrapperRIP;
2790         ExtraLoad = true;
2791       }
2792
2793       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2794                                           G->getOffset(), OpFlags);
2795
2796       // Add a wrapper if needed.
2797       if (WrapperKind != ISD::DELETED_NODE)
2798         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2799       // Add extra indirection if needed.
2800       if (ExtraLoad)
2801         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2802                              MachinePointerInfo::getGOT(),
2803                              false, false, false, 0);
2804     }
2805   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2806     unsigned char OpFlags = 0;
2807
2808     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2809     // external symbols should go through the PLT.
2810     if (Subtarget->isTargetELF() &&
2811         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2812       OpFlags = X86II::MO_PLT;
2813     } else if (Subtarget->isPICStyleStubAny() &&
2814                (!Subtarget->getTargetTriple().isMacOSX() ||
2815                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2816       // PC-relative references to external symbols should go through $stub,
2817       // unless we're building with the leopard linker or later, which
2818       // automatically synthesizes these stubs.
2819       OpFlags = X86II::MO_DARWIN_STUB;
2820     }
2821
2822     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2823                                          OpFlags);
2824   }
2825
2826   // Returns a chain & a flag for retval copy to use.
2827   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2828   SmallVector<SDValue, 8> Ops;
2829
2830   if (!IsSibcall && isTailCall) {
2831     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2832                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2833     InFlag = Chain.getValue(1);
2834   }
2835
2836   Ops.push_back(Chain);
2837   Ops.push_back(Callee);
2838
2839   if (isTailCall)
2840     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2841
2842   // Add argument registers to the end of the list so that they are known live
2843   // into the call.
2844   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2845     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2846                                   RegsToPass[i].second.getValueType()));
2847
2848   // Add a register mask operand representing the call-preserved registers.
2849   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2850   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2851   assert(Mask && "Missing call preserved mask for calling convention");
2852   Ops.push_back(DAG.getRegisterMask(Mask));
2853
2854   if (InFlag.getNode())
2855     Ops.push_back(InFlag);
2856
2857   if (isTailCall) {
2858     // We used to do:
2859     //// If this is the first return lowered for this function, add the regs
2860     //// to the liveout set for the function.
2861     // This isn't right, although it's probably harmless on x86; liveouts
2862     // should be computed from returns not tail calls.  Consider a void
2863     // function making a tail call to a function returning int.
2864     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2865   }
2866
2867   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2868   InFlag = Chain.getValue(1);
2869
2870   // Create the CALLSEQ_END node.
2871   unsigned NumBytesForCalleeToPush;
2872   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2873                        getTargetMachine().Options.GuaranteedTailCallOpt))
2874     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2875   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2876            SR == StackStructReturn)
2877     // If this is a call to a struct-return function, the callee
2878     // pops the hidden struct pointer, so we have to push it back.
2879     // This is common for Darwin/X86, Linux & Mingw32 targets.
2880     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2881     NumBytesForCalleeToPush = 4;
2882   else
2883     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2884
2885   // Returns a flag for retval copy to use.
2886   if (!IsSibcall) {
2887     Chain = DAG.getCALLSEQ_END(Chain,
2888                                DAG.getIntPtrConstant(NumBytes, true),
2889                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2890                                                      true),
2891                                InFlag, dl);
2892     InFlag = Chain.getValue(1);
2893   }
2894
2895   // Handle result values, copying them out of physregs into vregs that we
2896   // return.
2897   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2898                          Ins, dl, DAG, InVals);
2899 }
2900
2901 //===----------------------------------------------------------------------===//
2902 //                Fast Calling Convention (tail call) implementation
2903 //===----------------------------------------------------------------------===//
2904
2905 //  Like std call, callee cleans arguments, convention except that ECX is
2906 //  reserved for storing the tail called function address. Only 2 registers are
2907 //  free for argument passing (inreg). Tail call optimization is performed
2908 //  provided:
2909 //                * tailcallopt is enabled
2910 //                * caller/callee are fastcc
2911 //  On X86_64 architecture with GOT-style position independent code only local
2912 //  (within module) calls are supported at the moment.
2913 //  To keep the stack aligned according to platform abi the function
2914 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2915 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2916 //  If a tail called function callee has more arguments than the caller the
2917 //  caller needs to make sure that there is room to move the RETADDR to. This is
2918 //  achieved by reserving an area the size of the argument delta right after the
2919 //  original REtADDR, but before the saved framepointer or the spilled registers
2920 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2921 //  stack layout:
2922 //    arg1
2923 //    arg2
2924 //    RETADDR
2925 //    [ new RETADDR
2926 //      move area ]
2927 //    (possible EBP)
2928 //    ESI
2929 //    EDI
2930 //    local1 ..
2931
2932 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2933 /// for a 16 byte align requirement.
2934 unsigned
2935 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2936                                                SelectionDAG& DAG) const {
2937   MachineFunction &MF = DAG.getMachineFunction();
2938   const TargetMachine &TM = MF.getTarget();
2939   const X86RegisterInfo *RegInfo =
2940     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2941   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2942   unsigned StackAlignment = TFI.getStackAlignment();
2943   uint64_t AlignMask = StackAlignment - 1;
2944   int64_t Offset = StackSize;
2945   unsigned SlotSize = RegInfo->getSlotSize();
2946   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2947     // Number smaller than 12 so just add the difference.
2948     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2949   } else {
2950     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2951     Offset = ((~AlignMask) & Offset) + StackAlignment +
2952       (StackAlignment-SlotSize);
2953   }
2954   return Offset;
2955 }
2956
2957 /// MatchingStackOffset - Return true if the given stack call argument is
2958 /// already available in the same position (relatively) of the caller's
2959 /// incoming argument stack.
2960 static
2961 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2962                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2963                          const X86InstrInfo *TII) {
2964   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2965   int FI = INT_MAX;
2966   if (Arg.getOpcode() == ISD::CopyFromReg) {
2967     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2968     if (!TargetRegisterInfo::isVirtualRegister(VR))
2969       return false;
2970     MachineInstr *Def = MRI->getVRegDef(VR);
2971     if (!Def)
2972       return false;
2973     if (!Flags.isByVal()) {
2974       if (!TII->isLoadFromStackSlot(Def, FI))
2975         return false;
2976     } else {
2977       unsigned Opcode = Def->getOpcode();
2978       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2979           Def->getOperand(1).isFI()) {
2980         FI = Def->getOperand(1).getIndex();
2981         Bytes = Flags.getByValSize();
2982       } else
2983         return false;
2984     }
2985   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2986     if (Flags.isByVal())
2987       // ByVal argument is passed in as a pointer but it's now being
2988       // dereferenced. e.g.
2989       // define @foo(%struct.X* %A) {
2990       //   tail call @bar(%struct.X* byval %A)
2991       // }
2992       return false;
2993     SDValue Ptr = Ld->getBasePtr();
2994     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2995     if (!FINode)
2996       return false;
2997     FI = FINode->getIndex();
2998   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2999     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3000     FI = FINode->getIndex();
3001     Bytes = Flags.getByValSize();
3002   } else
3003     return false;
3004
3005   assert(FI != INT_MAX);
3006   if (!MFI->isFixedObjectIndex(FI))
3007     return false;
3008   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3009 }
3010
3011 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3012 /// for tail call optimization. Targets which want to do tail call
3013 /// optimization should implement this function.
3014 bool
3015 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3016                                                      CallingConv::ID CalleeCC,
3017                                                      bool isVarArg,
3018                                                      bool isCalleeStructRet,
3019                                                      bool isCallerStructRet,
3020                                                      Type *RetTy,
3021                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3022                                     const SmallVectorImpl<SDValue> &OutVals,
3023                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3024                                                      SelectionDAG &DAG) const {
3025   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3026     return false;
3027
3028   // If -tailcallopt is specified, make fastcc functions tail-callable.
3029   const MachineFunction &MF = DAG.getMachineFunction();
3030   const Function *CallerF = MF.getFunction();
3031
3032   // If the function return type is x86_fp80 and the callee return type is not,
3033   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3034   // perform a tailcall optimization here.
3035   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3036     return false;
3037
3038   CallingConv::ID CallerCC = CallerF->getCallingConv();
3039   bool CCMatch = CallerCC == CalleeCC;
3040   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3041   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3042
3043   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3044     if (IsTailCallConvention(CalleeCC) && CCMatch)
3045       return true;
3046     return false;
3047   }
3048
3049   // Look for obvious safe cases to perform tail call optimization that do not
3050   // require ABI changes. This is what gcc calls sibcall.
3051
3052   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3053   // emit a special epilogue.
3054   const X86RegisterInfo *RegInfo =
3055     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3056   if (RegInfo->needsStackRealignment(MF))
3057     return false;
3058
3059   // Also avoid sibcall optimization if either caller or callee uses struct
3060   // return semantics.
3061   if (isCalleeStructRet || isCallerStructRet)
3062     return false;
3063
3064   // An stdcall caller is expected to clean up its arguments; the callee
3065   // isn't going to do that.
3066   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3067     return false;
3068
3069   // Do not sibcall optimize vararg calls unless all arguments are passed via
3070   // registers.
3071   if (isVarArg && !Outs.empty()) {
3072
3073     // Optimizing for varargs on Win64 is unlikely to be safe without
3074     // additional testing.
3075     if (IsCalleeWin64 || IsCallerWin64)
3076       return false;
3077
3078     SmallVector<CCValAssign, 16> ArgLocs;
3079     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3080                    getTargetMachine(), ArgLocs, *DAG.getContext());
3081
3082     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3083     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3084       if (!ArgLocs[i].isRegLoc())
3085         return false;
3086   }
3087
3088   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3089   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3090   // this into a sibcall.
3091   bool Unused = false;
3092   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3093     if (!Ins[i].Used) {
3094       Unused = true;
3095       break;
3096     }
3097   }
3098   if (Unused) {
3099     SmallVector<CCValAssign, 16> RVLocs;
3100     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3101                    getTargetMachine(), RVLocs, *DAG.getContext());
3102     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3103     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3104       CCValAssign &VA = RVLocs[i];
3105       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3106         return false;
3107     }
3108   }
3109
3110   // If the calling conventions do not match, then we'd better make sure the
3111   // results are returned in the same way as what the caller expects.
3112   if (!CCMatch) {
3113     SmallVector<CCValAssign, 16> RVLocs1;
3114     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3115                     getTargetMachine(), RVLocs1, *DAG.getContext());
3116     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3117
3118     SmallVector<CCValAssign, 16> RVLocs2;
3119     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3120                     getTargetMachine(), RVLocs2, *DAG.getContext());
3121     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3122
3123     if (RVLocs1.size() != RVLocs2.size())
3124       return false;
3125     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3126       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3127         return false;
3128       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3129         return false;
3130       if (RVLocs1[i].isRegLoc()) {
3131         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3132           return false;
3133       } else {
3134         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3135           return false;
3136       }
3137     }
3138   }
3139
3140   // If the callee takes no arguments then go on to check the results of the
3141   // call.
3142   if (!Outs.empty()) {
3143     // Check if stack adjustment is needed. For now, do not do this if any
3144     // argument is passed on the stack.
3145     SmallVector<CCValAssign, 16> ArgLocs;
3146     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3147                    getTargetMachine(), ArgLocs, *DAG.getContext());
3148
3149     // Allocate shadow area for Win64
3150     if (IsCalleeWin64)
3151       CCInfo.AllocateStack(32, 8);
3152
3153     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3154     if (CCInfo.getNextStackOffset()) {
3155       MachineFunction &MF = DAG.getMachineFunction();
3156       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3157         return false;
3158
3159       // Check if the arguments are already laid out in the right way as
3160       // the caller's fixed stack objects.
3161       MachineFrameInfo *MFI = MF.getFrameInfo();
3162       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3163       const X86InstrInfo *TII =
3164         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3165       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3166         CCValAssign &VA = ArgLocs[i];
3167         SDValue Arg = OutVals[i];
3168         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3169         if (VA.getLocInfo() == CCValAssign::Indirect)
3170           return false;
3171         if (!VA.isRegLoc()) {
3172           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3173                                    MFI, MRI, TII))
3174             return false;
3175         }
3176       }
3177     }
3178
3179     // If the tailcall address may be in a register, then make sure it's
3180     // possible to register allocate for it. In 32-bit, the call address can
3181     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3182     // callee-saved registers are restored. These happen to be the same
3183     // registers used to pass 'inreg' arguments so watch out for those.
3184     if (!Subtarget->is64Bit() &&
3185         ((!isa<GlobalAddressSDNode>(Callee) &&
3186           !isa<ExternalSymbolSDNode>(Callee)) ||
3187          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3188       unsigned NumInRegs = 0;
3189       // In PIC we need an extra register to formulate the address computation
3190       // for the callee.
3191       unsigned MaxInRegs =
3192           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3193
3194       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3195         CCValAssign &VA = ArgLocs[i];
3196         if (!VA.isRegLoc())
3197           continue;
3198         unsigned Reg = VA.getLocReg();
3199         switch (Reg) {
3200         default: break;
3201         case X86::EAX: case X86::EDX: case X86::ECX:
3202           if (++NumInRegs == MaxInRegs)
3203             return false;
3204           break;
3205         }
3206       }
3207     }
3208   }
3209
3210   return true;
3211 }
3212
3213 FastISel *
3214 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3215                                   const TargetLibraryInfo *libInfo) const {
3216   return X86::createFastISel(funcInfo, libInfo);
3217 }
3218
3219 //===----------------------------------------------------------------------===//
3220 //                           Other Lowering Hooks
3221 //===----------------------------------------------------------------------===//
3222
3223 static bool MayFoldLoad(SDValue Op) {
3224   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3225 }
3226
3227 static bool MayFoldIntoStore(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3229 }
3230
3231 static bool isTargetShuffle(unsigned Opcode) {
3232   switch(Opcode) {
3233   default: return false;
3234   case X86ISD::PSHUFD:
3235   case X86ISD::PSHUFHW:
3236   case X86ISD::PSHUFLW:
3237   case X86ISD::SHUFP:
3238   case X86ISD::PALIGNR:
3239   case X86ISD::MOVLHPS:
3240   case X86ISD::MOVLHPD:
3241   case X86ISD::MOVHLPS:
3242   case X86ISD::MOVLPS:
3243   case X86ISD::MOVLPD:
3244   case X86ISD::MOVSHDUP:
3245   case X86ISD::MOVSLDUP:
3246   case X86ISD::MOVDDUP:
3247   case X86ISD::MOVSS:
3248   case X86ISD::MOVSD:
3249   case X86ISD::UNPCKL:
3250   case X86ISD::UNPCKH:
3251   case X86ISD::VPERMILP:
3252   case X86ISD::VPERM2X128:
3253   case X86ISD::VPERMI:
3254     return true;
3255   }
3256 }
3257
3258 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3259                                     SDValue V1, SelectionDAG &DAG) {
3260   switch(Opc) {
3261   default: llvm_unreachable("Unknown x86 shuffle node");
3262   case X86ISD::MOVSHDUP:
3263   case X86ISD::MOVSLDUP:
3264   case X86ISD::MOVDDUP:
3265     return DAG.getNode(Opc, dl, VT, V1);
3266   }
3267 }
3268
3269 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3270                                     SDValue V1, unsigned TargetMask,
3271                                     SelectionDAG &DAG) {
3272   switch(Opc) {
3273   default: llvm_unreachable("Unknown x86 shuffle node");
3274   case X86ISD::PSHUFD:
3275   case X86ISD::PSHUFHW:
3276   case X86ISD::PSHUFLW:
3277   case X86ISD::VPERMILP:
3278   case X86ISD::VPERMI:
3279     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3280   }
3281 }
3282
3283 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3284                                     SDValue V1, SDValue V2, unsigned TargetMask,
3285                                     SelectionDAG &DAG) {
3286   switch(Opc) {
3287   default: llvm_unreachable("Unknown x86 shuffle node");
3288   case X86ISD::PALIGNR:
3289   case X86ISD::SHUFP:
3290   case X86ISD::VPERM2X128:
3291     return DAG.getNode(Opc, dl, VT, V1, V2,
3292                        DAG.getConstant(TargetMask, MVT::i8));
3293   }
3294 }
3295
3296 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3297                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3298   switch(Opc) {
3299   default: llvm_unreachable("Unknown x86 shuffle node");
3300   case X86ISD::MOVLHPS:
3301   case X86ISD::MOVLHPD:
3302   case X86ISD::MOVHLPS:
3303   case X86ISD::MOVLPS:
3304   case X86ISD::MOVLPD:
3305   case X86ISD::MOVSS:
3306   case X86ISD::MOVSD:
3307   case X86ISD::UNPCKL:
3308   case X86ISD::UNPCKH:
3309     return DAG.getNode(Opc, dl, VT, V1, V2);
3310   }
3311 }
3312
3313 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3314   MachineFunction &MF = DAG.getMachineFunction();
3315   const X86RegisterInfo *RegInfo =
3316     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3317   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3318   int ReturnAddrIndex = FuncInfo->getRAIndex();
3319
3320   if (ReturnAddrIndex == 0) {
3321     // Set up a frame object for the return address.
3322     unsigned SlotSize = RegInfo->getSlotSize();
3323     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3324                                                            false);
3325     FuncInfo->setRAIndex(ReturnAddrIndex);
3326   }
3327
3328   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3329 }
3330
3331 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3332                                        bool hasSymbolicDisplacement) {
3333   // Offset should fit into 32 bit immediate field.
3334   if (!isInt<32>(Offset))
3335     return false;
3336
3337   // If we don't have a symbolic displacement - we don't have any extra
3338   // restrictions.
3339   if (!hasSymbolicDisplacement)
3340     return true;
3341
3342   // FIXME: Some tweaks might be needed for medium code model.
3343   if (M != CodeModel::Small && M != CodeModel::Kernel)
3344     return false;
3345
3346   // For small code model we assume that latest object is 16MB before end of 31
3347   // bits boundary. We may also accept pretty large negative constants knowing
3348   // that all objects are in the positive half of address space.
3349   if (M == CodeModel::Small && Offset < 16*1024*1024)
3350     return true;
3351
3352   // For kernel code model we know that all object resist in the negative half
3353   // of 32bits address space. We may not accept negative offsets, since they may
3354   // be just off and we may accept pretty large positive ones.
3355   if (M == CodeModel::Kernel && Offset > 0)
3356     return true;
3357
3358   return false;
3359 }
3360
3361 /// isCalleePop - Determines whether the callee is required to pop its
3362 /// own arguments. Callee pop is necessary to support tail calls.
3363 bool X86::isCalleePop(CallingConv::ID CallingConv,
3364                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3365   if (IsVarArg)
3366     return false;
3367
3368   switch (CallingConv) {
3369   default:
3370     return false;
3371   case CallingConv::X86_StdCall:
3372     return !is64Bit;
3373   case CallingConv::X86_FastCall:
3374     return !is64Bit;
3375   case CallingConv::X86_ThisCall:
3376     return !is64Bit;
3377   case CallingConv::Fast:
3378     return TailCallOpt;
3379   case CallingConv::GHC:
3380     return TailCallOpt;
3381   case CallingConv::HiPE:
3382     return TailCallOpt;
3383   }
3384 }
3385
3386 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3387 /// specific condition code, returning the condition code and the LHS/RHS of the
3388 /// comparison to make.
3389 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3390                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3391   if (!isFP) {
3392     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3393       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3394         // X > -1   -> X == 0, jump !sign.
3395         RHS = DAG.getConstant(0, RHS.getValueType());
3396         return X86::COND_NS;
3397       }
3398       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3399         // X < 0   -> X == 0, jump on sign.
3400         return X86::COND_S;
3401       }
3402       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3403         // X < 1   -> X <= 0
3404         RHS = DAG.getConstant(0, RHS.getValueType());
3405         return X86::COND_LE;
3406       }
3407     }
3408
3409     switch (SetCCOpcode) {
3410     default: llvm_unreachable("Invalid integer condition!");
3411     case ISD::SETEQ:  return X86::COND_E;
3412     case ISD::SETGT:  return X86::COND_G;
3413     case ISD::SETGE:  return X86::COND_GE;
3414     case ISD::SETLT:  return X86::COND_L;
3415     case ISD::SETLE:  return X86::COND_LE;
3416     case ISD::SETNE:  return X86::COND_NE;
3417     case ISD::SETULT: return X86::COND_B;
3418     case ISD::SETUGT: return X86::COND_A;
3419     case ISD::SETULE: return X86::COND_BE;
3420     case ISD::SETUGE: return X86::COND_AE;
3421     }
3422   }
3423
3424   // First determine if it is required or is profitable to flip the operands.
3425
3426   // If LHS is a foldable load, but RHS is not, flip the condition.
3427   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3428       !ISD::isNON_EXTLoad(RHS.getNode())) {
3429     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3430     std::swap(LHS, RHS);
3431   }
3432
3433   switch (SetCCOpcode) {
3434   default: break;
3435   case ISD::SETOLT:
3436   case ISD::SETOLE:
3437   case ISD::SETUGT:
3438   case ISD::SETUGE:
3439     std::swap(LHS, RHS);
3440     break;
3441   }
3442
3443   // On a floating point condition, the flags are set as follows:
3444   // ZF  PF  CF   op
3445   //  0 | 0 | 0 | X > Y
3446   //  0 | 0 | 1 | X < Y
3447   //  1 | 0 | 0 | X == Y
3448   //  1 | 1 | 1 | unordered
3449   switch (SetCCOpcode) {
3450   default: llvm_unreachable("Condcode should be pre-legalized away");
3451   case ISD::SETUEQ:
3452   case ISD::SETEQ:   return X86::COND_E;
3453   case ISD::SETOLT:              // flipped
3454   case ISD::SETOGT:
3455   case ISD::SETGT:   return X86::COND_A;
3456   case ISD::SETOLE:              // flipped
3457   case ISD::SETOGE:
3458   case ISD::SETGE:   return X86::COND_AE;
3459   case ISD::SETUGT:              // flipped
3460   case ISD::SETULT:
3461   case ISD::SETLT:   return X86::COND_B;
3462   case ISD::SETUGE:              // flipped
3463   case ISD::SETULE:
3464   case ISD::SETLE:   return X86::COND_BE;
3465   case ISD::SETONE:
3466   case ISD::SETNE:   return X86::COND_NE;
3467   case ISD::SETUO:   return X86::COND_P;
3468   case ISD::SETO:    return X86::COND_NP;
3469   case ISD::SETOEQ:
3470   case ISD::SETUNE:  return X86::COND_INVALID;
3471   }
3472 }
3473
3474 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3475 /// code. Current x86 isa includes the following FP cmov instructions:
3476 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3477 static bool hasFPCMov(unsigned X86CC) {
3478   switch (X86CC) {
3479   default:
3480     return false;
3481   case X86::COND_B:
3482   case X86::COND_BE:
3483   case X86::COND_E:
3484   case X86::COND_P:
3485   case X86::COND_A:
3486   case X86::COND_AE:
3487   case X86::COND_NE:
3488   case X86::COND_NP:
3489     return true;
3490   }
3491 }
3492
3493 /// isFPImmLegal - Returns true if the target can instruction select the
3494 /// specified FP immediate natively. If false, the legalizer will
3495 /// materialize the FP immediate as a load from a constant pool.
3496 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3497   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3498     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3499       return true;
3500   }
3501   return false;
3502 }
3503
3504 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3505 /// the specified range (L, H].
3506 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3507   return (Val < 0) || (Val >= Low && Val < Hi);
3508 }
3509
3510 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3511 /// specified value.
3512 static bool isUndefOrEqual(int Val, int CmpVal) {
3513   return (Val < 0 || Val == CmpVal);
3514 }
3515
3516 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3517 /// from position Pos and ending in Pos+Size, falls within the specified
3518 /// sequential range (L, L+Pos]. or is undef.
3519 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3520                                        unsigned Pos, unsigned Size, int Low) {
3521   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3522     if (!isUndefOrEqual(Mask[i], Low))
3523       return false;
3524   return true;
3525 }
3526
3527 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3528 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3529 /// the second operand.
3530 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3531   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3532     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3533   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3534     return (Mask[0] < 2 && Mask[1] < 2);
3535   return false;
3536 }
3537
3538 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3539 /// is suitable for input to PSHUFHW.
3540 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3541   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3542     return false;
3543
3544   // Lower quadword copied in order or undef.
3545   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3546     return false;
3547
3548   // Upper quadword shuffled.
3549   for (unsigned i = 4; i != 8; ++i)
3550     if (!isUndefOrInRange(Mask[i], 4, 8))
3551       return false;
3552
3553   if (VT == MVT::v16i16) {
3554     // Lower quadword copied in order or undef.
3555     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3556       return false;
3557
3558     // Upper quadword shuffled.
3559     for (unsigned i = 12; i != 16; ++i)
3560       if (!isUndefOrInRange(Mask[i], 12, 16))
3561         return false;
3562   }
3563
3564   return true;
3565 }
3566
3567 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3568 /// is suitable for input to PSHUFLW.
3569 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3570   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3571     return false;
3572
3573   // Upper quadword copied in order.
3574   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3575     return false;
3576
3577   // Lower quadword shuffled.
3578   for (unsigned i = 0; i != 4; ++i)
3579     if (!isUndefOrInRange(Mask[i], 0, 4))
3580       return false;
3581
3582   if (VT == MVT::v16i16) {
3583     // Upper quadword copied in order.
3584     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3585       return false;
3586
3587     // Lower quadword shuffled.
3588     for (unsigned i = 8; i != 12; ++i)
3589       if (!isUndefOrInRange(Mask[i], 8, 12))
3590         return false;
3591   }
3592
3593   return true;
3594 }
3595
3596 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3597 /// is suitable for input to PALIGNR.
3598 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3599                           const X86Subtarget *Subtarget) {
3600   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3601       (VT.is256BitVector() && !Subtarget->hasInt256()))
3602     return false;
3603
3604   unsigned NumElts = VT.getVectorNumElements();
3605   unsigned NumLanes = VT.getSizeInBits()/128;
3606   unsigned NumLaneElts = NumElts/NumLanes;
3607
3608   // Do not handle 64-bit element shuffles with palignr.
3609   if (NumLaneElts == 2)
3610     return false;
3611
3612   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3613     unsigned i;
3614     for (i = 0; i != NumLaneElts; ++i) {
3615       if (Mask[i+l] >= 0)
3616         break;
3617     }
3618
3619     // Lane is all undef, go to next lane
3620     if (i == NumLaneElts)
3621       continue;
3622
3623     int Start = Mask[i+l];
3624
3625     // Make sure its in this lane in one of the sources
3626     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3627         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3628       return false;
3629
3630     // If not lane 0, then we must match lane 0
3631     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3632       return false;
3633
3634     // Correct second source to be contiguous with first source
3635     if (Start >= (int)NumElts)
3636       Start -= NumElts - NumLaneElts;
3637
3638     // Make sure we're shifting in the right direction.
3639     if (Start <= (int)(i+l))
3640       return false;
3641
3642     Start -= i;
3643
3644     // Check the rest of the elements to see if they are consecutive.
3645     for (++i; i != NumLaneElts; ++i) {
3646       int Idx = Mask[i+l];
3647
3648       // Make sure its in this lane
3649       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3650           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3651         return false;
3652
3653       // If not lane 0, then we must match lane 0
3654       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3655         return false;
3656
3657       if (Idx >= (int)NumElts)
3658         Idx -= NumElts - NumLaneElts;
3659
3660       if (!isUndefOrEqual(Idx, Start+i))
3661         return false;
3662
3663     }
3664   }
3665
3666   return true;
3667 }
3668
3669 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3670 /// the two vector operands have swapped position.
3671 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3672                                      unsigned NumElems) {
3673   for (unsigned i = 0; i != NumElems; ++i) {
3674     int idx = Mask[i];
3675     if (idx < 0)
3676       continue;
3677     else if (idx < (int)NumElems)
3678       Mask[i] = idx + NumElems;
3679     else
3680       Mask[i] = idx - NumElems;
3681   }
3682 }
3683
3684 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3685 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3686 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3687 /// reverse of what x86 shuffles want.
3688 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3689                         bool Commuted = false) {
3690   if (!HasFp256 && VT.is256BitVector())
3691     return false;
3692
3693   unsigned NumElems = VT.getVectorNumElements();
3694   unsigned NumLanes = VT.getSizeInBits()/128;
3695   unsigned NumLaneElems = NumElems/NumLanes;
3696
3697   if (NumLaneElems != 2 && NumLaneElems != 4)
3698     return false;
3699
3700   // VSHUFPSY divides the resulting vector into 4 chunks.
3701   // The sources are also splitted into 4 chunks, and each destination
3702   // chunk must come from a different source chunk.
3703   //
3704   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3705   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3706   //
3707   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3708   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3709   //
3710   // VSHUFPDY divides the resulting vector into 4 chunks.
3711   // The sources are also splitted into 4 chunks, and each destination
3712   // chunk must come from a different source chunk.
3713   //
3714   //  SRC1 =>      X3       X2       X1       X0
3715   //  SRC2 =>      Y3       Y2       Y1       Y0
3716   //
3717   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3718   //
3719   unsigned HalfLaneElems = NumLaneElems/2;
3720   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3721     for (unsigned i = 0; i != NumLaneElems; ++i) {
3722       int Idx = Mask[i+l];
3723       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3724       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3725         return false;
3726       // For VSHUFPSY, the mask of the second half must be the same as the
3727       // first but with the appropriate offsets. This works in the same way as
3728       // VPERMILPS works with masks.
3729       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3730         continue;
3731       if (!isUndefOrEqual(Idx, Mask[i]+l))
3732         return false;
3733     }
3734   }
3735
3736   return true;
3737 }
3738
3739 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3740 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3741 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3742   if (!VT.is128BitVector())
3743     return false;
3744
3745   unsigned NumElems = VT.getVectorNumElements();
3746
3747   if (NumElems != 4)
3748     return false;
3749
3750   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3751   return isUndefOrEqual(Mask[0], 6) &&
3752          isUndefOrEqual(Mask[1], 7) &&
3753          isUndefOrEqual(Mask[2], 2) &&
3754          isUndefOrEqual(Mask[3], 3);
3755 }
3756
3757 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3758 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3759 /// <2, 3, 2, 3>
3760 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3761   if (!VT.is128BitVector())
3762     return false;
3763
3764   unsigned NumElems = VT.getVectorNumElements();
3765
3766   if (NumElems != 4)
3767     return false;
3768
3769   return isUndefOrEqual(Mask[0], 2) &&
3770          isUndefOrEqual(Mask[1], 3) &&
3771          isUndefOrEqual(Mask[2], 2) &&
3772          isUndefOrEqual(Mask[3], 3);
3773 }
3774
3775 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3776 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3777 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3778   if (!VT.is128BitVector())
3779     return false;
3780
3781   unsigned NumElems = VT.getVectorNumElements();
3782
3783   if (NumElems != 2 && NumElems != 4)
3784     return false;
3785
3786   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3787     if (!isUndefOrEqual(Mask[i], i + NumElems))
3788       return false;
3789
3790   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3791     if (!isUndefOrEqual(Mask[i], i))
3792       return false;
3793
3794   return true;
3795 }
3796
3797 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3798 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3799 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3800   if (!VT.is128BitVector())
3801     return false;
3802
3803   unsigned NumElems = VT.getVectorNumElements();
3804
3805   if (NumElems != 2 && NumElems != 4)
3806     return false;
3807
3808   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3809     if (!isUndefOrEqual(Mask[i], i))
3810       return false;
3811
3812   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3813     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3814       return false;
3815
3816   return true;
3817 }
3818
3819 //
3820 // Some special combinations that can be optimized.
3821 //
3822 static
3823 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3824                                SelectionDAG &DAG) {
3825   MVT VT = SVOp->getValueType(0).getSimpleVT();
3826   SDLoc dl(SVOp);
3827
3828   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3829     return SDValue();
3830
3831   ArrayRef<int> Mask = SVOp->getMask();
3832
3833   // These are the special masks that may be optimized.
3834   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3835   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3836   bool MatchEvenMask = true;
3837   bool MatchOddMask  = true;
3838   for (int i=0; i<8; ++i) {
3839     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3840       MatchEvenMask = false;
3841     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3842       MatchOddMask = false;
3843   }
3844
3845   if (!MatchEvenMask && !MatchOddMask)
3846     return SDValue();
3847
3848   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3849
3850   SDValue Op0 = SVOp->getOperand(0);
3851   SDValue Op1 = SVOp->getOperand(1);
3852
3853   if (MatchEvenMask) {
3854     // Shift the second operand right to 32 bits.
3855     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3856     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3857   } else {
3858     // Shift the first operand left to 32 bits.
3859     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3860     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3861   }
3862   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3863   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3864 }
3865
3866 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3868 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3869                          bool HasInt256, bool V2IsSplat = false) {
3870   unsigned NumElts = VT.getVectorNumElements();
3871
3872   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3873          "Unsupported vector type for unpckh");
3874
3875   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3876       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3877     return false;
3878
3879   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3880   // independently on 128-bit lanes.
3881   unsigned NumLanes = VT.getSizeInBits()/128;
3882   unsigned NumLaneElts = NumElts/NumLanes;
3883
3884   for (unsigned l = 0; l != NumLanes; ++l) {
3885     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3886          i != (l+1)*NumLaneElts;
3887          i += 2, ++j) {
3888       int BitI  = Mask[i];
3889       int BitI1 = Mask[i+1];
3890       if (!isUndefOrEqual(BitI, j))
3891         return false;
3892       if (V2IsSplat) {
3893         if (!isUndefOrEqual(BitI1, NumElts))
3894           return false;
3895       } else {
3896         if (!isUndefOrEqual(BitI1, j + NumElts))
3897           return false;
3898       }
3899     }
3900   }
3901
3902   return true;
3903 }
3904
3905 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3907 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3908                          bool HasInt256, bool V2IsSplat = false) {
3909   unsigned NumElts = VT.getVectorNumElements();
3910
3911   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3912          "Unsupported vector type for unpckh");
3913
3914   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3915       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3916     return false;
3917
3918   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3919   // independently on 128-bit lanes.
3920   unsigned NumLanes = VT.getSizeInBits()/128;
3921   unsigned NumLaneElts = NumElts/NumLanes;
3922
3923   for (unsigned l = 0; l != NumLanes; ++l) {
3924     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3925          i != (l+1)*NumLaneElts; i += 2, ++j) {
3926       int BitI  = Mask[i];
3927       int BitI1 = Mask[i+1];
3928       if (!isUndefOrEqual(BitI, j))
3929         return false;
3930       if (V2IsSplat) {
3931         if (isUndefOrEqual(BitI1, NumElts))
3932           return false;
3933       } else {
3934         if (!isUndefOrEqual(BitI1, j+NumElts))
3935           return false;
3936       }
3937     }
3938   }
3939   return true;
3940 }
3941
3942 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3943 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3944 /// <0, 0, 1, 1>
3945 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3946   unsigned NumElts = VT.getVectorNumElements();
3947   bool Is256BitVec = VT.is256BitVector();
3948
3949   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3950          "Unsupported vector type for unpckh");
3951
3952   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3953       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3954     return false;
3955
3956   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3957   // FIXME: Need a better way to get rid of this, there's no latency difference
3958   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3959   // the former later. We should also remove the "_undef" special mask.
3960   if (NumElts == 4 && Is256BitVec)
3961     return false;
3962
3963   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3964   // independently on 128-bit lanes.
3965   unsigned NumLanes = VT.getSizeInBits()/128;
3966   unsigned NumLaneElts = NumElts/NumLanes;
3967
3968   for (unsigned l = 0; l != NumLanes; ++l) {
3969     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3970          i != (l+1)*NumLaneElts;
3971          i += 2, ++j) {
3972       int BitI  = Mask[i];
3973       int BitI1 = Mask[i+1];
3974
3975       if (!isUndefOrEqual(BitI, j))
3976         return false;
3977       if (!isUndefOrEqual(BitI1, j))
3978         return false;
3979     }
3980   }
3981
3982   return true;
3983 }
3984
3985 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3986 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3987 /// <2, 2, 3, 3>
3988 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3989   unsigned NumElts = VT.getVectorNumElements();
3990
3991   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3992          "Unsupported vector type for unpckh");
3993
3994   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3995       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3996     return false;
3997
3998   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3999   // independently on 128-bit lanes.
4000   unsigned NumLanes = VT.getSizeInBits()/128;
4001   unsigned NumLaneElts = NumElts/NumLanes;
4002
4003   for (unsigned l = 0; l != NumLanes; ++l) {
4004     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4005          i != (l+1)*NumLaneElts; i += 2, ++j) {
4006       int BitI  = Mask[i];
4007       int BitI1 = Mask[i+1];
4008       if (!isUndefOrEqual(BitI, j))
4009         return false;
4010       if (!isUndefOrEqual(BitI1, j))
4011         return false;
4012     }
4013   }
4014   return true;
4015 }
4016
4017 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4019 /// MOVSD, and MOVD, i.e. setting the lowest element.
4020 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4021   if (VT.getVectorElementType().getSizeInBits() < 32)
4022     return false;
4023   if (!VT.is128BitVector())
4024     return false;
4025
4026   unsigned NumElts = VT.getVectorNumElements();
4027
4028   if (!isUndefOrEqual(Mask[0], NumElts))
4029     return false;
4030
4031   for (unsigned i = 1; i != NumElts; ++i)
4032     if (!isUndefOrEqual(Mask[i], i))
4033       return false;
4034
4035   return true;
4036 }
4037
4038 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4039 /// as permutations between 128-bit chunks or halves. As an example: this
4040 /// shuffle bellow:
4041 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4042 /// The first half comes from the second half of V1 and the second half from the
4043 /// the second half of V2.
4044 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4045   if (!HasFp256 || !VT.is256BitVector())
4046     return false;
4047
4048   // The shuffle result is divided into half A and half B. In total the two
4049   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4050   // B must come from C, D, E or F.
4051   unsigned HalfSize = VT.getVectorNumElements()/2;
4052   bool MatchA = false, MatchB = false;
4053
4054   // Check if A comes from one of C, D, E, F.
4055   for (unsigned Half = 0; Half != 4; ++Half) {
4056     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4057       MatchA = true;
4058       break;
4059     }
4060   }
4061
4062   // Check if B comes from one of C, D, E, F.
4063   for (unsigned Half = 0; Half != 4; ++Half) {
4064     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4065       MatchB = true;
4066       break;
4067     }
4068   }
4069
4070   return MatchA && MatchB;
4071 }
4072
4073 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4075 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4076   MVT VT = SVOp->getValueType(0).getSimpleVT();
4077
4078   unsigned HalfSize = VT.getVectorNumElements()/2;
4079
4080   unsigned FstHalf = 0, SndHalf = 0;
4081   for (unsigned i = 0; i < HalfSize; ++i) {
4082     if (SVOp->getMaskElt(i) > 0) {
4083       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4084       break;
4085     }
4086   }
4087   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4088     if (SVOp->getMaskElt(i) > 0) {
4089       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4090       break;
4091     }
4092   }
4093
4094   return (FstHalf | (SndHalf << 4));
4095 }
4096
4097 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4098 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4099 /// Note that VPERMIL mask matching is different depending whether theunderlying
4100 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4101 /// to the same elements of the low, but to the higher half of the source.
4102 /// In VPERMILPD the two lanes could be shuffled independently of each other
4103 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4104 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4105   if (!HasFp256)
4106     return false;
4107
4108   unsigned NumElts = VT.getVectorNumElements();
4109   // Only match 256-bit with 32/64-bit types
4110   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4111     return false;
4112
4113   unsigned NumLanes = VT.getSizeInBits()/128;
4114   unsigned LaneSize = NumElts/NumLanes;
4115   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4116     for (unsigned i = 0; i != LaneSize; ++i) {
4117       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4118         return false;
4119       if (NumElts != 8 || l == 0)
4120         continue;
4121       // VPERMILPS handling
4122       if (Mask[i] < 0)
4123         continue;
4124       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4125         return false;
4126     }
4127   }
4128
4129   return true;
4130 }
4131
4132 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4133 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4134 /// element of vector 2 and the other elements to come from vector 1 in order.
4135 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4136                                bool V2IsSplat = false, bool V2IsUndef = false) {
4137   if (!VT.is128BitVector())
4138     return false;
4139
4140   unsigned NumOps = VT.getVectorNumElements();
4141   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4142     return false;
4143
4144   if (!isUndefOrEqual(Mask[0], 0))
4145     return false;
4146
4147   for (unsigned i = 1; i != NumOps; ++i)
4148     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4149           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4150           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4151       return false;
4152
4153   return true;
4154 }
4155
4156 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4157 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4158 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4159 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4160                            const X86Subtarget *Subtarget) {
4161   if (!Subtarget->hasSSE3())
4162     return false;
4163
4164   unsigned NumElems = VT.getVectorNumElements();
4165
4166   if ((VT.is128BitVector() && NumElems != 4) ||
4167       (VT.is256BitVector() && NumElems != 8))
4168     return false;
4169
4170   // "i+1" is the value the indexed mask element must have
4171   for (unsigned i = 0; i != NumElems; i += 2)
4172     if (!isUndefOrEqual(Mask[i], i+1) ||
4173         !isUndefOrEqual(Mask[i+1], i+1))
4174       return false;
4175
4176   return true;
4177 }
4178
4179 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4181 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4182 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4183                            const X86Subtarget *Subtarget) {
4184   if (!Subtarget->hasSSE3())
4185     return false;
4186
4187   unsigned NumElems = VT.getVectorNumElements();
4188
4189   if ((VT.is128BitVector() && NumElems != 4) ||
4190       (VT.is256BitVector() && NumElems != 8))
4191     return false;
4192
4193   // "i" is the value the indexed mask element must have
4194   for (unsigned i = 0; i != NumElems; i += 2)
4195     if (!isUndefOrEqual(Mask[i], i) ||
4196         !isUndefOrEqual(Mask[i+1], i))
4197       return false;
4198
4199   return true;
4200 }
4201
4202 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4203 /// specifies a shuffle of elements that is suitable for input to 256-bit
4204 /// version of MOVDDUP.
4205 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4206   if (!HasFp256 || !VT.is256BitVector())
4207     return false;
4208
4209   unsigned NumElts = VT.getVectorNumElements();
4210   if (NumElts != 4)
4211     return false;
4212
4213   for (unsigned i = 0; i != NumElts/2; ++i)
4214     if (!isUndefOrEqual(Mask[i], 0))
4215       return false;
4216   for (unsigned i = NumElts/2; i != NumElts; ++i)
4217     if (!isUndefOrEqual(Mask[i], NumElts/2))
4218       return false;
4219   return true;
4220 }
4221
4222 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4223 /// specifies a shuffle of elements that is suitable for input to 128-bit
4224 /// version of MOVDDUP.
4225 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4226   if (!VT.is128BitVector())
4227     return false;
4228
4229   unsigned e = VT.getVectorNumElements() / 2;
4230   for (unsigned i = 0; i != e; ++i)
4231     if (!isUndefOrEqual(Mask[i], i))
4232       return false;
4233   for (unsigned i = 0; i != e; ++i)
4234     if (!isUndefOrEqual(Mask[e+i], i))
4235       return false;
4236   return true;
4237 }
4238
4239 /// isVEXTRACTIndex - Return true if the specified
4240 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4241 /// suitable for instruction that extract 128 or 256 bit vectors
4242 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4243   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4244   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4245     return false;
4246
4247   // The index should be aligned on a vecWidth-bit boundary.
4248   uint64_t Index =
4249     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4250
4251   MVT VT = N->getValueType(0).getSimpleVT();
4252   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4253   bool Result = (Index * ElSize) % vecWidth == 0;
4254
4255   return Result;
4256 }
4257
4258 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4259 /// operand specifies a subvector insert that is suitable for input to
4260 /// insertion of 128 or 256-bit subvectors
4261 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4262   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4263   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4264     return false;
4265   // The index should be aligned on a vecWidth-bit boundary.
4266   uint64_t Index =
4267     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4268
4269   MVT VT = N->getValueType(0).getSimpleVT();
4270   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4271   bool Result = (Index * ElSize) % vecWidth == 0;
4272
4273   return Result;
4274 }
4275
4276 bool X86::isVINSERT128Index(SDNode *N) {
4277   return isVINSERTIndex(N, 128);
4278 }
4279
4280 bool X86::isVINSERT256Index(SDNode *N) {
4281   return isVINSERTIndex(N, 256);
4282 }
4283
4284 bool X86::isVEXTRACT128Index(SDNode *N) {
4285   return isVEXTRACTIndex(N, 128);
4286 }
4287
4288 bool X86::isVEXTRACT256Index(SDNode *N) {
4289   return isVEXTRACTIndex(N, 256);
4290 }
4291
4292 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4293 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4294 /// Handles 128-bit and 256-bit.
4295 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4296   MVT VT = N->getValueType(0).getSimpleVT();
4297
4298   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4299          "Unsupported vector type for PSHUF/SHUFP");
4300
4301   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4302   // independently on 128-bit lanes.
4303   unsigned NumElts = VT.getVectorNumElements();
4304   unsigned NumLanes = VT.getSizeInBits()/128;
4305   unsigned NumLaneElts = NumElts/NumLanes;
4306
4307   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4308          "Only supports 2 or 4 elements per lane");
4309
4310   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4311   unsigned Mask = 0;
4312   for (unsigned i = 0; i != NumElts; ++i) {
4313     int Elt = N->getMaskElt(i);
4314     if (Elt < 0) continue;
4315     Elt &= NumLaneElts - 1;
4316     unsigned ShAmt = (i << Shift) % 8;
4317     Mask |= Elt << ShAmt;
4318   }
4319
4320   return Mask;
4321 }
4322
4323 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4324 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4325 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4326   MVT VT = N->getValueType(0).getSimpleVT();
4327
4328   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4329          "Unsupported vector type for PSHUFHW");
4330
4331   unsigned NumElts = VT.getVectorNumElements();
4332
4333   unsigned Mask = 0;
4334   for (unsigned l = 0; l != NumElts; l += 8) {
4335     // 8 nodes per lane, but we only care about the last 4.
4336     for (unsigned i = 0; i < 4; ++i) {
4337       int Elt = N->getMaskElt(l+i+4);
4338       if (Elt < 0) continue;
4339       Elt &= 0x3; // only 2-bits.
4340       Mask |= Elt << (i * 2);
4341     }
4342   }
4343
4344   return Mask;
4345 }
4346
4347 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4348 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4349 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4350   MVT VT = N->getValueType(0).getSimpleVT();
4351
4352   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4353          "Unsupported vector type for PSHUFHW");
4354
4355   unsigned NumElts = VT.getVectorNumElements();
4356
4357   unsigned Mask = 0;
4358   for (unsigned l = 0; l != NumElts; l += 8) {
4359     // 8 nodes per lane, but we only care about the first 4.
4360     for (unsigned i = 0; i < 4; ++i) {
4361       int Elt = N->getMaskElt(l+i);
4362       if (Elt < 0) continue;
4363       Elt &= 0x3; // only 2-bits
4364       Mask |= Elt << (i * 2);
4365     }
4366   }
4367
4368   return Mask;
4369 }
4370
4371 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4372 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4373 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4374   MVT VT = SVOp->getValueType(0).getSimpleVT();
4375   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4376
4377   unsigned NumElts = VT.getVectorNumElements();
4378   unsigned NumLanes = VT.getSizeInBits()/128;
4379   unsigned NumLaneElts = NumElts/NumLanes;
4380
4381   int Val = 0;
4382   unsigned i;
4383   for (i = 0; i != NumElts; ++i) {
4384     Val = SVOp->getMaskElt(i);
4385     if (Val >= 0)
4386       break;
4387   }
4388   if (Val >= (int)NumElts)
4389     Val -= NumElts - NumLaneElts;
4390
4391   assert(Val - i > 0 && "PALIGNR imm should be positive");
4392   return (Val - i) * EltSize;
4393 }
4394
4395 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4396   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4397   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4398     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4399
4400   uint64_t Index =
4401     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4402
4403   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4404   MVT ElVT = VecVT.getVectorElementType();
4405
4406   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4407   return Index / NumElemsPerChunk;
4408 }
4409
4410 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4411   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4412   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4413     llvm_unreachable("Illegal insert subvector for VINSERT");
4414
4415   uint64_t Index =
4416     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4417
4418   MVT VecVT = N->getValueType(0).getSimpleVT();
4419   MVT ElVT = VecVT.getVectorElementType();
4420
4421   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4422   return Index / NumElemsPerChunk;
4423 }
4424
4425 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4426 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4427 /// and VINSERTI128 instructions.
4428 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4429   return getExtractVEXTRACTImmediate(N, 128);
4430 }
4431
4432 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4433 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4434 /// and VINSERTI64x4 instructions.
4435 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4436   return getExtractVEXTRACTImmediate(N, 256);
4437 }
4438
4439 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4440 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4441 /// and VINSERTI128 instructions.
4442 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4443   return getInsertVINSERTImmediate(N, 128);
4444 }
4445
4446 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4447 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4448 /// and VINSERTI64x4 instructions.
4449 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4450   return getInsertVINSERTImmediate(N, 256);
4451 }
4452
4453 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4454 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4455 /// Handles 256-bit.
4456 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4457   MVT VT = N->getValueType(0).getSimpleVT();
4458
4459   unsigned NumElts = VT.getVectorNumElements();
4460
4461   assert((VT.is256BitVector() && NumElts == 4) &&
4462          "Unsupported vector type for VPERMQ/VPERMPD");
4463
4464   unsigned Mask = 0;
4465   for (unsigned i = 0; i != NumElts; ++i) {
4466     int Elt = N->getMaskElt(i);
4467     if (Elt < 0)
4468       continue;
4469     Mask |= Elt << (i*2);
4470   }
4471
4472   return Mask;
4473 }
4474 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4475 /// constant +0.0.
4476 bool X86::isZeroNode(SDValue Elt) {
4477   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4478     return CN->isNullValue();
4479   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4480     return CFP->getValueAPF().isPosZero();
4481   return false;
4482 }
4483
4484 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4485 /// their permute mask.
4486 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4487                                     SelectionDAG &DAG) {
4488   MVT VT = SVOp->getValueType(0).getSimpleVT();
4489   unsigned NumElems = VT.getVectorNumElements();
4490   SmallVector<int, 8> MaskVec;
4491
4492   for (unsigned i = 0; i != NumElems; ++i) {
4493     int Idx = SVOp->getMaskElt(i);
4494     if (Idx >= 0) {
4495       if (Idx < (int)NumElems)
4496         Idx += NumElems;
4497       else
4498         Idx -= NumElems;
4499     }
4500     MaskVec.push_back(Idx);
4501   }
4502   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4503                               SVOp->getOperand(0), &MaskVec[0]);
4504 }
4505
4506 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4507 /// match movhlps. The lower half elements should come from upper half of
4508 /// V1 (and in order), and the upper half elements should come from the upper
4509 /// half of V2 (and in order).
4510 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4511   if (!VT.is128BitVector())
4512     return false;
4513   if (VT.getVectorNumElements() != 4)
4514     return false;
4515   for (unsigned i = 0, e = 2; i != e; ++i)
4516     if (!isUndefOrEqual(Mask[i], i+2))
4517       return false;
4518   for (unsigned i = 2; i != 4; ++i)
4519     if (!isUndefOrEqual(Mask[i], i+4))
4520       return false;
4521   return true;
4522 }
4523
4524 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4525 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4526 /// required.
4527 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4528   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4529     return false;
4530   N = N->getOperand(0).getNode();
4531   if (!ISD::isNON_EXTLoad(N))
4532     return false;
4533   if (LD)
4534     *LD = cast<LoadSDNode>(N);
4535   return true;
4536 }
4537
4538 // Test whether the given value is a vector value which will be legalized
4539 // into a load.
4540 static bool WillBeConstantPoolLoad(SDNode *N) {
4541   if (N->getOpcode() != ISD::BUILD_VECTOR)
4542     return false;
4543
4544   // Check for any non-constant elements.
4545   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4546     switch (N->getOperand(i).getNode()->getOpcode()) {
4547     case ISD::UNDEF:
4548     case ISD::ConstantFP:
4549     case ISD::Constant:
4550       break;
4551     default:
4552       return false;
4553     }
4554
4555   // Vectors of all-zeros and all-ones are materialized with special
4556   // instructions rather than being loaded.
4557   return !ISD::isBuildVectorAllZeros(N) &&
4558          !ISD::isBuildVectorAllOnes(N);
4559 }
4560
4561 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4562 /// match movlp{s|d}. The lower half elements should come from lower half of
4563 /// V1 (and in order), and the upper half elements should come from the upper
4564 /// half of V2 (and in order). And since V1 will become the source of the
4565 /// MOVLP, it must be either a vector load or a scalar load to vector.
4566 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4567                                ArrayRef<int> Mask, EVT VT) {
4568   if (!VT.is128BitVector())
4569     return false;
4570
4571   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4572     return false;
4573   // Is V2 is a vector load, don't do this transformation. We will try to use
4574   // load folding shufps op.
4575   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4576     return false;
4577
4578   unsigned NumElems = VT.getVectorNumElements();
4579
4580   if (NumElems != 2 && NumElems != 4)
4581     return false;
4582   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4583     if (!isUndefOrEqual(Mask[i], i))
4584       return false;
4585   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4586     if (!isUndefOrEqual(Mask[i], i+NumElems))
4587       return false;
4588   return true;
4589 }
4590
4591 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4592 /// all the same.
4593 static bool isSplatVector(SDNode *N) {
4594   if (N->getOpcode() != ISD::BUILD_VECTOR)
4595     return false;
4596
4597   SDValue SplatValue = N->getOperand(0);
4598   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4599     if (N->getOperand(i) != SplatValue)
4600       return false;
4601   return true;
4602 }
4603
4604 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4605 /// to an zero vector.
4606 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4607 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4608   SDValue V1 = N->getOperand(0);
4609   SDValue V2 = N->getOperand(1);
4610   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4611   for (unsigned i = 0; i != NumElems; ++i) {
4612     int Idx = N->getMaskElt(i);
4613     if (Idx >= (int)NumElems) {
4614       unsigned Opc = V2.getOpcode();
4615       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4616         continue;
4617       if (Opc != ISD::BUILD_VECTOR ||
4618           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4619         return false;
4620     } else if (Idx >= 0) {
4621       unsigned Opc = V1.getOpcode();
4622       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4623         continue;
4624       if (Opc != ISD::BUILD_VECTOR ||
4625           !X86::isZeroNode(V1.getOperand(Idx)))
4626         return false;
4627     }
4628   }
4629   return true;
4630 }
4631
4632 /// getZeroVector - Returns a vector of specified type with all zero elements.
4633 ///
4634 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4635                              SelectionDAG &DAG, SDLoc dl) {
4636   assert(VT.isVector() && "Expected a vector type");
4637
4638   // Always build SSE zero vectors as <4 x i32> bitcasted
4639   // to their dest type. This ensures they get CSE'd.
4640   SDValue Vec;
4641   if (VT.is128BitVector()) {  // SSE
4642     if (Subtarget->hasSSE2()) {  // SSE2
4643       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4644       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4645     } else { // SSE1
4646       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4647       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4648     }
4649   } else if (VT.is256BitVector()) { // AVX
4650     if (Subtarget->hasInt256()) { // AVX2
4651       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4652       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4653       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4654                         array_lengthof(Ops));
4655     } else {
4656       // 256-bit logic and arithmetic instructions in AVX are all
4657       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4658       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4659       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4660       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4661                         array_lengthof(Ops));
4662     }
4663   } else
4664     llvm_unreachable("Unexpected vector type");
4665
4666   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4667 }
4668
4669 /// getOnesVector - Returns a vector of specified type with all bits set.
4670 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4671 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4672 /// Then bitcast to their original type, ensuring they get CSE'd.
4673 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4674                              SDLoc dl) {
4675   assert(VT.isVector() && "Expected a vector type");
4676
4677   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4678   SDValue Vec;
4679   if (VT.is256BitVector()) {
4680     if (HasInt256) { // AVX2
4681       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4683                         array_lengthof(Ops));
4684     } else { // AVX
4685       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4686       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4687     }
4688   } else if (VT.is128BitVector()) {
4689     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4690   } else
4691     llvm_unreachable("Unexpected vector type");
4692
4693   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4694 }
4695
4696 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4697 /// that point to V2 points to its first element.
4698 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4699   for (unsigned i = 0; i != NumElems; ++i) {
4700     if (Mask[i] > (int)NumElems) {
4701       Mask[i] = NumElems;
4702     }
4703   }
4704 }
4705
4706 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4707 /// operation of specified width.
4708 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4709                        SDValue V2) {
4710   unsigned NumElems = VT.getVectorNumElements();
4711   SmallVector<int, 8> Mask;
4712   Mask.push_back(NumElems);
4713   for (unsigned i = 1; i != NumElems; ++i)
4714     Mask.push_back(i);
4715   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4716 }
4717
4718 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4719 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4720                           SDValue V2) {
4721   unsigned NumElems = VT.getVectorNumElements();
4722   SmallVector<int, 8> Mask;
4723   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4724     Mask.push_back(i);
4725     Mask.push_back(i + NumElems);
4726   }
4727   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4728 }
4729
4730 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4731 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4732                           SDValue V2) {
4733   unsigned NumElems = VT.getVectorNumElements();
4734   SmallVector<int, 8> Mask;
4735   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4736     Mask.push_back(i + Half);
4737     Mask.push_back(i + NumElems + Half);
4738   }
4739   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4740 }
4741
4742 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4743 // a generic shuffle instruction because the target has no such instructions.
4744 // Generate shuffles which repeat i16 and i8 several times until they can be
4745 // represented by v4f32 and then be manipulated by target suported shuffles.
4746 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4747   EVT VT = V.getValueType();
4748   int NumElems = VT.getVectorNumElements();
4749   SDLoc dl(V);
4750
4751   while (NumElems > 4) {
4752     if (EltNo < NumElems/2) {
4753       V = getUnpackl(DAG, dl, VT, V, V);
4754     } else {
4755       V = getUnpackh(DAG, dl, VT, V, V);
4756       EltNo -= NumElems/2;
4757     }
4758     NumElems >>= 1;
4759   }
4760   return V;
4761 }
4762
4763 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4764 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4765   EVT VT = V.getValueType();
4766   SDLoc dl(V);
4767
4768   if (VT.is128BitVector()) {
4769     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4770     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4771     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4772                              &SplatMask[0]);
4773   } else if (VT.is256BitVector()) {
4774     // To use VPERMILPS to splat scalars, the second half of indicies must
4775     // refer to the higher part, which is a duplication of the lower one,
4776     // because VPERMILPS can only handle in-lane permutations.
4777     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4778                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4779
4780     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4781     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4782                              &SplatMask[0]);
4783   } else
4784     llvm_unreachable("Vector size not supported");
4785
4786   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4787 }
4788
4789 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4790 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4791   EVT SrcVT = SV->getValueType(0);
4792   SDValue V1 = SV->getOperand(0);
4793   SDLoc dl(SV);
4794
4795   int EltNo = SV->getSplatIndex();
4796   int NumElems = SrcVT.getVectorNumElements();
4797   bool Is256BitVec = SrcVT.is256BitVector();
4798
4799   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4800          "Unknown how to promote splat for type");
4801
4802   // Extract the 128-bit part containing the splat element and update
4803   // the splat element index when it refers to the higher register.
4804   if (Is256BitVec) {
4805     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4806     if (EltNo >= NumElems/2)
4807       EltNo -= NumElems/2;
4808   }
4809
4810   // All i16 and i8 vector types can't be used directly by a generic shuffle
4811   // instruction because the target has no such instruction. Generate shuffles
4812   // which repeat i16 and i8 several times until they fit in i32, and then can
4813   // be manipulated by target suported shuffles.
4814   EVT EltVT = SrcVT.getVectorElementType();
4815   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4816     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4817
4818   // Recreate the 256-bit vector and place the same 128-bit vector
4819   // into the low and high part. This is necessary because we want
4820   // to use VPERM* to shuffle the vectors
4821   if (Is256BitVec) {
4822     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4823   }
4824
4825   return getLegalSplat(DAG, V1, EltNo);
4826 }
4827
4828 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4829 /// vector of zero or undef vector.  This produces a shuffle where the low
4830 /// element of V2 is swizzled into the zero/undef vector, landing at element
4831 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4832 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4833                                            bool IsZero,
4834                                            const X86Subtarget *Subtarget,
4835                                            SelectionDAG &DAG) {
4836   EVT VT = V2.getValueType();
4837   SDValue V1 = IsZero
4838     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4839   unsigned NumElems = VT.getVectorNumElements();
4840   SmallVector<int, 16> MaskVec;
4841   for (unsigned i = 0; i != NumElems; ++i)
4842     // If this is the insertion idx, put the low elt of V2 here.
4843     MaskVec.push_back(i == Idx ? NumElems : i);
4844   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4845 }
4846
4847 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4848 /// target specific opcode. Returns true if the Mask could be calculated.
4849 /// Sets IsUnary to true if only uses one source.
4850 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4851                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4852   unsigned NumElems = VT.getVectorNumElements();
4853   SDValue ImmN;
4854
4855   IsUnary = false;
4856   switch(N->getOpcode()) {
4857   case X86ISD::SHUFP:
4858     ImmN = N->getOperand(N->getNumOperands()-1);
4859     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4860     break;
4861   case X86ISD::UNPCKH:
4862     DecodeUNPCKHMask(VT, Mask);
4863     break;
4864   case X86ISD::UNPCKL:
4865     DecodeUNPCKLMask(VT, Mask);
4866     break;
4867   case X86ISD::MOVHLPS:
4868     DecodeMOVHLPSMask(NumElems, Mask);
4869     break;
4870   case X86ISD::MOVLHPS:
4871     DecodeMOVLHPSMask(NumElems, Mask);
4872     break;
4873   case X86ISD::PALIGNR:
4874     ImmN = N->getOperand(N->getNumOperands()-1);
4875     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4876     break;
4877   case X86ISD::PSHUFD:
4878   case X86ISD::VPERMILP:
4879     ImmN = N->getOperand(N->getNumOperands()-1);
4880     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4881     IsUnary = true;
4882     break;
4883   case X86ISD::PSHUFHW:
4884     ImmN = N->getOperand(N->getNumOperands()-1);
4885     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::PSHUFLW:
4889     ImmN = N->getOperand(N->getNumOperands()-1);
4890     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::VPERMI:
4894     ImmN = N->getOperand(N->getNumOperands()-1);
4895     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4896     IsUnary = true;
4897     break;
4898   case X86ISD::MOVSS:
4899   case X86ISD::MOVSD: {
4900     // The index 0 always comes from the first element of the second source,
4901     // this is why MOVSS and MOVSD are used in the first place. The other
4902     // elements come from the other positions of the first source vector
4903     Mask.push_back(NumElems);
4904     for (unsigned i = 1; i != NumElems; ++i) {
4905       Mask.push_back(i);
4906     }
4907     break;
4908   }
4909   case X86ISD::VPERM2X128:
4910     ImmN = N->getOperand(N->getNumOperands()-1);
4911     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4912     if (Mask.empty()) return false;
4913     break;
4914   case X86ISD::MOVDDUP:
4915   case X86ISD::MOVLHPD:
4916   case X86ISD::MOVLPD:
4917   case X86ISD::MOVLPS:
4918   case X86ISD::MOVSHDUP:
4919   case X86ISD::MOVSLDUP:
4920     // Not yet implemented
4921     return false;
4922   default: llvm_unreachable("unknown target shuffle node");
4923   }
4924
4925   return true;
4926 }
4927
4928 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4929 /// element of the result of the vector shuffle.
4930 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4931                                    unsigned Depth) {
4932   if (Depth == 6)
4933     return SDValue();  // Limit search depth.
4934
4935   SDValue V = SDValue(N, 0);
4936   EVT VT = V.getValueType();
4937   unsigned Opcode = V.getOpcode();
4938
4939   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4940   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4941     int Elt = SV->getMaskElt(Index);
4942
4943     if (Elt < 0)
4944       return DAG.getUNDEF(VT.getVectorElementType());
4945
4946     unsigned NumElems = VT.getVectorNumElements();
4947     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4948                                          : SV->getOperand(1);
4949     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4950   }
4951
4952   // Recurse into target specific vector shuffles to find scalars.
4953   if (isTargetShuffle(Opcode)) {
4954     MVT ShufVT = V.getValueType().getSimpleVT();
4955     unsigned NumElems = ShufVT.getVectorNumElements();
4956     SmallVector<int, 16> ShuffleMask;
4957     bool IsUnary;
4958
4959     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4960       return SDValue();
4961
4962     int Elt = ShuffleMask[Index];
4963     if (Elt < 0)
4964       return DAG.getUNDEF(ShufVT.getVectorElementType());
4965
4966     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4967                                          : N->getOperand(1);
4968     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4969                                Depth+1);
4970   }
4971
4972   // Actual nodes that may contain scalar elements
4973   if (Opcode == ISD::BITCAST) {
4974     V = V.getOperand(0);
4975     EVT SrcVT = V.getValueType();
4976     unsigned NumElems = VT.getVectorNumElements();
4977
4978     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4979       return SDValue();
4980   }
4981
4982   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4983     return (Index == 0) ? V.getOperand(0)
4984                         : DAG.getUNDEF(VT.getVectorElementType());
4985
4986   if (V.getOpcode() == ISD::BUILD_VECTOR)
4987     return V.getOperand(Index);
4988
4989   return SDValue();
4990 }
4991
4992 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4993 /// shuffle operation which come from a consecutively from a zero. The
4994 /// search can start in two different directions, from left or right.
4995 /// We count undefs as zeros until PreferredNum is reached.
4996 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4997                                          unsigned NumElems, bool ZerosFromLeft,
4998                                          SelectionDAG &DAG,
4999                                          unsigned PreferredNum = -1U) {
5000   unsigned NumZeros = 0;
5001   for (unsigned i = 0; i != NumElems; ++i) {
5002     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5003     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5004     if (!Elt.getNode())
5005       break;
5006
5007     if (X86::isZeroNode(Elt))
5008       ++NumZeros;
5009     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5010       NumZeros = std::min(NumZeros + 1, PreferredNum);
5011     else
5012       break;
5013   }
5014
5015   return NumZeros;
5016 }
5017
5018 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5019 /// correspond consecutively to elements from one of the vector operands,
5020 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5021 static
5022 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5023                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5024                               unsigned NumElems, unsigned &OpNum) {
5025   bool SeenV1 = false;
5026   bool SeenV2 = false;
5027
5028   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5029     int Idx = SVOp->getMaskElt(i);
5030     // Ignore undef indicies
5031     if (Idx < 0)
5032       continue;
5033
5034     if (Idx < (int)NumElems)
5035       SeenV1 = true;
5036     else
5037       SeenV2 = true;
5038
5039     // Only accept consecutive elements from the same vector
5040     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5041       return false;
5042   }
5043
5044   OpNum = SeenV1 ? 0 : 1;
5045   return true;
5046 }
5047
5048 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5049 /// logical left shift of a vector.
5050 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5051                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5052   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5053   unsigned NumZeros = getNumOfConsecutiveZeros(
5054       SVOp, NumElems, false /* check zeros from right */, DAG,
5055       SVOp->getMaskElt(0));
5056   unsigned OpSrc;
5057
5058   if (!NumZeros)
5059     return false;
5060
5061   // Considering the elements in the mask that are not consecutive zeros,
5062   // check if they consecutively come from only one of the source vectors.
5063   //
5064   //               V1 = {X, A, B, C}     0
5065   //                         \  \  \    /
5066   //   vector_shuffle V1, V2 <1, 2, 3, X>
5067   //
5068   if (!isShuffleMaskConsecutive(SVOp,
5069             0,                   // Mask Start Index
5070             NumElems-NumZeros,   // Mask End Index(exclusive)
5071             NumZeros,            // Where to start looking in the src vector
5072             NumElems,            // Number of elements in vector
5073             OpSrc))              // Which source operand ?
5074     return false;
5075
5076   isLeft = false;
5077   ShAmt = NumZeros;
5078   ShVal = SVOp->getOperand(OpSrc);
5079   return true;
5080 }
5081
5082 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5083 /// logical left shift of a vector.
5084 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5085                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5086   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5087   unsigned NumZeros = getNumOfConsecutiveZeros(
5088       SVOp, NumElems, true /* check zeros from left */, DAG,
5089       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5090   unsigned OpSrc;
5091
5092   if (!NumZeros)
5093     return false;
5094
5095   // Considering the elements in the mask that are not consecutive zeros,
5096   // check if they consecutively come from only one of the source vectors.
5097   //
5098   //                           0    { A, B, X, X } = V2
5099   //                          / \    /  /
5100   //   vector_shuffle V1, V2 <X, X, 4, 5>
5101   //
5102   if (!isShuffleMaskConsecutive(SVOp,
5103             NumZeros,     // Mask Start Index
5104             NumElems,     // Mask End Index(exclusive)
5105             0,            // Where to start looking in the src vector
5106             NumElems,     // Number of elements in vector
5107             OpSrc))       // Which source operand ?
5108     return false;
5109
5110   isLeft = true;
5111   ShAmt = NumZeros;
5112   ShVal = SVOp->getOperand(OpSrc);
5113   return true;
5114 }
5115
5116 /// isVectorShift - Returns true if the shuffle can be implemented as a
5117 /// logical left or right shift of a vector.
5118 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5119                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5120   // Although the logic below support any bitwidth size, there are no
5121   // shift instructions which handle more than 128-bit vectors.
5122   if (!SVOp->getValueType(0).is128BitVector())
5123     return false;
5124
5125   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5126       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5127     return true;
5128
5129   return false;
5130 }
5131
5132 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5133 ///
5134 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5135                                        unsigned NumNonZero, unsigned NumZero,
5136                                        SelectionDAG &DAG,
5137                                        const X86Subtarget* Subtarget,
5138                                        const TargetLowering &TLI) {
5139   if (NumNonZero > 8)
5140     return SDValue();
5141
5142   SDLoc dl(Op);
5143   SDValue V(0, 0);
5144   bool First = true;
5145   for (unsigned i = 0; i < 16; ++i) {
5146     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5147     if (ThisIsNonZero && First) {
5148       if (NumZero)
5149         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5150       else
5151         V = DAG.getUNDEF(MVT::v8i16);
5152       First = false;
5153     }
5154
5155     if ((i & 1) != 0) {
5156       SDValue ThisElt(0, 0), LastElt(0, 0);
5157       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5158       if (LastIsNonZero) {
5159         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5160                               MVT::i16, Op.getOperand(i-1));
5161       }
5162       if (ThisIsNonZero) {
5163         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5164         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5165                               ThisElt, DAG.getConstant(8, MVT::i8));
5166         if (LastIsNonZero)
5167           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5168       } else
5169         ThisElt = LastElt;
5170
5171       if (ThisElt.getNode())
5172         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5173                         DAG.getIntPtrConstant(i/2));
5174     }
5175   }
5176
5177   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5178 }
5179
5180 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5181 ///
5182 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5183                                      unsigned NumNonZero, unsigned NumZero,
5184                                      SelectionDAG &DAG,
5185                                      const X86Subtarget* Subtarget,
5186                                      const TargetLowering &TLI) {
5187   if (NumNonZero > 4)
5188     return SDValue();
5189
5190   SDLoc dl(Op);
5191   SDValue V(0, 0);
5192   bool First = true;
5193   for (unsigned i = 0; i < 8; ++i) {
5194     bool isNonZero = (NonZeros & (1 << i)) != 0;
5195     if (isNonZero) {
5196       if (First) {
5197         if (NumZero)
5198           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5199         else
5200           V = DAG.getUNDEF(MVT::v8i16);
5201         First = false;
5202       }
5203       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5204                       MVT::v8i16, V, Op.getOperand(i),
5205                       DAG.getIntPtrConstant(i));
5206     }
5207   }
5208
5209   return V;
5210 }
5211
5212 /// getVShift - Return a vector logical shift node.
5213 ///
5214 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5215                          unsigned NumBits, SelectionDAG &DAG,
5216                          const TargetLowering &TLI, SDLoc dl) {
5217   assert(VT.is128BitVector() && "Unknown type for VShift");
5218   EVT ShVT = MVT::v2i64;
5219   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5220   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5221   return DAG.getNode(ISD::BITCAST, dl, VT,
5222                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5223                              DAG.getConstant(NumBits,
5224                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5225 }
5226
5227 SDValue
5228 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5229                                           SelectionDAG &DAG) const {
5230
5231   // Check if the scalar load can be widened into a vector load. And if
5232   // the address is "base + cst" see if the cst can be "absorbed" into
5233   // the shuffle mask.
5234   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5235     SDValue Ptr = LD->getBasePtr();
5236     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5237       return SDValue();
5238     EVT PVT = LD->getValueType(0);
5239     if (PVT != MVT::i32 && PVT != MVT::f32)
5240       return SDValue();
5241
5242     int FI = -1;
5243     int64_t Offset = 0;
5244     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5245       FI = FINode->getIndex();
5246       Offset = 0;
5247     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5248                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5249       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5250       Offset = Ptr.getConstantOperandVal(1);
5251       Ptr = Ptr.getOperand(0);
5252     } else {
5253       return SDValue();
5254     }
5255
5256     // FIXME: 256-bit vector instructions don't require a strict alignment,
5257     // improve this code to support it better.
5258     unsigned RequiredAlign = VT.getSizeInBits()/8;
5259     SDValue Chain = LD->getChain();
5260     // Make sure the stack object alignment is at least 16 or 32.
5261     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5262     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5263       if (MFI->isFixedObjectIndex(FI)) {
5264         // Can't change the alignment. FIXME: It's possible to compute
5265         // the exact stack offset and reference FI + adjust offset instead.
5266         // If someone *really* cares about this. That's the way to implement it.
5267         return SDValue();
5268       } else {
5269         MFI->setObjectAlignment(FI, RequiredAlign);
5270       }
5271     }
5272
5273     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5274     // Ptr + (Offset & ~15).
5275     if (Offset < 0)
5276       return SDValue();
5277     if ((Offset % RequiredAlign) & 3)
5278       return SDValue();
5279     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5280     if (StartOffset)
5281       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5282                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5283
5284     int EltNo = (Offset - StartOffset) >> 2;
5285     unsigned NumElems = VT.getVectorNumElements();
5286
5287     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5288     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5289                              LD->getPointerInfo().getWithOffset(StartOffset),
5290                              false, false, false, 0);
5291
5292     SmallVector<int, 8> Mask;
5293     for (unsigned i = 0; i != NumElems; ++i)
5294       Mask.push_back(EltNo);
5295
5296     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5297   }
5298
5299   return SDValue();
5300 }
5301
5302 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5303 /// vector of type 'VT', see if the elements can be replaced by a single large
5304 /// load which has the same value as a build_vector whose operands are 'elts'.
5305 ///
5306 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5307 ///
5308 /// FIXME: we'd also like to handle the case where the last elements are zero
5309 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5310 /// There's even a handy isZeroNode for that purpose.
5311 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5312                                         SDLoc &DL, SelectionDAG &DAG) {
5313   EVT EltVT = VT.getVectorElementType();
5314   unsigned NumElems = Elts.size();
5315
5316   LoadSDNode *LDBase = NULL;
5317   unsigned LastLoadedElt = -1U;
5318
5319   // For each element in the initializer, see if we've found a load or an undef.
5320   // If we don't find an initial load element, or later load elements are
5321   // non-consecutive, bail out.
5322   for (unsigned i = 0; i < NumElems; ++i) {
5323     SDValue Elt = Elts[i];
5324
5325     if (!Elt.getNode() ||
5326         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5327       return SDValue();
5328     if (!LDBase) {
5329       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5330         return SDValue();
5331       LDBase = cast<LoadSDNode>(Elt.getNode());
5332       LastLoadedElt = i;
5333       continue;
5334     }
5335     if (Elt.getOpcode() == ISD::UNDEF)
5336       continue;
5337
5338     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5339     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5340       return SDValue();
5341     LastLoadedElt = i;
5342   }
5343
5344   // If we have found an entire vector of loads and undefs, then return a large
5345   // load of the entire vector width starting at the base pointer.  If we found
5346   // consecutive loads for the low half, generate a vzext_load node.
5347   if (LastLoadedElt == NumElems - 1) {
5348     SDValue NewLd = SDValue();
5349     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5350       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5351                           LDBase->getPointerInfo(),
5352                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5353                           LDBase->isInvariant(), 0);
5354     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5355                         LDBase->getPointerInfo(),
5356                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5357                         LDBase->isInvariant(), LDBase->getAlignment());
5358
5359     if (LDBase->hasAnyUseOfValue(1)) {
5360       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5361                                      SDValue(LDBase, 1),
5362                                      SDValue(NewLd.getNode(), 1));
5363       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5364       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5365                              SDValue(NewLd.getNode(), 1));
5366     }
5367
5368     return NewLd;
5369   }
5370   if (NumElems == 4 && LastLoadedElt == 1 &&
5371       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5372     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5373     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5374     SDValue ResNode =
5375         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5376                                 array_lengthof(Ops), MVT::i64,
5377                                 LDBase->getPointerInfo(),
5378                                 LDBase->getAlignment(),
5379                                 false/*isVolatile*/, true/*ReadMem*/,
5380                                 false/*WriteMem*/);
5381
5382     // Make sure the newly-created LOAD is in the same position as LDBase in
5383     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5384     // update uses of LDBase's output chain to use the TokenFactor.
5385     if (LDBase->hasAnyUseOfValue(1)) {
5386       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5387                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5388       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5389       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5390                              SDValue(ResNode.getNode(), 1));
5391     }
5392
5393     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5394   }
5395   return SDValue();
5396 }
5397
5398 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5399 /// to generate a splat value for the following cases:
5400 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5401 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5402 /// a scalar load, or a constant.
5403 /// The VBROADCAST node is returned when a pattern is found,
5404 /// or SDValue() otherwise.
5405 SDValue
5406 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5407   if (!Subtarget->hasFp256())
5408     return SDValue();
5409
5410   MVT VT = Op.getValueType().getSimpleVT();
5411   SDLoc dl(Op);
5412
5413   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5414          "Unsupported vector type for broadcast.");
5415
5416   SDValue Ld;
5417   bool ConstSplatVal;
5418
5419   switch (Op.getOpcode()) {
5420     default:
5421       // Unknown pattern found.
5422       return SDValue();
5423
5424     case ISD::BUILD_VECTOR: {
5425       // The BUILD_VECTOR node must be a splat.
5426       if (!isSplatVector(Op.getNode()))
5427         return SDValue();
5428
5429       Ld = Op.getOperand(0);
5430       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5431                      Ld.getOpcode() == ISD::ConstantFP);
5432
5433       // The suspected load node has several users. Make sure that all
5434       // of its users are from the BUILD_VECTOR node.
5435       // Constants may have multiple users.
5436       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5437         return SDValue();
5438       break;
5439     }
5440
5441     case ISD::VECTOR_SHUFFLE: {
5442       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5443
5444       // Shuffles must have a splat mask where the first element is
5445       // broadcasted.
5446       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5447         return SDValue();
5448
5449       SDValue Sc = Op.getOperand(0);
5450       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5451           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5452
5453         if (!Subtarget->hasInt256())
5454           return SDValue();
5455
5456         // Use the register form of the broadcast instruction available on AVX2.
5457         if (VT.is256BitVector())
5458           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5459         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5460       }
5461
5462       Ld = Sc.getOperand(0);
5463       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5464                        Ld.getOpcode() == ISD::ConstantFP);
5465
5466       // The scalar_to_vector node and the suspected
5467       // load node must have exactly one user.
5468       // Constants may have multiple users.
5469       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5470         return SDValue();
5471       break;
5472     }
5473   }
5474
5475   bool Is256 = VT.is256BitVector();
5476
5477   // Handle the broadcasting a single constant scalar from the constant pool
5478   // into a vector. On Sandybridge it is still better to load a constant vector
5479   // from the constant pool and not to broadcast it from a scalar.
5480   if (ConstSplatVal && Subtarget->hasInt256()) {
5481     EVT CVT = Ld.getValueType();
5482     assert(!CVT.isVector() && "Must not broadcast a vector type");
5483     unsigned ScalarSize = CVT.getSizeInBits();
5484
5485     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5486       const Constant *C = 0;
5487       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5488         C = CI->getConstantIntValue();
5489       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5490         C = CF->getConstantFPValue();
5491
5492       assert(C && "Invalid constant type");
5493
5494       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5495       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5496       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5497                        MachinePointerInfo::getConstantPool(),
5498                        false, false, false, Alignment);
5499
5500       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5501     }
5502   }
5503
5504   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5505   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5506
5507   // Handle AVX2 in-register broadcasts.
5508   if (!IsLoad && Subtarget->hasInt256() &&
5509       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5510     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5511
5512   // The scalar source must be a normal load.
5513   if (!IsLoad)
5514     return SDValue();
5515
5516   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5517     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5518
5519   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5520   // double since there is no vbroadcastsd xmm
5521   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5522     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5523       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5524   }
5525
5526   // Unsupported broadcast.
5527   return SDValue();
5528 }
5529
5530 SDValue
5531 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5532   EVT VT = Op.getValueType();
5533
5534   // Skip if insert_vec_elt is not supported.
5535   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5536     return SDValue();
5537
5538   SDLoc DL(Op);
5539   unsigned NumElems = Op.getNumOperands();
5540
5541   SDValue VecIn1;
5542   SDValue VecIn2;
5543   SmallVector<unsigned, 4> InsertIndices;
5544   SmallVector<int, 8> Mask(NumElems, -1);
5545
5546   for (unsigned i = 0; i != NumElems; ++i) {
5547     unsigned Opc = Op.getOperand(i).getOpcode();
5548
5549     if (Opc == ISD::UNDEF)
5550       continue;
5551
5552     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5553       // Quit if more than 1 elements need inserting.
5554       if (InsertIndices.size() > 1)
5555         return SDValue();
5556
5557       InsertIndices.push_back(i);
5558       continue;
5559     }
5560
5561     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5562     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5563
5564     // Quit if extracted from vector of different type.
5565     if (ExtractedFromVec.getValueType() != VT)
5566       return SDValue();
5567
5568     // Quit if non-constant index.
5569     if (!isa<ConstantSDNode>(ExtIdx))
5570       return SDValue();
5571
5572     if (VecIn1.getNode() == 0)
5573       VecIn1 = ExtractedFromVec;
5574     else if (VecIn1 != ExtractedFromVec) {
5575       if (VecIn2.getNode() == 0)
5576         VecIn2 = ExtractedFromVec;
5577       else if (VecIn2 != ExtractedFromVec)
5578         // Quit if more than 2 vectors to shuffle
5579         return SDValue();
5580     }
5581
5582     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5583
5584     if (ExtractedFromVec == VecIn1)
5585       Mask[i] = Idx;
5586     else if (ExtractedFromVec == VecIn2)
5587       Mask[i] = Idx + NumElems;
5588   }
5589
5590   if (VecIn1.getNode() == 0)
5591     return SDValue();
5592
5593   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5594   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5595   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5596     unsigned Idx = InsertIndices[i];
5597     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5598                      DAG.getIntPtrConstant(Idx));
5599   }
5600
5601   return NV;
5602 }
5603
5604 SDValue
5605 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5606   SDLoc dl(Op);
5607
5608   MVT VT = Op.getValueType().getSimpleVT();
5609   MVT ExtVT = VT.getVectorElementType();
5610   unsigned NumElems = Op.getNumOperands();
5611
5612   // Vectors containing all zeros can be matched by pxor and xorps later
5613   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5614     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5615     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5616     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5617       return Op;
5618
5619     return getZeroVector(VT, Subtarget, DAG, dl);
5620   }
5621
5622   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5623   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5624   // vpcmpeqd on 256-bit vectors.
5625   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5626     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5627       return Op;
5628
5629     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5630   }
5631
5632   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5633   if (Broadcast.getNode())
5634     return Broadcast;
5635
5636   unsigned EVTBits = ExtVT.getSizeInBits();
5637
5638   unsigned NumZero  = 0;
5639   unsigned NumNonZero = 0;
5640   unsigned NonZeros = 0;
5641   bool IsAllConstants = true;
5642   SmallSet<SDValue, 8> Values;
5643   for (unsigned i = 0; i < NumElems; ++i) {
5644     SDValue Elt = Op.getOperand(i);
5645     if (Elt.getOpcode() == ISD::UNDEF)
5646       continue;
5647     Values.insert(Elt);
5648     if (Elt.getOpcode() != ISD::Constant &&
5649         Elt.getOpcode() != ISD::ConstantFP)
5650       IsAllConstants = false;
5651     if (X86::isZeroNode(Elt))
5652       NumZero++;
5653     else {
5654       NonZeros |= (1 << i);
5655       NumNonZero++;
5656     }
5657   }
5658
5659   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5660   if (NumNonZero == 0)
5661     return DAG.getUNDEF(VT);
5662
5663   // Special case for single non-zero, non-undef, element.
5664   if (NumNonZero == 1) {
5665     unsigned Idx = countTrailingZeros(NonZeros);
5666     SDValue Item = Op.getOperand(Idx);
5667
5668     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5669     // the value are obviously zero, truncate the value to i32 and do the
5670     // insertion that way.  Only do this if the value is non-constant or if the
5671     // value is a constant being inserted into element 0.  It is cheaper to do
5672     // a constant pool load than it is to do a movd + shuffle.
5673     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5674         (!IsAllConstants || Idx == 0)) {
5675       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5676         // Handle SSE only.
5677         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5678         EVT VecVT = MVT::v4i32;
5679         unsigned VecElts = 4;
5680
5681         // Truncate the value (which may itself be a constant) to i32, and
5682         // convert it to a vector with movd (S2V+shuffle to zero extend).
5683         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5684         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5685         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5686
5687         // Now we have our 32-bit value zero extended in the low element of
5688         // a vector.  If Idx != 0, swizzle it into place.
5689         if (Idx != 0) {
5690           SmallVector<int, 4> Mask;
5691           Mask.push_back(Idx);
5692           for (unsigned i = 1; i != VecElts; ++i)
5693             Mask.push_back(i);
5694           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5695                                       &Mask[0]);
5696         }
5697         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5698       }
5699     }
5700
5701     // If we have a constant or non-constant insertion into the low element of
5702     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5703     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5704     // depending on what the source datatype is.
5705     if (Idx == 0) {
5706       if (NumZero == 0)
5707         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5708
5709       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5710           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5711         if (VT.is256BitVector()) {
5712           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5713           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5714                              Item, DAG.getIntPtrConstant(0));
5715         }
5716         assert(VT.is128BitVector() && "Expected an SSE value type!");
5717         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5718         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5719         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5720       }
5721
5722       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5723         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5724         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5725         if (VT.is256BitVector()) {
5726           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5727           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5728         } else {
5729           assert(VT.is128BitVector() && "Expected an SSE value type!");
5730           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5731         }
5732         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5733       }
5734     }
5735
5736     // Is it a vector logical left shift?
5737     if (NumElems == 2 && Idx == 1 &&
5738         X86::isZeroNode(Op.getOperand(0)) &&
5739         !X86::isZeroNode(Op.getOperand(1))) {
5740       unsigned NumBits = VT.getSizeInBits();
5741       return getVShift(true, VT,
5742                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5743                                    VT, Op.getOperand(1)),
5744                        NumBits/2, DAG, *this, dl);
5745     }
5746
5747     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5748       return SDValue();
5749
5750     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5751     // is a non-constant being inserted into an element other than the low one,
5752     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5753     // movd/movss) to move this into the low element, then shuffle it into
5754     // place.
5755     if (EVTBits == 32) {
5756       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5757
5758       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5759       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5760       SmallVector<int, 8> MaskVec;
5761       for (unsigned i = 0; i != NumElems; ++i)
5762         MaskVec.push_back(i == Idx ? 0 : 1);
5763       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5764     }
5765   }
5766
5767   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5768   if (Values.size() == 1) {
5769     if (EVTBits == 32) {
5770       // Instead of a shuffle like this:
5771       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5772       // Check if it's possible to issue this instead.
5773       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5774       unsigned Idx = countTrailingZeros(NonZeros);
5775       SDValue Item = Op.getOperand(Idx);
5776       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5777         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5778     }
5779     return SDValue();
5780   }
5781
5782   // A vector full of immediates; various special cases are already
5783   // handled, so this is best done with a single constant-pool load.
5784   if (IsAllConstants)
5785     return SDValue();
5786
5787   // For AVX-length vectors, build the individual 128-bit pieces and use
5788   // shuffles to put them in place.
5789   if (VT.is256BitVector()) {
5790     SmallVector<SDValue, 32> V;
5791     for (unsigned i = 0; i != NumElems; ++i)
5792       V.push_back(Op.getOperand(i));
5793
5794     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5795
5796     // Build both the lower and upper subvector.
5797     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5798     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5799                                 NumElems/2);
5800
5801     // Recreate the wider vector with the lower and upper part.
5802     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5803   }
5804
5805   // Let legalizer expand 2-wide build_vectors.
5806   if (EVTBits == 64) {
5807     if (NumNonZero == 1) {
5808       // One half is zero or undef.
5809       unsigned Idx = countTrailingZeros(NonZeros);
5810       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5811                                  Op.getOperand(Idx));
5812       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5813     }
5814     return SDValue();
5815   }
5816
5817   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5818   if (EVTBits == 8 && NumElems == 16) {
5819     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5820                                         Subtarget, *this);
5821     if (V.getNode()) return V;
5822   }
5823
5824   if (EVTBits == 16 && NumElems == 8) {
5825     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5826                                       Subtarget, *this);
5827     if (V.getNode()) return V;
5828   }
5829
5830   // If element VT is == 32 bits, turn it into a number of shuffles.
5831   SmallVector<SDValue, 8> V(NumElems);
5832   if (NumElems == 4 && NumZero > 0) {
5833     for (unsigned i = 0; i < 4; ++i) {
5834       bool isZero = !(NonZeros & (1 << i));
5835       if (isZero)
5836         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5837       else
5838         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5839     }
5840
5841     for (unsigned i = 0; i < 2; ++i) {
5842       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5843         default: break;
5844         case 0:
5845           V[i] = V[i*2];  // Must be a zero vector.
5846           break;
5847         case 1:
5848           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5849           break;
5850         case 2:
5851           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5852           break;
5853         case 3:
5854           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5855           break;
5856       }
5857     }
5858
5859     bool Reverse1 = (NonZeros & 0x3) == 2;
5860     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5861     int MaskVec[] = {
5862       Reverse1 ? 1 : 0,
5863       Reverse1 ? 0 : 1,
5864       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5865       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5866     };
5867     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5868   }
5869
5870   if (Values.size() > 1 && VT.is128BitVector()) {
5871     // Check for a build vector of consecutive loads.
5872     for (unsigned i = 0; i < NumElems; ++i)
5873       V[i] = Op.getOperand(i);
5874
5875     // Check for elements which are consecutive loads.
5876     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5877     if (LD.getNode())
5878       return LD;
5879
5880     // Check for a build vector from mostly shuffle plus few inserting.
5881     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5882     if (Sh.getNode())
5883       return Sh;
5884
5885     // For SSE 4.1, use insertps to put the high elements into the low element.
5886     if (getSubtarget()->hasSSE41()) {
5887       SDValue Result;
5888       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5889         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5890       else
5891         Result = DAG.getUNDEF(VT);
5892
5893       for (unsigned i = 1; i < NumElems; ++i) {
5894         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5895         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5896                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5897       }
5898       return Result;
5899     }
5900
5901     // Otherwise, expand into a number of unpckl*, start by extending each of
5902     // our (non-undef) elements to the full vector width with the element in the
5903     // bottom slot of the vector (which generates no code for SSE).
5904     for (unsigned i = 0; i < NumElems; ++i) {
5905       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5906         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5907       else
5908         V[i] = DAG.getUNDEF(VT);
5909     }
5910
5911     // Next, we iteratively mix elements, e.g. for v4f32:
5912     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5913     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5914     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5915     unsigned EltStride = NumElems >> 1;
5916     while (EltStride != 0) {
5917       for (unsigned i = 0; i < EltStride; ++i) {
5918         // If V[i+EltStride] is undef and this is the first round of mixing,
5919         // then it is safe to just drop this shuffle: V[i] is already in the
5920         // right place, the one element (since it's the first round) being
5921         // inserted as undef can be dropped.  This isn't safe for successive
5922         // rounds because they will permute elements within both vectors.
5923         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5924             EltStride == NumElems/2)
5925           continue;
5926
5927         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5928       }
5929       EltStride >>= 1;
5930     }
5931     return V[0];
5932   }
5933   return SDValue();
5934 }
5935
5936 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5937 // to create 256-bit vectors from two other 128-bit ones.
5938 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5939   SDLoc dl(Op);
5940   MVT ResVT = Op.getValueType().getSimpleVT();
5941
5942   assert((ResVT.is256BitVector() ||
5943           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5944
5945   SDValue V1 = Op.getOperand(0);
5946   SDValue V2 = Op.getOperand(1);
5947   unsigned NumElems = ResVT.getVectorNumElements();
5948   if(ResVT.is256BitVector())
5949     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5950
5951   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5952 }
5953
5954 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5955   assert(Op.getNumOperands() == 2);
5956
5957   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
5958   // from two other 128-bit ones.
5959   return LowerAVXCONCAT_VECTORS(Op, DAG);
5960 }
5961
5962 // Try to lower a shuffle node into a simple blend instruction.
5963 static SDValue
5964 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5965                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5966   SDValue V1 = SVOp->getOperand(0);
5967   SDValue V2 = SVOp->getOperand(1);
5968   SDLoc dl(SVOp);
5969   MVT VT = SVOp->getValueType(0).getSimpleVT();
5970   MVT EltVT = VT.getVectorElementType();
5971   unsigned NumElems = VT.getVectorNumElements();
5972
5973   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5974     return SDValue();
5975   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5976     return SDValue();
5977
5978   // Check the mask for BLEND and build the value.
5979   unsigned MaskValue = 0;
5980   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5981   unsigned NumLanes = (NumElems-1)/8 + 1;
5982   unsigned NumElemsInLane = NumElems / NumLanes;
5983
5984   // Blend for v16i16 should be symetric for the both lanes.
5985   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5986
5987     int SndLaneEltIdx = (NumLanes == 2) ?
5988       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5989     int EltIdx = SVOp->getMaskElt(i);
5990
5991     if ((EltIdx < 0 || EltIdx == (int)i) &&
5992         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5993       continue;
5994
5995     if (((unsigned)EltIdx == (i + NumElems)) &&
5996         (SndLaneEltIdx < 0 ||
5997          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5998       MaskValue |= (1<<i);
5999     else
6000       return SDValue();
6001   }
6002
6003   // Convert i32 vectors to floating point if it is not AVX2.
6004   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6005   MVT BlendVT = VT;
6006   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6007     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6008                                NumElems);
6009     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6010     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6011   }
6012
6013   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6014                             DAG.getConstant(MaskValue, MVT::i32));
6015   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6016 }
6017
6018 // v8i16 shuffles - Prefer shuffles in the following order:
6019 // 1. [all]   pshuflw, pshufhw, optional move
6020 // 2. [ssse3] 1 x pshufb
6021 // 3. [ssse3] 2 x pshufb + 1 x por
6022 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6023 static SDValue
6024 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6025                          SelectionDAG &DAG) {
6026   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6027   SDValue V1 = SVOp->getOperand(0);
6028   SDValue V2 = SVOp->getOperand(1);
6029   SDLoc dl(SVOp);
6030   SmallVector<int, 8> MaskVals;
6031
6032   // Determine if more than 1 of the words in each of the low and high quadwords
6033   // of the result come from the same quadword of one of the two inputs.  Undef
6034   // mask values count as coming from any quadword, for better codegen.
6035   unsigned LoQuad[] = { 0, 0, 0, 0 };
6036   unsigned HiQuad[] = { 0, 0, 0, 0 };
6037   std::bitset<4> InputQuads;
6038   for (unsigned i = 0; i < 8; ++i) {
6039     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6040     int EltIdx = SVOp->getMaskElt(i);
6041     MaskVals.push_back(EltIdx);
6042     if (EltIdx < 0) {
6043       ++Quad[0];
6044       ++Quad[1];
6045       ++Quad[2];
6046       ++Quad[3];
6047       continue;
6048     }
6049     ++Quad[EltIdx / 4];
6050     InputQuads.set(EltIdx / 4);
6051   }
6052
6053   int BestLoQuad = -1;
6054   unsigned MaxQuad = 1;
6055   for (unsigned i = 0; i < 4; ++i) {
6056     if (LoQuad[i] > MaxQuad) {
6057       BestLoQuad = i;
6058       MaxQuad = LoQuad[i];
6059     }
6060   }
6061
6062   int BestHiQuad = -1;
6063   MaxQuad = 1;
6064   for (unsigned i = 0; i < 4; ++i) {
6065     if (HiQuad[i] > MaxQuad) {
6066       BestHiQuad = i;
6067       MaxQuad = HiQuad[i];
6068     }
6069   }
6070
6071   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6072   // of the two input vectors, shuffle them into one input vector so only a
6073   // single pshufb instruction is necessary. If There are more than 2 input
6074   // quads, disable the next transformation since it does not help SSSE3.
6075   bool V1Used = InputQuads[0] || InputQuads[1];
6076   bool V2Used = InputQuads[2] || InputQuads[3];
6077   if (Subtarget->hasSSSE3()) {
6078     if (InputQuads.count() == 2 && V1Used && V2Used) {
6079       BestLoQuad = InputQuads[0] ? 0 : 1;
6080       BestHiQuad = InputQuads[2] ? 2 : 3;
6081     }
6082     if (InputQuads.count() > 2) {
6083       BestLoQuad = -1;
6084       BestHiQuad = -1;
6085     }
6086   }
6087
6088   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6089   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6090   // words from all 4 input quadwords.
6091   SDValue NewV;
6092   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6093     int MaskV[] = {
6094       BestLoQuad < 0 ? 0 : BestLoQuad,
6095       BestHiQuad < 0 ? 1 : BestHiQuad
6096     };
6097     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6098                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6099                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6100     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6101
6102     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6103     // source words for the shuffle, to aid later transformations.
6104     bool AllWordsInNewV = true;
6105     bool InOrder[2] = { true, true };
6106     for (unsigned i = 0; i != 8; ++i) {
6107       int idx = MaskVals[i];
6108       if (idx != (int)i)
6109         InOrder[i/4] = false;
6110       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6111         continue;
6112       AllWordsInNewV = false;
6113       break;
6114     }
6115
6116     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6117     if (AllWordsInNewV) {
6118       for (int i = 0; i != 8; ++i) {
6119         int idx = MaskVals[i];
6120         if (idx < 0)
6121           continue;
6122         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6123         if ((idx != i) && idx < 4)
6124           pshufhw = false;
6125         if ((idx != i) && idx > 3)
6126           pshuflw = false;
6127       }
6128       V1 = NewV;
6129       V2Used = false;
6130       BestLoQuad = 0;
6131       BestHiQuad = 1;
6132     }
6133
6134     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6135     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6136     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6137       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6138       unsigned TargetMask = 0;
6139       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6140                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6141       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6142       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6143                              getShufflePSHUFLWImmediate(SVOp);
6144       V1 = NewV.getOperand(0);
6145       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6146     }
6147   }
6148
6149   // Promote splats to a larger type which usually leads to more efficient code.
6150   // FIXME: Is this true if pshufb is available?
6151   if (SVOp->isSplat())
6152     return PromoteSplat(SVOp, DAG);
6153
6154   // If we have SSSE3, and all words of the result are from 1 input vector,
6155   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6156   // is present, fall back to case 4.
6157   if (Subtarget->hasSSSE3()) {
6158     SmallVector<SDValue,16> pshufbMask;
6159
6160     // If we have elements from both input vectors, set the high bit of the
6161     // shuffle mask element to zero out elements that come from V2 in the V1
6162     // mask, and elements that come from V1 in the V2 mask, so that the two
6163     // results can be OR'd together.
6164     bool TwoInputs = V1Used && V2Used;
6165     for (unsigned i = 0; i != 8; ++i) {
6166       int EltIdx = MaskVals[i] * 2;
6167       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6168       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6169       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6170       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6171     }
6172     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6173     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6174                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6175                                  MVT::v16i8, &pshufbMask[0], 16));
6176     if (!TwoInputs)
6177       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6178
6179     // Calculate the shuffle mask for the second input, shuffle it, and
6180     // OR it with the first shuffled input.
6181     pshufbMask.clear();
6182     for (unsigned i = 0; i != 8; ++i) {
6183       int EltIdx = MaskVals[i] * 2;
6184       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6185       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6186       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6187       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6188     }
6189     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6190     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6191                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6192                                  MVT::v16i8, &pshufbMask[0], 16));
6193     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6194     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6195   }
6196
6197   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6198   // and update MaskVals with new element order.
6199   std::bitset<8> InOrder;
6200   if (BestLoQuad >= 0) {
6201     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6202     for (int i = 0; i != 4; ++i) {
6203       int idx = MaskVals[i];
6204       if (idx < 0) {
6205         InOrder.set(i);
6206       } else if ((idx / 4) == BestLoQuad) {
6207         MaskV[i] = idx & 3;
6208         InOrder.set(i);
6209       }
6210     }
6211     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6212                                 &MaskV[0]);
6213
6214     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6215       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6216       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6217                                   NewV.getOperand(0),
6218                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6219     }
6220   }
6221
6222   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6223   // and update MaskVals with the new element order.
6224   if (BestHiQuad >= 0) {
6225     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6226     for (unsigned i = 4; i != 8; ++i) {
6227       int idx = MaskVals[i];
6228       if (idx < 0) {
6229         InOrder.set(i);
6230       } else if ((idx / 4) == BestHiQuad) {
6231         MaskV[i] = (idx & 3) + 4;
6232         InOrder.set(i);
6233       }
6234     }
6235     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6236                                 &MaskV[0]);
6237
6238     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6239       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6240       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6241                                   NewV.getOperand(0),
6242                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6243     }
6244   }
6245
6246   // In case BestHi & BestLo were both -1, which means each quadword has a word
6247   // from each of the four input quadwords, calculate the InOrder bitvector now
6248   // before falling through to the insert/extract cleanup.
6249   if (BestLoQuad == -1 && BestHiQuad == -1) {
6250     NewV = V1;
6251     for (int i = 0; i != 8; ++i)
6252       if (MaskVals[i] < 0 || MaskVals[i] == i)
6253         InOrder.set(i);
6254   }
6255
6256   // The other elements are put in the right place using pextrw and pinsrw.
6257   for (unsigned i = 0; i != 8; ++i) {
6258     if (InOrder[i])
6259       continue;
6260     int EltIdx = MaskVals[i];
6261     if (EltIdx < 0)
6262       continue;
6263     SDValue ExtOp = (EltIdx < 8) ?
6264       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6265                   DAG.getIntPtrConstant(EltIdx)) :
6266       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6267                   DAG.getIntPtrConstant(EltIdx - 8));
6268     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6269                        DAG.getIntPtrConstant(i));
6270   }
6271   return NewV;
6272 }
6273
6274 // v16i8 shuffles - Prefer shuffles in the following order:
6275 // 1. [ssse3] 1 x pshufb
6276 // 2. [ssse3] 2 x pshufb + 1 x por
6277 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6278 static
6279 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6280                                  SelectionDAG &DAG,
6281                                  const X86TargetLowering &TLI) {
6282   SDValue V1 = SVOp->getOperand(0);
6283   SDValue V2 = SVOp->getOperand(1);
6284   SDLoc dl(SVOp);
6285   ArrayRef<int> MaskVals = SVOp->getMask();
6286
6287   // Promote splats to a larger type which usually leads to more efficient code.
6288   // FIXME: Is this true if pshufb is available?
6289   if (SVOp->isSplat())
6290     return PromoteSplat(SVOp, DAG);
6291
6292   // If we have SSSE3, case 1 is generated when all result bytes come from
6293   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6294   // present, fall back to case 3.
6295
6296   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6297   if (TLI.getSubtarget()->hasSSSE3()) {
6298     SmallVector<SDValue,16> pshufbMask;
6299
6300     // If all result elements are from one input vector, then only translate
6301     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6302     //
6303     // Otherwise, we have elements from both input vectors, and must zero out
6304     // elements that come from V2 in the first mask, and V1 in the second mask
6305     // so that we can OR them together.
6306     for (unsigned i = 0; i != 16; ++i) {
6307       int EltIdx = MaskVals[i];
6308       if (EltIdx < 0 || EltIdx >= 16)
6309         EltIdx = 0x80;
6310       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6311     }
6312     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6313                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6314                                  MVT::v16i8, &pshufbMask[0], 16));
6315
6316     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6317     // the 2nd operand if it's undefined or zero.
6318     if (V2.getOpcode() == ISD::UNDEF ||
6319         ISD::isBuildVectorAllZeros(V2.getNode()))
6320       return V1;
6321
6322     // Calculate the shuffle mask for the second input, shuffle it, and
6323     // OR it with the first shuffled input.
6324     pshufbMask.clear();
6325     for (unsigned i = 0; i != 16; ++i) {
6326       int EltIdx = MaskVals[i];
6327       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6328       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6329     }
6330     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6331                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6332                                  MVT::v16i8, &pshufbMask[0], 16));
6333     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6334   }
6335
6336   // No SSSE3 - Calculate in place words and then fix all out of place words
6337   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6338   // the 16 different words that comprise the two doublequadword input vectors.
6339   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6340   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6341   SDValue NewV = V1;
6342   for (int i = 0; i != 8; ++i) {
6343     int Elt0 = MaskVals[i*2];
6344     int Elt1 = MaskVals[i*2+1];
6345
6346     // This word of the result is all undef, skip it.
6347     if (Elt0 < 0 && Elt1 < 0)
6348       continue;
6349
6350     // This word of the result is already in the correct place, skip it.
6351     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6352       continue;
6353
6354     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6355     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6356     SDValue InsElt;
6357
6358     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6359     // using a single extract together, load it and store it.
6360     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6361       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6362                            DAG.getIntPtrConstant(Elt1 / 2));
6363       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6364                         DAG.getIntPtrConstant(i));
6365       continue;
6366     }
6367
6368     // If Elt1 is defined, extract it from the appropriate source.  If the
6369     // source byte is not also odd, shift the extracted word left 8 bits
6370     // otherwise clear the bottom 8 bits if we need to do an or.
6371     if (Elt1 >= 0) {
6372       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6373                            DAG.getIntPtrConstant(Elt1 / 2));
6374       if ((Elt1 & 1) == 0)
6375         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6376                              DAG.getConstant(8,
6377                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6378       else if (Elt0 >= 0)
6379         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6380                              DAG.getConstant(0xFF00, MVT::i16));
6381     }
6382     // If Elt0 is defined, extract it from the appropriate source.  If the
6383     // source byte is not also even, shift the extracted word right 8 bits. If
6384     // Elt1 was also defined, OR the extracted values together before
6385     // inserting them in the result.
6386     if (Elt0 >= 0) {
6387       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6388                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6389       if ((Elt0 & 1) != 0)
6390         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6391                               DAG.getConstant(8,
6392                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6393       else if (Elt1 >= 0)
6394         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6395                              DAG.getConstant(0x00FF, MVT::i16));
6396       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6397                          : InsElt0;
6398     }
6399     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6400                        DAG.getIntPtrConstant(i));
6401   }
6402   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6403 }
6404
6405 // v32i8 shuffles - Translate to VPSHUFB if possible.
6406 static
6407 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6408                                  const X86Subtarget *Subtarget,
6409                                  SelectionDAG &DAG) {
6410   MVT VT = SVOp->getValueType(0).getSimpleVT();
6411   SDValue V1 = SVOp->getOperand(0);
6412   SDValue V2 = SVOp->getOperand(1);
6413   SDLoc dl(SVOp);
6414   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6415
6416   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6417   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6418   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6419
6420   // VPSHUFB may be generated if
6421   // (1) one of input vector is undefined or zeroinitializer.
6422   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6423   // And (2) the mask indexes don't cross the 128-bit lane.
6424   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6425       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6426     return SDValue();
6427
6428   if (V1IsAllZero && !V2IsAllZero) {
6429     CommuteVectorShuffleMask(MaskVals, 32);
6430     V1 = V2;
6431   }
6432   SmallVector<SDValue, 32> pshufbMask;
6433   for (unsigned i = 0; i != 32; i++) {
6434     int EltIdx = MaskVals[i];
6435     if (EltIdx < 0 || EltIdx >= 32)
6436       EltIdx = 0x80;
6437     else {
6438       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6439         // Cross lane is not allowed.
6440         return SDValue();
6441       EltIdx &= 0xf;
6442     }
6443     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6444   }
6445   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6446                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6447                                   MVT::v32i8, &pshufbMask[0], 32));
6448 }
6449
6450 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6451 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6452 /// done when every pair / quad of shuffle mask elements point to elements in
6453 /// the right sequence. e.g.
6454 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6455 static
6456 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6457                                  SelectionDAG &DAG) {
6458   MVT VT = SVOp->getValueType(0).getSimpleVT();
6459   SDLoc dl(SVOp);
6460   unsigned NumElems = VT.getVectorNumElements();
6461   MVT NewVT;
6462   unsigned Scale;
6463   switch (VT.SimpleTy) {
6464   default: llvm_unreachable("Unexpected!");
6465   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6466   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6467   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6468   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6469   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6470   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6471   }
6472
6473   SmallVector<int, 8> MaskVec;
6474   for (unsigned i = 0; i != NumElems; i += Scale) {
6475     int StartIdx = -1;
6476     for (unsigned j = 0; j != Scale; ++j) {
6477       int EltIdx = SVOp->getMaskElt(i+j);
6478       if (EltIdx < 0)
6479         continue;
6480       if (StartIdx < 0)
6481         StartIdx = (EltIdx / Scale);
6482       if (EltIdx != (int)(StartIdx*Scale + j))
6483         return SDValue();
6484     }
6485     MaskVec.push_back(StartIdx);
6486   }
6487
6488   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6489   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6490   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6491 }
6492
6493 /// getVZextMovL - Return a zero-extending vector move low node.
6494 ///
6495 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6496                             SDValue SrcOp, SelectionDAG &DAG,
6497                             const X86Subtarget *Subtarget, SDLoc dl) {
6498   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6499     LoadSDNode *LD = NULL;
6500     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6501       LD = dyn_cast<LoadSDNode>(SrcOp);
6502     if (!LD) {
6503       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6504       // instead.
6505       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6506       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6507           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6508           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6509           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6510         // PR2108
6511         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6512         return DAG.getNode(ISD::BITCAST, dl, VT,
6513                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6514                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6515                                                    OpVT,
6516                                                    SrcOp.getOperand(0)
6517                                                           .getOperand(0))));
6518       }
6519     }
6520   }
6521
6522   return DAG.getNode(ISD::BITCAST, dl, VT,
6523                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6524                                  DAG.getNode(ISD::BITCAST, dl,
6525                                              OpVT, SrcOp)));
6526 }
6527
6528 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6529 /// which could not be matched by any known target speficic shuffle
6530 static SDValue
6531 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6532
6533   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6534   if (NewOp.getNode())
6535     return NewOp;
6536
6537   MVT VT = SVOp->getValueType(0).getSimpleVT();
6538
6539   unsigned NumElems = VT.getVectorNumElements();
6540   unsigned NumLaneElems = NumElems / 2;
6541
6542   SDLoc dl(SVOp);
6543   MVT EltVT = VT.getVectorElementType();
6544   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6545   SDValue Output[2];
6546
6547   SmallVector<int, 16> Mask;
6548   for (unsigned l = 0; l < 2; ++l) {
6549     // Build a shuffle mask for the output, discovering on the fly which
6550     // input vectors to use as shuffle operands (recorded in InputUsed).
6551     // If building a suitable shuffle vector proves too hard, then bail
6552     // out with UseBuildVector set.
6553     bool UseBuildVector = false;
6554     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6555     unsigned LaneStart = l * NumLaneElems;
6556     for (unsigned i = 0; i != NumLaneElems; ++i) {
6557       // The mask element.  This indexes into the input.
6558       int Idx = SVOp->getMaskElt(i+LaneStart);
6559       if (Idx < 0) {
6560         // the mask element does not index into any input vector.
6561         Mask.push_back(-1);
6562         continue;
6563       }
6564
6565       // The input vector this mask element indexes into.
6566       int Input = Idx / NumLaneElems;
6567
6568       // Turn the index into an offset from the start of the input vector.
6569       Idx -= Input * NumLaneElems;
6570
6571       // Find or create a shuffle vector operand to hold this input.
6572       unsigned OpNo;
6573       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6574         if (InputUsed[OpNo] == Input)
6575           // This input vector is already an operand.
6576           break;
6577         if (InputUsed[OpNo] < 0) {
6578           // Create a new operand for this input vector.
6579           InputUsed[OpNo] = Input;
6580           break;
6581         }
6582       }
6583
6584       if (OpNo >= array_lengthof(InputUsed)) {
6585         // More than two input vectors used!  Give up on trying to create a
6586         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6587         UseBuildVector = true;
6588         break;
6589       }
6590
6591       // Add the mask index for the new shuffle vector.
6592       Mask.push_back(Idx + OpNo * NumLaneElems);
6593     }
6594
6595     if (UseBuildVector) {
6596       SmallVector<SDValue, 16> SVOps;
6597       for (unsigned i = 0; i != NumLaneElems; ++i) {
6598         // The mask element.  This indexes into the input.
6599         int Idx = SVOp->getMaskElt(i+LaneStart);
6600         if (Idx < 0) {
6601           SVOps.push_back(DAG.getUNDEF(EltVT));
6602           continue;
6603         }
6604
6605         // The input vector this mask element indexes into.
6606         int Input = Idx / NumElems;
6607
6608         // Turn the index into an offset from the start of the input vector.
6609         Idx -= Input * NumElems;
6610
6611         // Extract the vector element by hand.
6612         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6613                                     SVOp->getOperand(Input),
6614                                     DAG.getIntPtrConstant(Idx)));
6615       }
6616
6617       // Construct the output using a BUILD_VECTOR.
6618       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6619                               SVOps.size());
6620     } else if (InputUsed[0] < 0) {
6621       // No input vectors were used! The result is undefined.
6622       Output[l] = DAG.getUNDEF(NVT);
6623     } else {
6624       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6625                                         (InputUsed[0] % 2) * NumLaneElems,
6626                                         DAG, dl);
6627       // If only one input was used, use an undefined vector for the other.
6628       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6629         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6630                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6631       // At least one input vector was used. Create a new shuffle vector.
6632       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6633     }
6634
6635     Mask.clear();
6636   }
6637
6638   // Concatenate the result back
6639   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6640 }
6641
6642 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6643 /// 4 elements, and match them with several different shuffle types.
6644 static SDValue
6645 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6646   SDValue V1 = SVOp->getOperand(0);
6647   SDValue V2 = SVOp->getOperand(1);
6648   SDLoc dl(SVOp);
6649   MVT VT = SVOp->getValueType(0).getSimpleVT();
6650
6651   assert(VT.is128BitVector() && "Unsupported vector size");
6652
6653   std::pair<int, int> Locs[4];
6654   int Mask1[] = { -1, -1, -1, -1 };
6655   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6656
6657   unsigned NumHi = 0;
6658   unsigned NumLo = 0;
6659   for (unsigned i = 0; i != 4; ++i) {
6660     int Idx = PermMask[i];
6661     if (Idx < 0) {
6662       Locs[i] = std::make_pair(-1, -1);
6663     } else {
6664       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6665       if (Idx < 4) {
6666         Locs[i] = std::make_pair(0, NumLo);
6667         Mask1[NumLo] = Idx;
6668         NumLo++;
6669       } else {
6670         Locs[i] = std::make_pair(1, NumHi);
6671         if (2+NumHi < 4)
6672           Mask1[2+NumHi] = Idx;
6673         NumHi++;
6674       }
6675     }
6676   }
6677
6678   if (NumLo <= 2 && NumHi <= 2) {
6679     // If no more than two elements come from either vector. This can be
6680     // implemented with two shuffles. First shuffle gather the elements.
6681     // The second shuffle, which takes the first shuffle as both of its
6682     // vector operands, put the elements into the right order.
6683     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6684
6685     int Mask2[] = { -1, -1, -1, -1 };
6686
6687     for (unsigned i = 0; i != 4; ++i)
6688       if (Locs[i].first != -1) {
6689         unsigned Idx = (i < 2) ? 0 : 4;
6690         Idx += Locs[i].first * 2 + Locs[i].second;
6691         Mask2[i] = Idx;
6692       }
6693
6694     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6695   }
6696
6697   if (NumLo == 3 || NumHi == 3) {
6698     // Otherwise, we must have three elements from one vector, call it X, and
6699     // one element from the other, call it Y.  First, use a shufps to build an
6700     // intermediate vector with the one element from Y and the element from X
6701     // that will be in the same half in the final destination (the indexes don't
6702     // matter). Then, use a shufps to build the final vector, taking the half
6703     // containing the element from Y from the intermediate, and the other half
6704     // from X.
6705     if (NumHi == 3) {
6706       // Normalize it so the 3 elements come from V1.
6707       CommuteVectorShuffleMask(PermMask, 4);
6708       std::swap(V1, V2);
6709     }
6710
6711     // Find the element from V2.
6712     unsigned HiIndex;
6713     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6714       int Val = PermMask[HiIndex];
6715       if (Val < 0)
6716         continue;
6717       if (Val >= 4)
6718         break;
6719     }
6720
6721     Mask1[0] = PermMask[HiIndex];
6722     Mask1[1] = -1;
6723     Mask1[2] = PermMask[HiIndex^1];
6724     Mask1[3] = -1;
6725     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6726
6727     if (HiIndex >= 2) {
6728       Mask1[0] = PermMask[0];
6729       Mask1[1] = PermMask[1];
6730       Mask1[2] = HiIndex & 1 ? 6 : 4;
6731       Mask1[3] = HiIndex & 1 ? 4 : 6;
6732       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6733     }
6734
6735     Mask1[0] = HiIndex & 1 ? 2 : 0;
6736     Mask1[1] = HiIndex & 1 ? 0 : 2;
6737     Mask1[2] = PermMask[2];
6738     Mask1[3] = PermMask[3];
6739     if (Mask1[2] >= 0)
6740       Mask1[2] += 4;
6741     if (Mask1[3] >= 0)
6742       Mask1[3] += 4;
6743     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6744   }
6745
6746   // Break it into (shuffle shuffle_hi, shuffle_lo).
6747   int LoMask[] = { -1, -1, -1, -1 };
6748   int HiMask[] = { -1, -1, -1, -1 };
6749
6750   int *MaskPtr = LoMask;
6751   unsigned MaskIdx = 0;
6752   unsigned LoIdx = 0;
6753   unsigned HiIdx = 2;
6754   for (unsigned i = 0; i != 4; ++i) {
6755     if (i == 2) {
6756       MaskPtr = HiMask;
6757       MaskIdx = 1;
6758       LoIdx = 0;
6759       HiIdx = 2;
6760     }
6761     int Idx = PermMask[i];
6762     if (Idx < 0) {
6763       Locs[i] = std::make_pair(-1, -1);
6764     } else if (Idx < 4) {
6765       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6766       MaskPtr[LoIdx] = Idx;
6767       LoIdx++;
6768     } else {
6769       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6770       MaskPtr[HiIdx] = Idx;
6771       HiIdx++;
6772     }
6773   }
6774
6775   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6776   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6777   int MaskOps[] = { -1, -1, -1, -1 };
6778   for (unsigned i = 0; i != 4; ++i)
6779     if (Locs[i].first != -1)
6780       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6781   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6782 }
6783
6784 static bool MayFoldVectorLoad(SDValue V) {
6785   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6786     V = V.getOperand(0);
6787
6788   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6789     V = V.getOperand(0);
6790   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6791       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6792     // BUILD_VECTOR (load), undef
6793     V = V.getOperand(0);
6794
6795   return MayFoldLoad(V);
6796 }
6797
6798 static
6799 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6800   EVT VT = Op.getValueType();
6801
6802   // Canonizalize to v2f64.
6803   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6804   return DAG.getNode(ISD::BITCAST, dl, VT,
6805                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6806                                           V1, DAG));
6807 }
6808
6809 static
6810 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6811                         bool HasSSE2) {
6812   SDValue V1 = Op.getOperand(0);
6813   SDValue V2 = Op.getOperand(1);
6814   EVT VT = Op.getValueType();
6815
6816   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6817
6818   if (HasSSE2 && VT == MVT::v2f64)
6819     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6820
6821   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6822   return DAG.getNode(ISD::BITCAST, dl, VT,
6823                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6824                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6825                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6826 }
6827
6828 static
6829 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6830   SDValue V1 = Op.getOperand(0);
6831   SDValue V2 = Op.getOperand(1);
6832   EVT VT = Op.getValueType();
6833
6834   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6835          "unsupported shuffle type");
6836
6837   if (V2.getOpcode() == ISD::UNDEF)
6838     V2 = V1;
6839
6840   // v4i32 or v4f32
6841   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6842 }
6843
6844 static
6845 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6846   SDValue V1 = Op.getOperand(0);
6847   SDValue V2 = Op.getOperand(1);
6848   EVT VT = Op.getValueType();
6849   unsigned NumElems = VT.getVectorNumElements();
6850
6851   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6852   // operand of these instructions is only memory, so check if there's a
6853   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6854   // same masks.
6855   bool CanFoldLoad = false;
6856
6857   // Trivial case, when V2 comes from a load.
6858   if (MayFoldVectorLoad(V2))
6859     CanFoldLoad = true;
6860
6861   // When V1 is a load, it can be folded later into a store in isel, example:
6862   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6863   //    turns into:
6864   //  (MOVLPSmr addr:$src1, VR128:$src2)
6865   // So, recognize this potential and also use MOVLPS or MOVLPD
6866   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6867     CanFoldLoad = true;
6868
6869   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6870   if (CanFoldLoad) {
6871     if (HasSSE2 && NumElems == 2)
6872       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6873
6874     if (NumElems == 4)
6875       // If we don't care about the second element, proceed to use movss.
6876       if (SVOp->getMaskElt(1) != -1)
6877         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6878   }
6879
6880   // movl and movlp will both match v2i64, but v2i64 is never matched by
6881   // movl earlier because we make it strict to avoid messing with the movlp load
6882   // folding logic (see the code above getMOVLP call). Match it here then,
6883   // this is horrible, but will stay like this until we move all shuffle
6884   // matching to x86 specific nodes. Note that for the 1st condition all
6885   // types are matched with movsd.
6886   if (HasSSE2) {
6887     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6888     // as to remove this logic from here, as much as possible
6889     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6890       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6891     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6892   }
6893
6894   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6895
6896   // Invert the operand order and use SHUFPS to match it.
6897   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6898                               getShuffleSHUFImmediate(SVOp), DAG);
6899 }
6900
6901 // Reduce a vector shuffle to zext.
6902 SDValue
6903 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6904   // PMOVZX is only available from SSE41.
6905   if (!Subtarget->hasSSE41())
6906     return SDValue();
6907
6908   EVT VT = Op.getValueType();
6909
6910   // Only AVX2 support 256-bit vector integer extending.
6911   if (!Subtarget->hasInt256() && VT.is256BitVector())
6912     return SDValue();
6913
6914   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6915   SDLoc DL(Op);
6916   SDValue V1 = Op.getOperand(0);
6917   SDValue V2 = Op.getOperand(1);
6918   unsigned NumElems = VT.getVectorNumElements();
6919
6920   // Extending is an unary operation and the element type of the source vector
6921   // won't be equal to or larger than i64.
6922   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6923       VT.getVectorElementType() == MVT::i64)
6924     return SDValue();
6925
6926   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6927   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6928   while ((1U << Shift) < NumElems) {
6929     if (SVOp->getMaskElt(1U << Shift) == 1)
6930       break;
6931     Shift += 1;
6932     // The maximal ratio is 8, i.e. from i8 to i64.
6933     if (Shift > 3)
6934       return SDValue();
6935   }
6936
6937   // Check the shuffle mask.
6938   unsigned Mask = (1U << Shift) - 1;
6939   for (unsigned i = 0; i != NumElems; ++i) {
6940     int EltIdx = SVOp->getMaskElt(i);
6941     if ((i & Mask) != 0 && EltIdx != -1)
6942       return SDValue();
6943     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6944       return SDValue();
6945   }
6946
6947   LLVMContext *Context = DAG.getContext();
6948   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6949   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6950   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6951
6952   if (!isTypeLegal(NVT))
6953     return SDValue();
6954
6955   // Simplify the operand as it's prepared to be fed into shuffle.
6956   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6957   if (V1.getOpcode() == ISD::BITCAST &&
6958       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6959       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6960       V1.getOperand(0)
6961         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6962     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6963     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6964     ConstantSDNode *CIdx =
6965       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6966     // If it's foldable, i.e. normal load with single use, we will let code
6967     // selection to fold it. Otherwise, we will short the conversion sequence.
6968     if (CIdx && CIdx->getZExtValue() == 0 &&
6969         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6970       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6971         // The "ext_vec_elt" node is wider than the result node.
6972         // In this case we should extract subvector from V.
6973         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6974         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6975         EVT FullVT = V.getValueType();
6976         EVT SubVecVT = EVT::getVectorVT(*Context,
6977                                         FullVT.getVectorElementType(),
6978                                         FullVT.getVectorNumElements()/Ratio);
6979         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6980                         DAG.getIntPtrConstant(0));
6981       }
6982       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6983     }
6984   }
6985
6986   return DAG.getNode(ISD::BITCAST, DL, VT,
6987                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6988 }
6989
6990 SDValue
6991 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6992   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6993   MVT VT = Op.getValueType().getSimpleVT();
6994   SDLoc dl(Op);
6995   SDValue V1 = Op.getOperand(0);
6996   SDValue V2 = Op.getOperand(1);
6997
6998   if (isZeroShuffle(SVOp))
6999     return getZeroVector(VT, Subtarget, DAG, dl);
7000
7001   // Handle splat operations
7002   if (SVOp->isSplat()) {
7003     // Use vbroadcast whenever the splat comes from a foldable load
7004     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7005     if (Broadcast.getNode())
7006       return Broadcast;
7007   }
7008
7009   // Check integer expanding shuffles.
7010   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7011   if (NewOp.getNode())
7012     return NewOp;
7013
7014   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7015   // do it!
7016   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7017       VT == MVT::v16i16 || VT == MVT::v32i8) {
7018     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7019     if (NewOp.getNode())
7020       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7021   } else if ((VT == MVT::v4i32 ||
7022              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7023     // FIXME: Figure out a cleaner way to do this.
7024     // Try to make use of movq to zero out the top part.
7025     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7026       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7027       if (NewOp.getNode()) {
7028         MVT NewVT = NewOp.getValueType().getSimpleVT();
7029         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7030                                NewVT, true, false))
7031           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7032                               DAG, Subtarget, dl);
7033       }
7034     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7035       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7036       if (NewOp.getNode()) {
7037         MVT NewVT = NewOp.getValueType().getSimpleVT();
7038         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7039           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7040                               DAG, Subtarget, dl);
7041       }
7042     }
7043   }
7044   return SDValue();
7045 }
7046
7047 SDValue
7048 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7049   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7050   SDValue V1 = Op.getOperand(0);
7051   SDValue V2 = Op.getOperand(1);
7052   MVT VT = Op.getValueType().getSimpleVT();
7053   SDLoc dl(Op);
7054   unsigned NumElems = VT.getVectorNumElements();
7055   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7056   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7057   bool V1IsSplat = false;
7058   bool V2IsSplat = false;
7059   bool HasSSE2 = Subtarget->hasSSE2();
7060   bool HasFp256    = Subtarget->hasFp256();
7061   bool HasInt256   = Subtarget->hasInt256();
7062   MachineFunction &MF = DAG.getMachineFunction();
7063   bool OptForSize = MF.getFunction()->getAttributes().
7064     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7065
7066   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7067
7068   if (V1IsUndef && V2IsUndef)
7069     return DAG.getUNDEF(VT);
7070
7071   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7072
7073   // Vector shuffle lowering takes 3 steps:
7074   //
7075   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7076   //    narrowing and commutation of operands should be handled.
7077   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7078   //    shuffle nodes.
7079   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7080   //    so the shuffle can be broken into other shuffles and the legalizer can
7081   //    try the lowering again.
7082   //
7083   // The general idea is that no vector_shuffle operation should be left to
7084   // be matched during isel, all of them must be converted to a target specific
7085   // node here.
7086
7087   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7088   // narrowing and commutation of operands should be handled. The actual code
7089   // doesn't include all of those, work in progress...
7090   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7091   if (NewOp.getNode())
7092     return NewOp;
7093
7094   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7095
7096   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7097   // unpckh_undef). Only use pshufd if speed is more important than size.
7098   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7099     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7100   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7101     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7102
7103   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7104       V2IsUndef && MayFoldVectorLoad(V1))
7105     return getMOVDDup(Op, dl, V1, DAG);
7106
7107   if (isMOVHLPS_v_undef_Mask(M, VT))
7108     return getMOVHighToLow(Op, dl, DAG);
7109
7110   // Use to match splats
7111   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7112       (VT == MVT::v2f64 || VT == MVT::v2i64))
7113     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7114
7115   if (isPSHUFDMask(M, VT)) {
7116     // The actual implementation will match the mask in the if above and then
7117     // during isel it can match several different instructions, not only pshufd
7118     // as its name says, sad but true, emulate the behavior for now...
7119     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7120       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7121
7122     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7123
7124     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7125       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7126
7127     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7128       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7129                                   DAG);
7130
7131     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7132                                 TargetMask, DAG);
7133   }
7134
7135   if (isPALIGNRMask(M, VT, Subtarget))
7136     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7137                                 getShufflePALIGNRImmediate(SVOp),
7138                                 DAG);
7139
7140   // Check if this can be converted into a logical shift.
7141   bool isLeft = false;
7142   unsigned ShAmt = 0;
7143   SDValue ShVal;
7144   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7145   if (isShift && ShVal.hasOneUse()) {
7146     // If the shifted value has multiple uses, it may be cheaper to use
7147     // v_set0 + movlhps or movhlps, etc.
7148     MVT EltVT = VT.getVectorElementType();
7149     ShAmt *= EltVT.getSizeInBits();
7150     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7151   }
7152
7153   if (isMOVLMask(M, VT)) {
7154     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7155       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7156     if (!isMOVLPMask(M, VT)) {
7157       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7158         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7159
7160       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7161         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7162     }
7163   }
7164
7165   // FIXME: fold these into legal mask.
7166   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7167     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7168
7169   if (isMOVHLPSMask(M, VT))
7170     return getMOVHighToLow(Op, dl, DAG);
7171
7172   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7173     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7174
7175   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7176     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7177
7178   if (isMOVLPMask(M, VT))
7179     return getMOVLP(Op, dl, DAG, HasSSE2);
7180
7181   if (ShouldXformToMOVHLPS(M, VT) ||
7182       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7183     return CommuteVectorShuffle(SVOp, DAG);
7184
7185   if (isShift) {
7186     // No better options. Use a vshldq / vsrldq.
7187     MVT EltVT = VT.getVectorElementType();
7188     ShAmt *= EltVT.getSizeInBits();
7189     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7190   }
7191
7192   bool Commuted = false;
7193   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7194   // 1,1,1,1 -> v8i16 though.
7195   V1IsSplat = isSplatVector(V1.getNode());
7196   V2IsSplat = isSplatVector(V2.getNode());
7197
7198   // Canonicalize the splat or undef, if present, to be on the RHS.
7199   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7200     CommuteVectorShuffleMask(M, NumElems);
7201     std::swap(V1, V2);
7202     std::swap(V1IsSplat, V2IsSplat);
7203     Commuted = true;
7204   }
7205
7206   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7207     // Shuffling low element of v1 into undef, just return v1.
7208     if (V2IsUndef)
7209       return V1;
7210     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7211     // the instruction selector will not match, so get a canonical MOVL with
7212     // swapped operands to undo the commute.
7213     return getMOVL(DAG, dl, VT, V2, V1);
7214   }
7215
7216   if (isUNPCKLMask(M, VT, HasInt256))
7217     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7218
7219   if (isUNPCKHMask(M, VT, HasInt256))
7220     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7221
7222   if (V2IsSplat) {
7223     // Normalize mask so all entries that point to V2 points to its first
7224     // element then try to match unpck{h|l} again. If match, return a
7225     // new vector_shuffle with the corrected mask.p
7226     SmallVector<int, 8> NewMask(M.begin(), M.end());
7227     NormalizeMask(NewMask, NumElems);
7228     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7229       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7230     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7231       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7232   }
7233
7234   if (Commuted) {
7235     // Commute is back and try unpck* again.
7236     // FIXME: this seems wrong.
7237     CommuteVectorShuffleMask(M, NumElems);
7238     std::swap(V1, V2);
7239     std::swap(V1IsSplat, V2IsSplat);
7240     Commuted = false;
7241
7242     if (isUNPCKLMask(M, VT, HasInt256))
7243       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7244
7245     if (isUNPCKHMask(M, VT, HasInt256))
7246       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7247   }
7248
7249   // Normalize the node to match x86 shuffle ops if needed
7250   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7251     return CommuteVectorShuffle(SVOp, DAG);
7252
7253   // The checks below are all present in isShuffleMaskLegal, but they are
7254   // inlined here right now to enable us to directly emit target specific
7255   // nodes, and remove one by one until they don't return Op anymore.
7256
7257   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7258       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7259     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7260       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7261   }
7262
7263   if (isPSHUFHWMask(M, VT, HasInt256))
7264     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7265                                 getShufflePSHUFHWImmediate(SVOp),
7266                                 DAG);
7267
7268   if (isPSHUFLWMask(M, VT, HasInt256))
7269     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7270                                 getShufflePSHUFLWImmediate(SVOp),
7271                                 DAG);
7272
7273   if (isSHUFPMask(M, VT, HasFp256))
7274     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7275                                 getShuffleSHUFImmediate(SVOp), DAG);
7276
7277   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7278     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7279   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7280     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7281
7282   //===--------------------------------------------------------------------===//
7283   // Generate target specific nodes for 128 or 256-bit shuffles only
7284   // supported in the AVX instruction set.
7285   //
7286
7287   // Handle VMOVDDUPY permutations
7288   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7289     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7290
7291   // Handle VPERMILPS/D* permutations
7292   if (isVPERMILPMask(M, VT, HasFp256)) {
7293     if (HasInt256 && VT == MVT::v8i32)
7294       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7295                                   getShuffleSHUFImmediate(SVOp), DAG);
7296     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7297                                 getShuffleSHUFImmediate(SVOp), DAG);
7298   }
7299
7300   // Handle VPERM2F128/VPERM2I128 permutations
7301   if (isVPERM2X128Mask(M, VT, HasFp256))
7302     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7303                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7304
7305   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7306   if (BlendOp.getNode())
7307     return BlendOp;
7308
7309   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7310     SmallVector<SDValue, 8> permclMask;
7311     for (unsigned i = 0; i != 8; ++i) {
7312       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7313     }
7314     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7315                                &permclMask[0], 8);
7316     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7317     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7318                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7319   }
7320
7321   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7322     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7323                                 getShuffleCLImmediate(SVOp), DAG);
7324
7325   //===--------------------------------------------------------------------===//
7326   // Since no target specific shuffle was selected for this generic one,
7327   // lower it into other known shuffles. FIXME: this isn't true yet, but
7328   // this is the plan.
7329   //
7330
7331   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7332   if (VT == MVT::v8i16) {
7333     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7334     if (NewOp.getNode())
7335       return NewOp;
7336   }
7337
7338   if (VT == MVT::v16i8) {
7339     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7340     if (NewOp.getNode())
7341       return NewOp;
7342   }
7343
7344   if (VT == MVT::v32i8) {
7345     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7346     if (NewOp.getNode())
7347       return NewOp;
7348   }
7349
7350   // Handle all 128-bit wide vectors with 4 elements, and match them with
7351   // several different shuffle types.
7352   if (NumElems == 4 && VT.is128BitVector())
7353     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7354
7355   // Handle general 256-bit shuffles
7356   if (VT.is256BitVector())
7357     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7358
7359   return SDValue();
7360 }
7361
7362 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7363   MVT VT = Op.getValueType().getSimpleVT();
7364   SDLoc dl(Op);
7365
7366   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7367     return SDValue();
7368
7369   if (VT.getSizeInBits() == 8) {
7370     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7371                                   Op.getOperand(0), Op.getOperand(1));
7372     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7373                                   DAG.getValueType(VT));
7374     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7375   }
7376
7377   if (VT.getSizeInBits() == 16) {
7378     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7379     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7380     if (Idx == 0)
7381       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7382                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7383                                      DAG.getNode(ISD::BITCAST, dl,
7384                                                  MVT::v4i32,
7385                                                  Op.getOperand(0)),
7386                                      Op.getOperand(1)));
7387     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7388                                   Op.getOperand(0), Op.getOperand(1));
7389     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7390                                   DAG.getValueType(VT));
7391     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7392   }
7393
7394   if (VT == MVT::f32) {
7395     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7396     // the result back to FR32 register. It's only worth matching if the
7397     // result has a single use which is a store or a bitcast to i32.  And in
7398     // the case of a store, it's not worth it if the index is a constant 0,
7399     // because a MOVSSmr can be used instead, which is smaller and faster.
7400     if (!Op.hasOneUse())
7401       return SDValue();
7402     SDNode *User = *Op.getNode()->use_begin();
7403     if ((User->getOpcode() != ISD::STORE ||
7404          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7405           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7406         (User->getOpcode() != ISD::BITCAST ||
7407          User->getValueType(0) != MVT::i32))
7408       return SDValue();
7409     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7410                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7411                                               Op.getOperand(0)),
7412                                               Op.getOperand(1));
7413     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7414   }
7415
7416   if (VT == MVT::i32 || VT == MVT::i64) {
7417     // ExtractPS/pextrq works with constant index.
7418     if (isa<ConstantSDNode>(Op.getOperand(1)))
7419       return Op;
7420   }
7421   return SDValue();
7422 }
7423
7424 SDValue
7425 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7426                                            SelectionDAG &DAG) const {
7427   SDLoc dl(Op);
7428   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7429     return SDValue();
7430
7431   SDValue Vec = Op.getOperand(0);
7432   MVT VecVT = Vec.getValueType().getSimpleVT();
7433
7434   // If this is a 256-bit vector result, first extract the 128-bit vector and
7435   // then extract the element from the 128-bit vector.
7436   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7437     SDValue Idx = Op.getOperand(1);
7438     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7439
7440     // Get the 128-bit vector.
7441     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7442     EVT EltVT = VecVT.getVectorElementType();
7443
7444     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7445
7446     //if (IdxVal >= NumElems/2)
7447     //  IdxVal -= NumElems/2;
7448     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7449     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7450                        DAG.getConstant(IdxVal, MVT::i32));
7451   }
7452
7453   assert(VecVT.is128BitVector() && "Unexpected vector length");
7454
7455   if (Subtarget->hasSSE41()) {
7456     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7457     if (Res.getNode())
7458       return Res;
7459   }
7460
7461   MVT VT = Op.getValueType().getSimpleVT();
7462   // TODO: handle v16i8.
7463   if (VT.getSizeInBits() == 16) {
7464     SDValue Vec = Op.getOperand(0);
7465     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7466     if (Idx == 0)
7467       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7468                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7469                                      DAG.getNode(ISD::BITCAST, dl,
7470                                                  MVT::v4i32, Vec),
7471                                      Op.getOperand(1)));
7472     // Transform it so it match pextrw which produces a 32-bit result.
7473     MVT EltVT = MVT::i32;
7474     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7475                                   Op.getOperand(0), Op.getOperand(1));
7476     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7477                                   DAG.getValueType(VT));
7478     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7479   }
7480
7481   if (VT.getSizeInBits() == 32) {
7482     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7483     if (Idx == 0)
7484       return Op;
7485
7486     // SHUFPS the element to the lowest double word, then movss.
7487     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7488     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7489     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7490                                        DAG.getUNDEF(VVT), Mask);
7491     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7492                        DAG.getIntPtrConstant(0));
7493   }
7494
7495   if (VT.getSizeInBits() == 64) {
7496     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7497     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7498     //        to match extract_elt for f64.
7499     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7500     if (Idx == 0)
7501       return Op;
7502
7503     // UNPCKHPD the element to the lowest double word, then movsd.
7504     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7505     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7506     int Mask[2] = { 1, -1 };
7507     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7508     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7509                                        DAG.getUNDEF(VVT), Mask);
7510     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7511                        DAG.getIntPtrConstant(0));
7512   }
7513
7514   return SDValue();
7515 }
7516
7517 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7518   MVT VT = Op.getValueType().getSimpleVT();
7519   MVT EltVT = VT.getVectorElementType();
7520   SDLoc dl(Op);
7521
7522   SDValue N0 = Op.getOperand(0);
7523   SDValue N1 = Op.getOperand(1);
7524   SDValue N2 = Op.getOperand(2);
7525
7526   if (!VT.is128BitVector())
7527     return SDValue();
7528
7529   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7530       isa<ConstantSDNode>(N2)) {
7531     unsigned Opc;
7532     if (VT == MVT::v8i16)
7533       Opc = X86ISD::PINSRW;
7534     else if (VT == MVT::v16i8)
7535       Opc = X86ISD::PINSRB;
7536     else
7537       Opc = X86ISD::PINSRB;
7538
7539     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7540     // argument.
7541     if (N1.getValueType() != MVT::i32)
7542       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7543     if (N2.getValueType() != MVT::i32)
7544       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7545     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7546   }
7547
7548   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7549     // Bits [7:6] of the constant are the source select.  This will always be
7550     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7551     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7552     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7553     // Bits [5:4] of the constant are the destination select.  This is the
7554     //  value of the incoming immediate.
7555     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7556     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7557     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7558     // Create this as a scalar to vector..
7559     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7560     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7561   }
7562
7563   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7564     // PINSR* works with constant index.
7565     return Op;
7566   }
7567   return SDValue();
7568 }
7569
7570 SDValue
7571 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7572   MVT VT = Op.getValueType().getSimpleVT();
7573   MVT EltVT = VT.getVectorElementType();
7574
7575   SDLoc dl(Op);
7576   SDValue N0 = Op.getOperand(0);
7577   SDValue N1 = Op.getOperand(1);
7578   SDValue N2 = Op.getOperand(2);
7579
7580   // If this is a 256-bit vector result, first extract the 128-bit vector,
7581   // insert the element into the extracted half and then place it back.
7582   if (VT.is256BitVector() || VT.is512BitVector()) {
7583     if (!isa<ConstantSDNode>(N2))
7584       return SDValue();
7585
7586     // Get the desired 128-bit vector half.
7587     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7588     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7589
7590     // Insert the element into the desired half.
7591     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7592     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7593
7594     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7595                     DAG.getConstant(IdxIn128, MVT::i32));
7596
7597     // Insert the changed part back to the 256-bit vector
7598     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7599   }
7600
7601   if (Subtarget->hasSSE41())
7602     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7603
7604   if (EltVT == MVT::i8)
7605     return SDValue();
7606
7607   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7608     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7609     // as its second argument.
7610     if (N1.getValueType() != MVT::i32)
7611       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7612     if (N2.getValueType() != MVT::i32)
7613       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7614     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7615   }
7616   return SDValue();
7617 }
7618
7619 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7620   LLVMContext *Context = DAG.getContext();
7621   SDLoc dl(Op);
7622   MVT OpVT = Op.getValueType().getSimpleVT();
7623
7624   // If this is a 256-bit vector result, first insert into a 128-bit
7625   // vector and then insert into the 256-bit vector.
7626   if (!OpVT.is128BitVector()) {
7627     // Insert into a 128-bit vector.
7628     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7629     EVT VT128 = EVT::getVectorVT(*Context,
7630                                  OpVT.getVectorElementType(),
7631                                  OpVT.getVectorNumElements() / SizeFactor);
7632
7633     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7634
7635     // Insert the 128-bit vector.
7636     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7637   }
7638
7639   if (OpVT == MVT::v1i64 &&
7640       Op.getOperand(0).getValueType() == MVT::i64)
7641     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7642
7643   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7644   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7645   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7646                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7647 }
7648
7649 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7650 // a simple subregister reference or explicit instructions to grab
7651 // upper bits of a vector.
7652 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7653                                       SelectionDAG &DAG) {
7654   SDLoc dl(Op);
7655   SDValue In =  Op.getOperand(0);
7656   SDValue Idx = Op.getOperand(1);
7657   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7658   EVT ResVT   = Op.getValueType();
7659   EVT InVT    = In.getValueType();
7660
7661   if (Subtarget->hasFp256()) {
7662     if (ResVT.is128BitVector() &&
7663         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7664         isa<ConstantSDNode>(Idx)) {
7665       return Extract128BitVector(In, IdxVal, DAG, dl);
7666     }
7667     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7668         isa<ConstantSDNode>(Idx)) {
7669       return Extract256BitVector(In, IdxVal, DAG, dl);
7670     }
7671   }
7672   return SDValue();
7673 }
7674
7675 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7676 // simple superregister reference or explicit instructions to insert
7677 // the upper bits of a vector.
7678 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7679                                      SelectionDAG &DAG) {
7680   if (Subtarget->hasFp256()) {
7681     SDLoc dl(Op.getNode());
7682     SDValue Vec = Op.getNode()->getOperand(0);
7683     SDValue SubVec = Op.getNode()->getOperand(1);
7684     SDValue Idx = Op.getNode()->getOperand(2);
7685
7686     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7687          Op.getNode()->getValueType(0).is512BitVector()) &&
7688         SubVec.getNode()->getValueType(0).is128BitVector() &&
7689         isa<ConstantSDNode>(Idx)) {
7690       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7691       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7692     }
7693
7694     if (Op.getNode()->getValueType(0).is512BitVector() &&
7695         SubVec.getNode()->getValueType(0).is256BitVector() &&
7696         isa<ConstantSDNode>(Idx)) {
7697       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7698       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7699     }
7700   }
7701   return SDValue();
7702 }
7703
7704 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7705 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7706 // one of the above mentioned nodes. It has to be wrapped because otherwise
7707 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7708 // be used to form addressing mode. These wrapped nodes will be selected
7709 // into MOV32ri.
7710 SDValue
7711 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7712   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7713
7714   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7715   // global base reg.
7716   unsigned char OpFlag = 0;
7717   unsigned WrapperKind = X86ISD::Wrapper;
7718   CodeModel::Model M = getTargetMachine().getCodeModel();
7719
7720   if (Subtarget->isPICStyleRIPRel() &&
7721       (M == CodeModel::Small || M == CodeModel::Kernel))
7722     WrapperKind = X86ISD::WrapperRIP;
7723   else if (Subtarget->isPICStyleGOT())
7724     OpFlag = X86II::MO_GOTOFF;
7725   else if (Subtarget->isPICStyleStubPIC())
7726     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7727
7728   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7729                                              CP->getAlignment(),
7730                                              CP->getOffset(), OpFlag);
7731   SDLoc DL(CP);
7732   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7733   // With PIC, the address is actually $g + Offset.
7734   if (OpFlag) {
7735     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7736                          DAG.getNode(X86ISD::GlobalBaseReg,
7737                                      SDLoc(), getPointerTy()),
7738                          Result);
7739   }
7740
7741   return Result;
7742 }
7743
7744 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7745   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7746
7747   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7748   // global base reg.
7749   unsigned char OpFlag = 0;
7750   unsigned WrapperKind = X86ISD::Wrapper;
7751   CodeModel::Model M = getTargetMachine().getCodeModel();
7752
7753   if (Subtarget->isPICStyleRIPRel() &&
7754       (M == CodeModel::Small || M == CodeModel::Kernel))
7755     WrapperKind = X86ISD::WrapperRIP;
7756   else if (Subtarget->isPICStyleGOT())
7757     OpFlag = X86II::MO_GOTOFF;
7758   else if (Subtarget->isPICStyleStubPIC())
7759     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7760
7761   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7762                                           OpFlag);
7763   SDLoc DL(JT);
7764   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7765
7766   // With PIC, the address is actually $g + Offset.
7767   if (OpFlag)
7768     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7769                          DAG.getNode(X86ISD::GlobalBaseReg,
7770                                      SDLoc(), getPointerTy()),
7771                          Result);
7772
7773   return Result;
7774 }
7775
7776 SDValue
7777 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7778   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7779
7780   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7781   // global base reg.
7782   unsigned char OpFlag = 0;
7783   unsigned WrapperKind = X86ISD::Wrapper;
7784   CodeModel::Model M = getTargetMachine().getCodeModel();
7785
7786   if (Subtarget->isPICStyleRIPRel() &&
7787       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7788     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7789       OpFlag = X86II::MO_GOTPCREL;
7790     WrapperKind = X86ISD::WrapperRIP;
7791   } else if (Subtarget->isPICStyleGOT()) {
7792     OpFlag = X86II::MO_GOT;
7793   } else if (Subtarget->isPICStyleStubPIC()) {
7794     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7795   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7796     OpFlag = X86II::MO_DARWIN_NONLAZY;
7797   }
7798
7799   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7800
7801   SDLoc DL(Op);
7802   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7803
7804   // With PIC, the address is actually $g + Offset.
7805   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7806       !Subtarget->is64Bit()) {
7807     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7808                          DAG.getNode(X86ISD::GlobalBaseReg,
7809                                      SDLoc(), getPointerTy()),
7810                          Result);
7811   }
7812
7813   // For symbols that require a load from a stub to get the address, emit the
7814   // load.
7815   if (isGlobalStubReference(OpFlag))
7816     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7817                          MachinePointerInfo::getGOT(), false, false, false, 0);
7818
7819   return Result;
7820 }
7821
7822 SDValue
7823 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7824   // Create the TargetBlockAddressAddress node.
7825   unsigned char OpFlags =
7826     Subtarget->ClassifyBlockAddressReference();
7827   CodeModel::Model M = getTargetMachine().getCodeModel();
7828   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7829   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7830   SDLoc dl(Op);
7831   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7832                                              OpFlags);
7833
7834   if (Subtarget->isPICStyleRIPRel() &&
7835       (M == CodeModel::Small || M == CodeModel::Kernel))
7836     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7837   else
7838     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7839
7840   // With PIC, the address is actually $g + Offset.
7841   if (isGlobalRelativeToPICBase(OpFlags)) {
7842     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7843                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7844                          Result);
7845   }
7846
7847   return Result;
7848 }
7849
7850 SDValue
7851 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7852                                       int64_t Offset, SelectionDAG &DAG) const {
7853   // Create the TargetGlobalAddress node, folding in the constant
7854   // offset if it is legal.
7855   unsigned char OpFlags =
7856     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7857   CodeModel::Model M = getTargetMachine().getCodeModel();
7858   SDValue Result;
7859   if (OpFlags == X86II::MO_NO_FLAG &&
7860       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7861     // A direct static reference to a global.
7862     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7863     Offset = 0;
7864   } else {
7865     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7866   }
7867
7868   if (Subtarget->isPICStyleRIPRel() &&
7869       (M == CodeModel::Small || M == CodeModel::Kernel))
7870     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7871   else
7872     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7873
7874   // With PIC, the address is actually $g + Offset.
7875   if (isGlobalRelativeToPICBase(OpFlags)) {
7876     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7877                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7878                          Result);
7879   }
7880
7881   // For globals that require a load from a stub to get the address, emit the
7882   // load.
7883   if (isGlobalStubReference(OpFlags))
7884     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7885                          MachinePointerInfo::getGOT(), false, false, false, 0);
7886
7887   // If there was a non-zero offset that we didn't fold, create an explicit
7888   // addition for it.
7889   if (Offset != 0)
7890     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7891                          DAG.getConstant(Offset, getPointerTy()));
7892
7893   return Result;
7894 }
7895
7896 SDValue
7897 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7898   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7899   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7900   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7901 }
7902
7903 static SDValue
7904 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7905            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7906            unsigned char OperandFlags, bool LocalDynamic = false) {
7907   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7908   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7909   SDLoc dl(GA);
7910   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7911                                            GA->getValueType(0),
7912                                            GA->getOffset(),
7913                                            OperandFlags);
7914
7915   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7916                                            : X86ISD::TLSADDR;
7917
7918   if (InFlag) {
7919     SDValue Ops[] = { Chain,  TGA, *InFlag };
7920     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7921   } else {
7922     SDValue Ops[]  = { Chain, TGA };
7923     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7924   }
7925
7926   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7927   MFI->setAdjustsStack(true);
7928
7929   SDValue Flag = Chain.getValue(1);
7930   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7931 }
7932
7933 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7934 static SDValue
7935 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7936                                 const EVT PtrVT) {
7937   SDValue InFlag;
7938   SDLoc dl(GA);  // ? function entry point might be better
7939   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7940                                    DAG.getNode(X86ISD::GlobalBaseReg,
7941                                                SDLoc(), PtrVT), InFlag);
7942   InFlag = Chain.getValue(1);
7943
7944   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7945 }
7946
7947 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7948 static SDValue
7949 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7950                                 const EVT PtrVT) {
7951   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7952                     X86::RAX, X86II::MO_TLSGD);
7953 }
7954
7955 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7956                                            SelectionDAG &DAG,
7957                                            const EVT PtrVT,
7958                                            bool is64Bit) {
7959   SDLoc dl(GA);
7960
7961   // Get the start address of the TLS block for this module.
7962   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7963       .getInfo<X86MachineFunctionInfo>();
7964   MFI->incNumLocalDynamicTLSAccesses();
7965
7966   SDValue Base;
7967   if (is64Bit) {
7968     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7969                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7970   } else {
7971     SDValue InFlag;
7972     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7973         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7974     InFlag = Chain.getValue(1);
7975     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7976                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7977   }
7978
7979   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7980   // of Base.
7981
7982   // Build x@dtpoff.
7983   unsigned char OperandFlags = X86II::MO_DTPOFF;
7984   unsigned WrapperKind = X86ISD::Wrapper;
7985   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7986                                            GA->getValueType(0),
7987                                            GA->getOffset(), OperandFlags);
7988   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7989
7990   // Add x@dtpoff with the base.
7991   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7992 }
7993
7994 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7995 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7996                                    const EVT PtrVT, TLSModel::Model model,
7997                                    bool is64Bit, bool isPIC) {
7998   SDLoc dl(GA);
7999
8000   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8001   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8002                                                          is64Bit ? 257 : 256));
8003
8004   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8005                                       DAG.getIntPtrConstant(0),
8006                                       MachinePointerInfo(Ptr),
8007                                       false, false, false, 0);
8008
8009   unsigned char OperandFlags = 0;
8010   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8011   // initialexec.
8012   unsigned WrapperKind = X86ISD::Wrapper;
8013   if (model == TLSModel::LocalExec) {
8014     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8015   } else if (model == TLSModel::InitialExec) {
8016     if (is64Bit) {
8017       OperandFlags = X86II::MO_GOTTPOFF;
8018       WrapperKind = X86ISD::WrapperRIP;
8019     } else {
8020       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8021     }
8022   } else {
8023     llvm_unreachable("Unexpected model");
8024   }
8025
8026   // emit "addl x@ntpoff,%eax" (local exec)
8027   // or "addl x@indntpoff,%eax" (initial exec)
8028   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8029   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8030                                            GA->getValueType(0),
8031                                            GA->getOffset(), OperandFlags);
8032   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8033
8034   if (model == TLSModel::InitialExec) {
8035     if (isPIC && !is64Bit) {
8036       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8037                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8038                            Offset);
8039     }
8040
8041     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8042                          MachinePointerInfo::getGOT(), false, false, false,
8043                          0);
8044   }
8045
8046   // The address of the thread local variable is the add of the thread
8047   // pointer with the offset of the variable.
8048   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8049 }
8050
8051 SDValue
8052 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8053
8054   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8055   const GlobalValue *GV = GA->getGlobal();
8056
8057   if (Subtarget->isTargetELF()) {
8058     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8059
8060     switch (model) {
8061       case TLSModel::GeneralDynamic:
8062         if (Subtarget->is64Bit())
8063           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8064         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8065       case TLSModel::LocalDynamic:
8066         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8067                                            Subtarget->is64Bit());
8068       case TLSModel::InitialExec:
8069       case TLSModel::LocalExec:
8070         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8071                                    Subtarget->is64Bit(),
8072                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8073     }
8074     llvm_unreachable("Unknown TLS model.");
8075   }
8076
8077   if (Subtarget->isTargetDarwin()) {
8078     // Darwin only has one model of TLS.  Lower to that.
8079     unsigned char OpFlag = 0;
8080     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8081                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8082
8083     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8084     // global base reg.
8085     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8086                   !Subtarget->is64Bit();
8087     if (PIC32)
8088       OpFlag = X86II::MO_TLVP_PIC_BASE;
8089     else
8090       OpFlag = X86II::MO_TLVP;
8091     SDLoc DL(Op);
8092     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8093                                                 GA->getValueType(0),
8094                                                 GA->getOffset(), OpFlag);
8095     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8096
8097     // With PIC32, the address is actually $g + Offset.
8098     if (PIC32)
8099       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8100                            DAG.getNode(X86ISD::GlobalBaseReg,
8101                                        SDLoc(), getPointerTy()),
8102                            Offset);
8103
8104     // Lowering the machine isd will make sure everything is in the right
8105     // location.
8106     SDValue Chain = DAG.getEntryNode();
8107     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8108     SDValue Args[] = { Chain, Offset };
8109     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8110
8111     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8112     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8113     MFI->setAdjustsStack(true);
8114
8115     // And our return value (tls address) is in the standard call return value
8116     // location.
8117     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8118     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8119                               Chain.getValue(1));
8120   }
8121
8122   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8123     // Just use the implicit TLS architecture
8124     // Need to generate someting similar to:
8125     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8126     //                                  ; from TEB
8127     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8128     //   mov     rcx, qword [rdx+rcx*8]
8129     //   mov     eax, .tls$:tlsvar
8130     //   [rax+rcx] contains the address
8131     // Windows 64bit: gs:0x58
8132     // Windows 32bit: fs:__tls_array
8133
8134     // If GV is an alias then use the aliasee for determining
8135     // thread-localness.
8136     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8137       GV = GA->resolveAliasedGlobal(false);
8138     SDLoc dl(GA);
8139     SDValue Chain = DAG.getEntryNode();
8140
8141     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8142     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8143     // use its literal value of 0x2C.
8144     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8145                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8146                                                              256)
8147                                         : Type::getInt32PtrTy(*DAG.getContext(),
8148                                                               257));
8149
8150     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8151       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8152         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8153
8154     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8155                                         MachinePointerInfo(Ptr),
8156                                         false, false, false, 0);
8157
8158     // Load the _tls_index variable
8159     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8160     if (Subtarget->is64Bit())
8161       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8162                            IDX, MachinePointerInfo(), MVT::i32,
8163                            false, false, 0);
8164     else
8165       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8166                         false, false, false, 0);
8167
8168     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8169                                     getPointerTy());
8170     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8171
8172     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8173     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8174                       false, false, false, 0);
8175
8176     // Get the offset of start of .tls section
8177     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8178                                              GA->getValueType(0),
8179                                              GA->getOffset(), X86II::MO_SECREL);
8180     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8181
8182     // The address of the thread local variable is the add of the thread
8183     // pointer with the offset of the variable.
8184     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8185   }
8186
8187   llvm_unreachable("TLS not implemented for this target.");
8188 }
8189
8190 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8191 /// and take a 2 x i32 value to shift plus a shift amount.
8192 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8193   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8194   EVT VT = Op.getValueType();
8195   unsigned VTBits = VT.getSizeInBits();
8196   SDLoc dl(Op);
8197   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8198   SDValue ShOpLo = Op.getOperand(0);
8199   SDValue ShOpHi = Op.getOperand(1);
8200   SDValue ShAmt  = Op.getOperand(2);
8201   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8202                                      DAG.getConstant(VTBits - 1, MVT::i8))
8203                        : DAG.getConstant(0, VT);
8204
8205   SDValue Tmp2, Tmp3;
8206   if (Op.getOpcode() == ISD::SHL_PARTS) {
8207     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8208     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8209   } else {
8210     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8211     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8212   }
8213
8214   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8215                                 DAG.getConstant(VTBits, MVT::i8));
8216   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8217                              AndNode, DAG.getConstant(0, MVT::i8));
8218
8219   SDValue Hi, Lo;
8220   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8221   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8222   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8223
8224   if (Op.getOpcode() == ISD::SHL_PARTS) {
8225     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8226     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8227   } else {
8228     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8229     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8230   }
8231
8232   SDValue Ops[2] = { Lo, Hi };
8233   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8234 }
8235
8236 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8237                                            SelectionDAG &DAG) const {
8238   EVT SrcVT = Op.getOperand(0).getValueType();
8239
8240   if (SrcVT.isVector())
8241     return SDValue();
8242
8243   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8244          "Unknown SINT_TO_FP to lower!");
8245
8246   // These are really Legal; return the operand so the caller accepts it as
8247   // Legal.
8248   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8249     return Op;
8250   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8251       Subtarget->is64Bit()) {
8252     return Op;
8253   }
8254
8255   SDLoc dl(Op);
8256   unsigned Size = SrcVT.getSizeInBits()/8;
8257   MachineFunction &MF = DAG.getMachineFunction();
8258   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8259   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8260   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8261                                StackSlot,
8262                                MachinePointerInfo::getFixedStack(SSFI),
8263                                false, false, 0);
8264   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8265 }
8266
8267 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8268                                      SDValue StackSlot,
8269                                      SelectionDAG &DAG) const {
8270   // Build the FILD
8271   SDLoc DL(Op);
8272   SDVTList Tys;
8273   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8274   if (useSSE)
8275     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8276   else
8277     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8278
8279   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8280
8281   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8282   MachineMemOperand *MMO;
8283   if (FI) {
8284     int SSFI = FI->getIndex();
8285     MMO =
8286       DAG.getMachineFunction()
8287       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8288                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8289   } else {
8290     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8291     StackSlot = StackSlot.getOperand(1);
8292   }
8293   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8294   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8295                                            X86ISD::FILD, DL,
8296                                            Tys, Ops, array_lengthof(Ops),
8297                                            SrcVT, MMO);
8298
8299   if (useSSE) {
8300     Chain = Result.getValue(1);
8301     SDValue InFlag = Result.getValue(2);
8302
8303     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8304     // shouldn't be necessary except that RFP cannot be live across
8305     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8306     MachineFunction &MF = DAG.getMachineFunction();
8307     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8308     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8309     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8310     Tys = DAG.getVTList(MVT::Other);
8311     SDValue Ops[] = {
8312       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8313     };
8314     MachineMemOperand *MMO =
8315       DAG.getMachineFunction()
8316       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8317                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8318
8319     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8320                                     Ops, array_lengthof(Ops),
8321                                     Op.getValueType(), MMO);
8322     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8323                          MachinePointerInfo::getFixedStack(SSFI),
8324                          false, false, false, 0);
8325   }
8326
8327   return Result;
8328 }
8329
8330 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8331 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8332                                                SelectionDAG &DAG) const {
8333   // This algorithm is not obvious. Here it is what we're trying to output:
8334   /*
8335      movq       %rax,  %xmm0
8336      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8337      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8338      #ifdef __SSE3__
8339        haddpd   %xmm0, %xmm0
8340      #else
8341        pshufd   $0x4e, %xmm0, %xmm1
8342        addpd    %xmm1, %xmm0
8343      #endif
8344   */
8345
8346   SDLoc dl(Op);
8347   LLVMContext *Context = DAG.getContext();
8348
8349   // Build some magic constants.
8350   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8351   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8352   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8353
8354   SmallVector<Constant*,2> CV1;
8355   CV1.push_back(
8356     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8357                                       APInt(64, 0x4330000000000000ULL))));
8358   CV1.push_back(
8359     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8360                                       APInt(64, 0x4530000000000000ULL))));
8361   Constant *C1 = ConstantVector::get(CV1);
8362   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8363
8364   // Load the 64-bit value into an XMM register.
8365   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8366                             Op.getOperand(0));
8367   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8368                               MachinePointerInfo::getConstantPool(),
8369                               false, false, false, 16);
8370   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8371                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8372                               CLod0);
8373
8374   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8375                               MachinePointerInfo::getConstantPool(),
8376                               false, false, false, 16);
8377   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8378   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8379   SDValue Result;
8380
8381   if (Subtarget->hasSSE3()) {
8382     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8383     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8384   } else {
8385     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8386     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8387                                            S2F, 0x4E, DAG);
8388     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8389                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8390                          Sub);
8391   }
8392
8393   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8394                      DAG.getIntPtrConstant(0));
8395 }
8396
8397 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8398 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8399                                                SelectionDAG &DAG) const {
8400   SDLoc dl(Op);
8401   // FP constant to bias correct the final result.
8402   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8403                                    MVT::f64);
8404
8405   // Load the 32-bit value into an XMM register.
8406   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8407                              Op.getOperand(0));
8408
8409   // Zero out the upper parts of the register.
8410   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8411
8412   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8413                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8414                      DAG.getIntPtrConstant(0));
8415
8416   // Or the load with the bias.
8417   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8418                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8419                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8420                                                    MVT::v2f64, Load)),
8421                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8422                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8423                                                    MVT::v2f64, Bias)));
8424   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8425                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8426                    DAG.getIntPtrConstant(0));
8427
8428   // Subtract the bias.
8429   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8430
8431   // Handle final rounding.
8432   EVT DestVT = Op.getValueType();
8433
8434   if (DestVT.bitsLT(MVT::f64))
8435     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8436                        DAG.getIntPtrConstant(0));
8437   if (DestVT.bitsGT(MVT::f64))
8438     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8439
8440   // Handle final rounding.
8441   return Sub;
8442 }
8443
8444 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8445                                                SelectionDAG &DAG) const {
8446   SDValue N0 = Op.getOperand(0);
8447   EVT SVT = N0.getValueType();
8448   SDLoc dl(Op);
8449
8450   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8451           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8452          "Custom UINT_TO_FP is not supported!");
8453
8454   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8455                              SVT.getVectorNumElements());
8456   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8457                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8458 }
8459
8460 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8461                                            SelectionDAG &DAG) const {
8462   SDValue N0 = Op.getOperand(0);
8463   SDLoc dl(Op);
8464
8465   if (Op.getValueType().isVector())
8466     return lowerUINT_TO_FP_vec(Op, DAG);
8467
8468   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8469   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8470   // the optimization here.
8471   if (DAG.SignBitIsZero(N0))
8472     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8473
8474   EVT SrcVT = N0.getValueType();
8475   EVT DstVT = Op.getValueType();
8476   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8477     return LowerUINT_TO_FP_i64(Op, DAG);
8478   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8479     return LowerUINT_TO_FP_i32(Op, DAG);
8480   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8481     return SDValue();
8482
8483   // Make a 64-bit buffer, and use it to build an FILD.
8484   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8485   if (SrcVT == MVT::i32) {
8486     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8487     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8488                                      getPointerTy(), StackSlot, WordOff);
8489     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8490                                   StackSlot, MachinePointerInfo(),
8491                                   false, false, 0);
8492     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8493                                   OffsetSlot, MachinePointerInfo(),
8494                                   false, false, 0);
8495     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8496     return Fild;
8497   }
8498
8499   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8500   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8501                                StackSlot, MachinePointerInfo(),
8502                                false, false, 0);
8503   // For i64 source, we need to add the appropriate power of 2 if the input
8504   // was negative.  This is the same as the optimization in
8505   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8506   // we must be careful to do the computation in x87 extended precision, not
8507   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8508   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8509   MachineMemOperand *MMO =
8510     DAG.getMachineFunction()
8511     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8512                           MachineMemOperand::MOLoad, 8, 8);
8513
8514   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8515   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8516   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8517                                          array_lengthof(Ops), MVT::i64, MMO);
8518
8519   APInt FF(32, 0x5F800000ULL);
8520
8521   // Check whether the sign bit is set.
8522   SDValue SignSet = DAG.getSetCC(dl,
8523                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8524                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8525                                  ISD::SETLT);
8526
8527   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8528   SDValue FudgePtr = DAG.getConstantPool(
8529                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8530                                          getPointerTy());
8531
8532   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8533   SDValue Zero = DAG.getIntPtrConstant(0);
8534   SDValue Four = DAG.getIntPtrConstant(4);
8535   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8536                                Zero, Four);
8537   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8538
8539   // Load the value out, extending it from f32 to f80.
8540   // FIXME: Avoid the extend by constructing the right constant pool?
8541   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8542                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8543                                  MVT::f32, false, false, 4);
8544   // Extend everything to 80 bits to force it to be done on x87.
8545   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8546   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8547 }
8548
8549 std::pair<SDValue,SDValue>
8550 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8551                                     bool IsSigned, bool IsReplace) const {
8552   SDLoc DL(Op);
8553
8554   EVT DstTy = Op.getValueType();
8555
8556   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8557     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8558     DstTy = MVT::i64;
8559   }
8560
8561   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8562          DstTy.getSimpleVT() >= MVT::i16 &&
8563          "Unknown FP_TO_INT to lower!");
8564
8565   // These are really Legal.
8566   if (DstTy == MVT::i32 &&
8567       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8568     return std::make_pair(SDValue(), SDValue());
8569   if (Subtarget->is64Bit() &&
8570       DstTy == MVT::i64 &&
8571       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8572     return std::make_pair(SDValue(), SDValue());
8573
8574   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8575   // stack slot, or into the FTOL runtime function.
8576   MachineFunction &MF = DAG.getMachineFunction();
8577   unsigned MemSize = DstTy.getSizeInBits()/8;
8578   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8579   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8580
8581   unsigned Opc;
8582   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8583     Opc = X86ISD::WIN_FTOL;
8584   else
8585     switch (DstTy.getSimpleVT().SimpleTy) {
8586     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8587     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8588     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8589     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8590     }
8591
8592   SDValue Chain = DAG.getEntryNode();
8593   SDValue Value = Op.getOperand(0);
8594   EVT TheVT = Op.getOperand(0).getValueType();
8595   // FIXME This causes a redundant load/store if the SSE-class value is already
8596   // in memory, such as if it is on the callstack.
8597   if (isScalarFPTypeInSSEReg(TheVT)) {
8598     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8599     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8600                          MachinePointerInfo::getFixedStack(SSFI),
8601                          false, false, 0);
8602     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8603     SDValue Ops[] = {
8604       Chain, StackSlot, DAG.getValueType(TheVT)
8605     };
8606
8607     MachineMemOperand *MMO =
8608       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8609                               MachineMemOperand::MOLoad, MemSize, MemSize);
8610     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8611                                     array_lengthof(Ops), DstTy, MMO);
8612     Chain = Value.getValue(1);
8613     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8614     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8615   }
8616
8617   MachineMemOperand *MMO =
8618     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8619                             MachineMemOperand::MOStore, MemSize, MemSize);
8620
8621   if (Opc != X86ISD::WIN_FTOL) {
8622     // Build the FP_TO_INT*_IN_MEM
8623     SDValue Ops[] = { Chain, Value, StackSlot };
8624     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8625                                            Ops, array_lengthof(Ops), DstTy,
8626                                            MMO);
8627     return std::make_pair(FIST, StackSlot);
8628   } else {
8629     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8630       DAG.getVTList(MVT::Other, MVT::Glue),
8631       Chain, Value);
8632     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8633       MVT::i32, ftol.getValue(1));
8634     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8635       MVT::i32, eax.getValue(2));
8636     SDValue Ops[] = { eax, edx };
8637     SDValue pair = IsReplace
8638       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8639       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8640     return std::make_pair(pair, SDValue());
8641   }
8642 }
8643
8644 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8645                               const X86Subtarget *Subtarget) {
8646   MVT VT = Op->getValueType(0).getSimpleVT();
8647   SDValue In = Op->getOperand(0);
8648   MVT InVT = In.getValueType().getSimpleVT();
8649   SDLoc dl(Op);
8650
8651   // Optimize vectors in AVX mode:
8652   //
8653   //   v8i16 -> v8i32
8654   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8655   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8656   //   Concat upper and lower parts.
8657   //
8658   //   v4i32 -> v4i64
8659   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8660   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8661   //   Concat upper and lower parts.
8662   //
8663
8664   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8665       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8666     return SDValue();
8667
8668   if (Subtarget->hasInt256())
8669     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8670
8671   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8672   SDValue Undef = DAG.getUNDEF(InVT);
8673   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8674   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8675   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8676
8677   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8678                              VT.getVectorNumElements()/2);
8679
8680   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8681   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8682
8683   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8684 }
8685
8686 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8687                                            SelectionDAG &DAG) const {
8688   if (Subtarget->hasFp256()) {
8689     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8690     if (Res.getNode())
8691       return Res;
8692   }
8693
8694   return SDValue();
8695 }
8696 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8697                                             SelectionDAG &DAG) const {
8698   SDLoc DL(Op);
8699   MVT VT = Op.getValueType().getSimpleVT();
8700   SDValue In = Op.getOperand(0);
8701   MVT SVT = In.getValueType().getSimpleVT();
8702
8703   if (Subtarget->hasFp256()) {
8704     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8705     if (Res.getNode())
8706       return Res;
8707   }
8708
8709   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8710       VT.getVectorNumElements() != SVT.getVectorNumElements())
8711     return SDValue();
8712
8713   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8714
8715   // AVX2 has better support of integer extending.
8716   if (Subtarget->hasInt256())
8717     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8718
8719   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8720   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8721   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8722                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8723                                                 DAG.getUNDEF(MVT::v8i16),
8724                                                 &Mask[0]));
8725
8726   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8727 }
8728
8729 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8730   SDLoc DL(Op);
8731   MVT VT = Op.getValueType().getSimpleVT();
8732   SDValue In = Op.getOperand(0);
8733   MVT SVT = In.getValueType().getSimpleVT();
8734
8735   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8736     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8737     if (Subtarget->hasInt256()) {
8738       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8739       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8740       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8741                                 ShufMask);
8742       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8743                          DAG.getIntPtrConstant(0));
8744     }
8745
8746     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8747     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8748                                DAG.getIntPtrConstant(0));
8749     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8750                                DAG.getIntPtrConstant(2));
8751
8752     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8753     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8754
8755     // The PSHUFD mask:
8756     static const int ShufMask1[] = {0, 2, 0, 0};
8757     SDValue Undef = DAG.getUNDEF(VT);
8758     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8759     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8760
8761     // The MOVLHPS mask:
8762     static const int ShufMask2[] = {0, 1, 4, 5};
8763     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8764   }
8765
8766   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8767     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8768     if (Subtarget->hasInt256()) {
8769       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8770
8771       SmallVector<SDValue,32> pshufbMask;
8772       for (unsigned i = 0; i < 2; ++i) {
8773         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8774         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8775         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8776         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8777         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8778         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8779         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8780         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8781         for (unsigned j = 0; j < 8; ++j)
8782           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8783       }
8784       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8785                                &pshufbMask[0], 32);
8786       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8787       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8788
8789       static const int ShufMask[] = {0,  2,  -1,  -1};
8790       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8791                                 &ShufMask[0]);
8792       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8793                        DAG.getIntPtrConstant(0));
8794       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8795     }
8796
8797     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8798                                DAG.getIntPtrConstant(0));
8799
8800     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8801                                DAG.getIntPtrConstant(4));
8802
8803     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8804     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8805
8806     // The PSHUFB mask:
8807     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8808                                    -1, -1, -1, -1, -1, -1, -1, -1};
8809
8810     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8811     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8812     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8813
8814     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8815     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8816
8817     // The MOVLHPS Mask:
8818     static const int ShufMask2[] = {0, 1, 4, 5};
8819     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8820     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8821   }
8822
8823   // Handle truncation of V256 to V128 using shuffles.
8824   if (!VT.is128BitVector() || !SVT.is256BitVector())
8825     return SDValue();
8826
8827   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8828          "Invalid op");
8829   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8830
8831   unsigned NumElems = VT.getVectorNumElements();
8832   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8833                              NumElems * 2);
8834
8835   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8836   // Prepare truncation shuffle mask
8837   for (unsigned i = 0; i != NumElems; ++i)
8838     MaskVec[i] = i * 2;
8839   SDValue V = DAG.getVectorShuffle(NVT, DL,
8840                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8841                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8842   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8843                      DAG.getIntPtrConstant(0));
8844 }
8845
8846 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8847                                            SelectionDAG &DAG) const {
8848   MVT VT = Op.getValueType().getSimpleVT();
8849   if (VT.isVector()) {
8850     if (VT == MVT::v8i16)
8851       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8852                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8853                                      MVT::v8i32, Op.getOperand(0)));
8854     return SDValue();
8855   }
8856
8857   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8858     /*IsSigned=*/ true, /*IsReplace=*/ false);
8859   SDValue FIST = Vals.first, StackSlot = Vals.second;
8860   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8861   if (FIST.getNode() == 0) return Op;
8862
8863   if (StackSlot.getNode())
8864     // Load the result.
8865     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8866                        FIST, StackSlot, MachinePointerInfo(),
8867                        false, false, false, 0);
8868
8869   // The node is the result.
8870   return FIST;
8871 }
8872
8873 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8874                                            SelectionDAG &DAG) const {
8875   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8876     /*IsSigned=*/ false, /*IsReplace=*/ false);
8877   SDValue FIST = Vals.first, StackSlot = Vals.second;
8878   assert(FIST.getNode() && "Unexpected failure");
8879
8880   if (StackSlot.getNode())
8881     // Load the result.
8882     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8883                        FIST, StackSlot, MachinePointerInfo(),
8884                        false, false, false, 0);
8885
8886   // The node is the result.
8887   return FIST;
8888 }
8889
8890 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8891   SDLoc DL(Op);
8892   MVT VT = Op.getValueType().getSimpleVT();
8893   SDValue In = Op.getOperand(0);
8894   MVT SVT = In.getValueType().getSimpleVT();
8895
8896   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8897
8898   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8899                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8900                                  In, DAG.getUNDEF(SVT)));
8901 }
8902
8903 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8904   LLVMContext *Context = DAG.getContext();
8905   SDLoc dl(Op);
8906   MVT VT = Op.getValueType().getSimpleVT();
8907   MVT EltVT = VT;
8908   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8909   if (VT.isVector()) {
8910     EltVT = VT.getVectorElementType();
8911     NumElts = VT.getVectorNumElements();
8912   }
8913   Constant *C;
8914   if (EltVT == MVT::f64)
8915     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8916                                           APInt(64, ~(1ULL << 63))));
8917   else
8918     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8919                                           APInt(32, ~(1U << 31))));
8920   C = ConstantVector::getSplat(NumElts, C);
8921   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8922   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8923   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8924                              MachinePointerInfo::getConstantPool(),
8925                              false, false, false, Alignment);
8926   if (VT.isVector()) {
8927     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8928     return DAG.getNode(ISD::BITCAST, dl, VT,
8929                        DAG.getNode(ISD::AND, dl, ANDVT,
8930                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8931                                                Op.getOperand(0)),
8932                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8933   }
8934   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8935 }
8936
8937 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8938   LLVMContext *Context = DAG.getContext();
8939   SDLoc dl(Op);
8940   MVT VT = Op.getValueType().getSimpleVT();
8941   MVT EltVT = VT;
8942   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8943   if (VT.isVector()) {
8944     EltVT = VT.getVectorElementType();
8945     NumElts = VT.getVectorNumElements();
8946   }
8947   Constant *C;
8948   if (EltVT == MVT::f64)
8949     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8950                                           APInt(64, 1ULL << 63)));
8951   else
8952     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8953                                           APInt(32, 1U << 31)));
8954   C = ConstantVector::getSplat(NumElts, C);
8955   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8956   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8957   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8958                              MachinePointerInfo::getConstantPool(),
8959                              false, false, false, Alignment);
8960   if (VT.isVector()) {
8961     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8962     return DAG.getNode(ISD::BITCAST, dl, VT,
8963                        DAG.getNode(ISD::XOR, dl, XORVT,
8964                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8965                                                Op.getOperand(0)),
8966                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8967   }
8968
8969   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8970 }
8971
8972 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8973   LLVMContext *Context = DAG.getContext();
8974   SDValue Op0 = Op.getOperand(0);
8975   SDValue Op1 = Op.getOperand(1);
8976   SDLoc dl(Op);
8977   MVT VT = Op.getValueType().getSimpleVT();
8978   MVT SrcVT = Op1.getValueType().getSimpleVT();
8979
8980   // If second operand is smaller, extend it first.
8981   if (SrcVT.bitsLT(VT)) {
8982     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8983     SrcVT = VT;
8984   }
8985   // And if it is bigger, shrink it first.
8986   if (SrcVT.bitsGT(VT)) {
8987     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8988     SrcVT = VT;
8989   }
8990
8991   // At this point the operands and the result should have the same
8992   // type, and that won't be f80 since that is not custom lowered.
8993
8994   // First get the sign bit of second operand.
8995   SmallVector<Constant*,4> CV;
8996   if (SrcVT == MVT::f64) {
8997     const fltSemantics &Sem = APFloat::IEEEdouble;
8998     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8999     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9000   } else {
9001     const fltSemantics &Sem = APFloat::IEEEsingle;
9002     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9003     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9004     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9005     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9006   }
9007   Constant *C = ConstantVector::get(CV);
9008   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9009   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9010                               MachinePointerInfo::getConstantPool(),
9011                               false, false, false, 16);
9012   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9013
9014   // Shift sign bit right or left if the two operands have different types.
9015   if (SrcVT.bitsGT(VT)) {
9016     // Op0 is MVT::f32, Op1 is MVT::f64.
9017     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9018     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9019                           DAG.getConstant(32, MVT::i32));
9020     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9021     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9022                           DAG.getIntPtrConstant(0));
9023   }
9024
9025   // Clear first operand sign bit.
9026   CV.clear();
9027   if (VT == MVT::f64) {
9028     const fltSemantics &Sem = APFloat::IEEEdouble;
9029     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9030                                                    APInt(64, ~(1ULL << 63)))));
9031     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9032   } else {
9033     const fltSemantics &Sem = APFloat::IEEEsingle;
9034     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9035                                                    APInt(32, ~(1U << 31)))));
9036     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9037     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9038     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9039   }
9040   C = ConstantVector::get(CV);
9041   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9042   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9043                               MachinePointerInfo::getConstantPool(),
9044                               false, false, false, 16);
9045   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9046
9047   // Or the value with the sign bit.
9048   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9049 }
9050
9051 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9052   SDValue N0 = Op.getOperand(0);
9053   SDLoc dl(Op);
9054   MVT VT = Op.getValueType().getSimpleVT();
9055
9056   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9057   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9058                                   DAG.getConstant(1, VT));
9059   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9060 }
9061
9062 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9063 //
9064 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9065                                                   SelectionDAG &DAG) const {
9066   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9067
9068   if (!Subtarget->hasSSE41())
9069     return SDValue();
9070
9071   if (!Op->hasOneUse())
9072     return SDValue();
9073
9074   SDNode *N = Op.getNode();
9075   SDLoc DL(N);
9076
9077   SmallVector<SDValue, 8> Opnds;
9078   DenseMap<SDValue, unsigned> VecInMap;
9079   EVT VT = MVT::Other;
9080
9081   // Recognize a special case where a vector is casted into wide integer to
9082   // test all 0s.
9083   Opnds.push_back(N->getOperand(0));
9084   Opnds.push_back(N->getOperand(1));
9085
9086   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9087     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9088     // BFS traverse all OR'd operands.
9089     if (I->getOpcode() == ISD::OR) {
9090       Opnds.push_back(I->getOperand(0));
9091       Opnds.push_back(I->getOperand(1));
9092       // Re-evaluate the number of nodes to be traversed.
9093       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9094       continue;
9095     }
9096
9097     // Quit if a non-EXTRACT_VECTOR_ELT
9098     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9099       return SDValue();
9100
9101     // Quit if without a constant index.
9102     SDValue Idx = I->getOperand(1);
9103     if (!isa<ConstantSDNode>(Idx))
9104       return SDValue();
9105
9106     SDValue ExtractedFromVec = I->getOperand(0);
9107     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9108     if (M == VecInMap.end()) {
9109       VT = ExtractedFromVec.getValueType();
9110       // Quit if not 128/256-bit vector.
9111       if (!VT.is128BitVector() && !VT.is256BitVector())
9112         return SDValue();
9113       // Quit if not the same type.
9114       if (VecInMap.begin() != VecInMap.end() &&
9115           VT != VecInMap.begin()->first.getValueType())
9116         return SDValue();
9117       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9118     }
9119     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9120   }
9121
9122   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9123          "Not extracted from 128-/256-bit vector.");
9124
9125   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9126   SmallVector<SDValue, 8> VecIns;
9127
9128   for (DenseMap<SDValue, unsigned>::const_iterator
9129         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9130     // Quit if not all elements are used.
9131     if (I->second != FullMask)
9132       return SDValue();
9133     VecIns.push_back(I->first);
9134   }
9135
9136   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9137
9138   // Cast all vectors into TestVT for PTEST.
9139   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9140     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9141
9142   // If more than one full vectors are evaluated, OR them first before PTEST.
9143   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9144     // Each iteration will OR 2 nodes and append the result until there is only
9145     // 1 node left, i.e. the final OR'd value of all vectors.
9146     SDValue LHS = VecIns[Slot];
9147     SDValue RHS = VecIns[Slot + 1];
9148     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9149   }
9150
9151   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9152                      VecIns.back(), VecIns.back());
9153 }
9154
9155 /// Emit nodes that will be selected as "test Op0,Op0", or something
9156 /// equivalent.
9157 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9158                                     SelectionDAG &DAG) const {
9159   SDLoc dl(Op);
9160
9161   // CF and OF aren't always set the way we want. Determine which
9162   // of these we need.
9163   bool NeedCF = false;
9164   bool NeedOF = false;
9165   switch (X86CC) {
9166   default: break;
9167   case X86::COND_A: case X86::COND_AE:
9168   case X86::COND_B: case X86::COND_BE:
9169     NeedCF = true;
9170     break;
9171   case X86::COND_G: case X86::COND_GE:
9172   case X86::COND_L: case X86::COND_LE:
9173   case X86::COND_O: case X86::COND_NO:
9174     NeedOF = true;
9175     break;
9176   }
9177
9178   // See if we can use the EFLAGS value from the operand instead of
9179   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9180   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9181   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9182     // Emit a CMP with 0, which is the TEST pattern.
9183     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9184                        DAG.getConstant(0, Op.getValueType()));
9185
9186   unsigned Opcode = 0;
9187   unsigned NumOperands = 0;
9188
9189   // Truncate operations may prevent the merge of the SETCC instruction
9190   // and the arithmetic intruction before it. Attempt to truncate the operands
9191   // of the arithmetic instruction and use a reduced bit-width instruction.
9192   bool NeedTruncation = false;
9193   SDValue ArithOp = Op;
9194   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9195     SDValue Arith = Op->getOperand(0);
9196     // Both the trunc and the arithmetic op need to have one user each.
9197     if (Arith->hasOneUse())
9198       switch (Arith.getOpcode()) {
9199         default: break;
9200         case ISD::ADD:
9201         case ISD::SUB:
9202         case ISD::AND:
9203         case ISD::OR:
9204         case ISD::XOR: {
9205           NeedTruncation = true;
9206           ArithOp = Arith;
9207         }
9208       }
9209   }
9210
9211   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9212   // which may be the result of a CAST.  We use the variable 'Op', which is the
9213   // non-casted variable when we check for possible users.
9214   switch (ArithOp.getOpcode()) {
9215   case ISD::ADD:
9216     // Due to an isel shortcoming, be conservative if this add is likely to be
9217     // selected as part of a load-modify-store instruction. When the root node
9218     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9219     // uses of other nodes in the match, such as the ADD in this case. This
9220     // leads to the ADD being left around and reselected, with the result being
9221     // two adds in the output.  Alas, even if none our users are stores, that
9222     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9223     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9224     // climbing the DAG back to the root, and it doesn't seem to be worth the
9225     // effort.
9226     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9227          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9228       if (UI->getOpcode() != ISD::CopyToReg &&
9229           UI->getOpcode() != ISD::SETCC &&
9230           UI->getOpcode() != ISD::STORE)
9231         goto default_case;
9232
9233     if (ConstantSDNode *C =
9234         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9235       // An add of one will be selected as an INC.
9236       if (C->getAPIntValue() == 1) {
9237         Opcode = X86ISD::INC;
9238         NumOperands = 1;
9239         break;
9240       }
9241
9242       // An add of negative one (subtract of one) will be selected as a DEC.
9243       if (C->getAPIntValue().isAllOnesValue()) {
9244         Opcode = X86ISD::DEC;
9245         NumOperands = 1;
9246         break;
9247       }
9248     }
9249
9250     // Otherwise use a regular EFLAGS-setting add.
9251     Opcode = X86ISD::ADD;
9252     NumOperands = 2;
9253     break;
9254   case ISD::AND: {
9255     // If the primary and result isn't used, don't bother using X86ISD::AND,
9256     // because a TEST instruction will be better.
9257     bool NonFlagUse = false;
9258     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9259            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9260       SDNode *User = *UI;
9261       unsigned UOpNo = UI.getOperandNo();
9262       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9263         // Look pass truncate.
9264         UOpNo = User->use_begin().getOperandNo();
9265         User = *User->use_begin();
9266       }
9267
9268       if (User->getOpcode() != ISD::BRCOND &&
9269           User->getOpcode() != ISD::SETCC &&
9270           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9271         NonFlagUse = true;
9272         break;
9273       }
9274     }
9275
9276     if (!NonFlagUse)
9277       break;
9278   }
9279     // FALL THROUGH
9280   case ISD::SUB:
9281   case ISD::OR:
9282   case ISD::XOR:
9283     // Due to the ISEL shortcoming noted above, be conservative if this op is
9284     // likely to be selected as part of a load-modify-store instruction.
9285     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9286            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9287       if (UI->getOpcode() == ISD::STORE)
9288         goto default_case;
9289
9290     // Otherwise use a regular EFLAGS-setting instruction.
9291     switch (ArithOp.getOpcode()) {
9292     default: llvm_unreachable("unexpected operator!");
9293     case ISD::SUB: Opcode = X86ISD::SUB; break;
9294     case ISD::XOR: Opcode = X86ISD::XOR; break;
9295     case ISD::AND: Opcode = X86ISD::AND; break;
9296     case ISD::OR: {
9297       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9298         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9299         if (EFLAGS.getNode())
9300           return EFLAGS;
9301       }
9302       Opcode = X86ISD::OR;
9303       break;
9304     }
9305     }
9306
9307     NumOperands = 2;
9308     break;
9309   case X86ISD::ADD:
9310   case X86ISD::SUB:
9311   case X86ISD::INC:
9312   case X86ISD::DEC:
9313   case X86ISD::OR:
9314   case X86ISD::XOR:
9315   case X86ISD::AND:
9316     return SDValue(Op.getNode(), 1);
9317   default:
9318   default_case:
9319     break;
9320   }
9321
9322   // If we found that truncation is beneficial, perform the truncation and
9323   // update 'Op'.
9324   if (NeedTruncation) {
9325     EVT VT = Op.getValueType();
9326     SDValue WideVal = Op->getOperand(0);
9327     EVT WideVT = WideVal.getValueType();
9328     unsigned ConvertedOp = 0;
9329     // Use a target machine opcode to prevent further DAGCombine
9330     // optimizations that may separate the arithmetic operations
9331     // from the setcc node.
9332     switch (WideVal.getOpcode()) {
9333       default: break;
9334       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9335       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9336       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9337       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9338       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9339     }
9340
9341     if (ConvertedOp) {
9342       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9343       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9344         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9345         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9346         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9347       }
9348     }
9349   }
9350
9351   if (Opcode == 0)
9352     // Emit a CMP with 0, which is the TEST pattern.
9353     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9354                        DAG.getConstant(0, Op.getValueType()));
9355
9356   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9357   SmallVector<SDValue, 4> Ops;
9358   for (unsigned i = 0; i != NumOperands; ++i)
9359     Ops.push_back(Op.getOperand(i));
9360
9361   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9362   DAG.ReplaceAllUsesWith(Op, New);
9363   return SDValue(New.getNode(), 1);
9364 }
9365
9366 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9367 /// equivalent.
9368 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9369                                    SelectionDAG &DAG) const {
9370   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9371     if (C->getAPIntValue() == 0)
9372       return EmitTest(Op0, X86CC, DAG);
9373
9374   SDLoc dl(Op0);
9375   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9376        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9377     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9378     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9379     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9380                               Op0, Op1);
9381     return SDValue(Sub.getNode(), 1);
9382   }
9383   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9384 }
9385
9386 /// Convert a comparison if required by the subtarget.
9387 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9388                                                  SelectionDAG &DAG) const {
9389   // If the subtarget does not support the FUCOMI instruction, floating-point
9390   // comparisons have to be converted.
9391   if (Subtarget->hasCMov() ||
9392       Cmp.getOpcode() != X86ISD::CMP ||
9393       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9394       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9395     return Cmp;
9396
9397   // The instruction selector will select an FUCOM instruction instead of
9398   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9399   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9400   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9401   SDLoc dl(Cmp);
9402   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9403   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9404   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9405                             DAG.getConstant(8, MVT::i8));
9406   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9407   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9408 }
9409
9410 static bool isAllOnes(SDValue V) {
9411   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9412   return C && C->isAllOnesValue();
9413 }
9414
9415 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9416 /// if it's possible.
9417 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9418                                      SDLoc dl, SelectionDAG &DAG) const {
9419   SDValue Op0 = And.getOperand(0);
9420   SDValue Op1 = And.getOperand(1);
9421   if (Op0.getOpcode() == ISD::TRUNCATE)
9422     Op0 = Op0.getOperand(0);
9423   if (Op1.getOpcode() == ISD::TRUNCATE)
9424     Op1 = Op1.getOperand(0);
9425
9426   SDValue LHS, RHS;
9427   if (Op1.getOpcode() == ISD::SHL)
9428     std::swap(Op0, Op1);
9429   if (Op0.getOpcode() == ISD::SHL) {
9430     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9431       if (And00C->getZExtValue() == 1) {
9432         // If we looked past a truncate, check that it's only truncating away
9433         // known zeros.
9434         unsigned BitWidth = Op0.getValueSizeInBits();
9435         unsigned AndBitWidth = And.getValueSizeInBits();
9436         if (BitWidth > AndBitWidth) {
9437           APInt Zeros, Ones;
9438           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9439           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9440             return SDValue();
9441         }
9442         LHS = Op1;
9443         RHS = Op0.getOperand(1);
9444       }
9445   } else if (Op1.getOpcode() == ISD::Constant) {
9446     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9447     uint64_t AndRHSVal = AndRHS->getZExtValue();
9448     SDValue AndLHS = Op0;
9449
9450     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9451       LHS = AndLHS.getOperand(0);
9452       RHS = AndLHS.getOperand(1);
9453     }
9454
9455     // Use BT if the immediate can't be encoded in a TEST instruction.
9456     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9457       LHS = AndLHS;
9458       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9459     }
9460   }
9461
9462   if (LHS.getNode()) {
9463     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9464     // instruction.  Since the shift amount is in-range-or-undefined, we know
9465     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9466     // the encoding for the i16 version is larger than the i32 version.
9467     // Also promote i16 to i32 for performance / code size reason.
9468     if (LHS.getValueType() == MVT::i8 ||
9469         LHS.getValueType() == MVT::i16)
9470       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9471
9472     // If the operand types disagree, extend the shift amount to match.  Since
9473     // BT ignores high bits (like shifts) we can use anyextend.
9474     if (LHS.getValueType() != RHS.getValueType())
9475       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9476
9477     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9478     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9479     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9480                        DAG.getConstant(Cond, MVT::i8), BT);
9481   }
9482
9483   return SDValue();
9484 }
9485
9486 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9487 // ones, and then concatenate the result back.
9488 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9489   MVT VT = Op.getValueType().getSimpleVT();
9490
9491   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9492          "Unsupported value type for operation");
9493
9494   unsigned NumElems = VT.getVectorNumElements();
9495   SDLoc dl(Op);
9496   SDValue CC = Op.getOperand(2);
9497
9498   // Extract the LHS vectors
9499   SDValue LHS = Op.getOperand(0);
9500   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9501   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9502
9503   // Extract the RHS vectors
9504   SDValue RHS = Op.getOperand(1);
9505   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9506   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9507
9508   // Issue the operation on the smaller types and concatenate the result back
9509   MVT EltVT = VT.getVectorElementType();
9510   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9511   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9512                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9513                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9514 }
9515
9516 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9517                            SelectionDAG &DAG) {
9518   SDValue Cond;
9519   SDValue Op0 = Op.getOperand(0);
9520   SDValue Op1 = Op.getOperand(1);
9521   SDValue CC = Op.getOperand(2);
9522   MVT VT = Op.getValueType().getSimpleVT();
9523   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9524   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9525   SDLoc dl(Op);
9526
9527   if (isFP) {
9528 #ifndef NDEBUG
9529     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9530     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9531 #endif
9532
9533     unsigned SSECC;
9534     bool Swap = false;
9535
9536     // SSE Condition code mapping:
9537     //  0 - EQ
9538     //  1 - LT
9539     //  2 - LE
9540     //  3 - UNORD
9541     //  4 - NEQ
9542     //  5 - NLT
9543     //  6 - NLE
9544     //  7 - ORD
9545     switch (SetCCOpcode) {
9546     default: llvm_unreachable("Unexpected SETCC condition");
9547     case ISD::SETOEQ:
9548     case ISD::SETEQ:  SSECC = 0; break;
9549     case ISD::SETOGT:
9550     case ISD::SETGT: Swap = true; // Fallthrough
9551     case ISD::SETLT:
9552     case ISD::SETOLT: SSECC = 1; break;
9553     case ISD::SETOGE:
9554     case ISD::SETGE: Swap = true; // Fallthrough
9555     case ISD::SETLE:
9556     case ISD::SETOLE: SSECC = 2; break;
9557     case ISD::SETUO:  SSECC = 3; break;
9558     case ISD::SETUNE:
9559     case ISD::SETNE:  SSECC = 4; break;
9560     case ISD::SETULE: Swap = true; // Fallthrough
9561     case ISD::SETUGE: SSECC = 5; break;
9562     case ISD::SETULT: Swap = true; // Fallthrough
9563     case ISD::SETUGT: SSECC = 6; break;
9564     case ISD::SETO:   SSECC = 7; break;
9565     case ISD::SETUEQ:
9566     case ISD::SETONE: SSECC = 8; break;
9567     }
9568     if (Swap)
9569       std::swap(Op0, Op1);
9570
9571     // In the two special cases we can't handle, emit two comparisons.
9572     if (SSECC == 8) {
9573       unsigned CC0, CC1;
9574       unsigned CombineOpc;
9575       if (SetCCOpcode == ISD::SETUEQ) {
9576         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9577       } else {
9578         assert(SetCCOpcode == ISD::SETONE);
9579         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9580       }
9581
9582       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9583                                  DAG.getConstant(CC0, MVT::i8));
9584       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9585                                  DAG.getConstant(CC1, MVT::i8));
9586       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9587     }
9588     // Handle all other FP comparisons here.
9589     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9590                        DAG.getConstant(SSECC, MVT::i8));
9591   }
9592
9593   // Break 256-bit integer vector compare into smaller ones.
9594   if (VT.is256BitVector() && !Subtarget->hasInt256())
9595     return Lower256IntVSETCC(Op, DAG);
9596
9597   // We are handling one of the integer comparisons here.  Since SSE only has
9598   // GT and EQ comparisons for integer, swapping operands and multiple
9599   // operations may be required for some comparisons.
9600   unsigned Opc;
9601   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9602   
9603   switch (SetCCOpcode) {
9604   default: llvm_unreachable("Unexpected SETCC condition");
9605   case ISD::SETNE:  Invert = true;
9606   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9607   case ISD::SETLT:  Swap = true;
9608   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9609   case ISD::SETGE:  Swap = true;
9610   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9611   case ISD::SETULT: Swap = true;
9612   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9613   case ISD::SETUGE: Swap = true;
9614   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9615   }
9616   
9617   // Special case: Use min/max operations for SETULE/SETUGE
9618   MVT VET = VT.getVectorElementType();
9619   bool hasMinMax =
9620        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9621     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9622   
9623   if (hasMinMax) {
9624     switch (SetCCOpcode) {
9625     default: break;
9626     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9627     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9628     }
9629     
9630     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9631   }
9632   
9633   if (Swap)
9634     std::swap(Op0, Op1);
9635
9636   // Check that the operation in question is available (most are plain SSE2,
9637   // but PCMPGTQ and PCMPEQQ have different requirements).
9638   if (VT == MVT::v2i64) {
9639     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9640       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9641
9642       // First cast everything to the right type.
9643       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9644       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9645
9646       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9647       // bits of the inputs before performing those operations. The lower
9648       // compare is always unsigned.
9649       SDValue SB;
9650       if (FlipSigns) {
9651         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9652       } else {
9653         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9654         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9655         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9656                          Sign, Zero, Sign, Zero);
9657       }
9658       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9659       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9660
9661       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9662       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9663       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9664
9665       // Create masks for only the low parts/high parts of the 64 bit integers.
9666       static const int MaskHi[] = { 1, 1, 3, 3 };
9667       static const int MaskLo[] = { 0, 0, 2, 2 };
9668       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9669       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9670       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9671
9672       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9673       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9674
9675       if (Invert)
9676         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9677
9678       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9679     }
9680
9681     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9682       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9683       // pcmpeqd + pshufd + pand.
9684       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9685
9686       // First cast everything to the right type.
9687       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9688       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9689
9690       // Do the compare.
9691       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9692
9693       // Make sure the lower and upper halves are both all-ones.
9694       static const int Mask[] = { 1, 0, 3, 2 };
9695       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9696       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9697
9698       if (Invert)
9699         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9700
9701       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9702     }
9703   }
9704
9705   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9706   // bits of the inputs before performing those operations.
9707   if (FlipSigns) {
9708     EVT EltVT = VT.getVectorElementType();
9709     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9710     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9711     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9712   }
9713
9714   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9715
9716   // If the logical-not of the result is required, perform that now.
9717   if (Invert)
9718     Result = DAG.getNOT(dl, Result, VT);
9719   
9720   if (MinMax)
9721     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9722
9723   return Result;
9724 }
9725
9726 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9727
9728   MVT VT = Op.getValueType().getSimpleVT();
9729
9730   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9731
9732   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9733   SDValue Op0 = Op.getOperand(0);
9734   SDValue Op1 = Op.getOperand(1);
9735   SDLoc dl(Op);
9736   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9737
9738   // Optimize to BT if possible.
9739   // Lower (X & (1 << N)) == 0 to BT(X, N).
9740   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9741   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9742   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9743       Op1.getOpcode() == ISD::Constant &&
9744       cast<ConstantSDNode>(Op1)->isNullValue() &&
9745       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9746     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9747     if (NewSetCC.getNode())
9748       return NewSetCC;
9749   }
9750
9751   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9752   // these.
9753   if (Op1.getOpcode() == ISD::Constant &&
9754       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9755        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9756       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9757
9758     // If the input is a setcc, then reuse the input setcc or use a new one with
9759     // the inverted condition.
9760     if (Op0.getOpcode() == X86ISD::SETCC) {
9761       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9762       bool Invert = (CC == ISD::SETNE) ^
9763         cast<ConstantSDNode>(Op1)->isNullValue();
9764       if (!Invert) return Op0;
9765
9766       CCode = X86::GetOppositeBranchCondition(CCode);
9767       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9768                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9769     }
9770   }
9771
9772   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9773   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9774   if (X86CC == X86::COND_INVALID)
9775     return SDValue();
9776
9777   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9778   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9779   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9780                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9781 }
9782
9783 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9784 static bool isX86LogicalCmp(SDValue Op) {
9785   unsigned Opc = Op.getNode()->getOpcode();
9786   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9787       Opc == X86ISD::SAHF)
9788     return true;
9789   if (Op.getResNo() == 1 &&
9790       (Opc == X86ISD::ADD ||
9791        Opc == X86ISD::SUB ||
9792        Opc == X86ISD::ADC ||
9793        Opc == X86ISD::SBB ||
9794        Opc == X86ISD::SMUL ||
9795        Opc == X86ISD::UMUL ||
9796        Opc == X86ISD::INC ||
9797        Opc == X86ISD::DEC ||
9798        Opc == X86ISD::OR ||
9799        Opc == X86ISD::XOR ||
9800        Opc == X86ISD::AND))
9801     return true;
9802
9803   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9804     return true;
9805
9806   return false;
9807 }
9808
9809 static bool isZero(SDValue V) {
9810   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9811   return C && C->isNullValue();
9812 }
9813
9814 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9815   if (V.getOpcode() != ISD::TRUNCATE)
9816     return false;
9817
9818   SDValue VOp0 = V.getOperand(0);
9819   unsigned InBits = VOp0.getValueSizeInBits();
9820   unsigned Bits = V.getValueSizeInBits();
9821   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9822 }
9823
9824 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9825   bool addTest = true;
9826   SDValue Cond  = Op.getOperand(0);
9827   SDValue Op1 = Op.getOperand(1);
9828   SDValue Op2 = Op.getOperand(2);
9829   SDLoc DL(Op);
9830   SDValue CC;
9831
9832   if (Cond.getOpcode() == ISD::SETCC) {
9833     SDValue NewCond = LowerSETCC(Cond, DAG);
9834     if (NewCond.getNode())
9835       Cond = NewCond;
9836   }
9837
9838   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9839   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9840   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9841   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9842   if (Cond.getOpcode() == X86ISD::SETCC &&
9843       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9844       isZero(Cond.getOperand(1).getOperand(1))) {
9845     SDValue Cmp = Cond.getOperand(1);
9846
9847     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9848
9849     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9850         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9851       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9852
9853       SDValue CmpOp0 = Cmp.getOperand(0);
9854       // Apply further optimizations for special cases
9855       // (select (x != 0), -1, 0) -> neg & sbb
9856       // (select (x == 0), 0, -1) -> neg & sbb
9857       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9858         if (YC->isNullValue() &&
9859             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9860           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9861           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9862                                     DAG.getConstant(0, CmpOp0.getValueType()),
9863                                     CmpOp0);
9864           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9865                                     DAG.getConstant(X86::COND_B, MVT::i8),
9866                                     SDValue(Neg.getNode(), 1));
9867           return Res;
9868         }
9869
9870       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9871                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9872       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9873
9874       SDValue Res =   // Res = 0 or -1.
9875         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9876                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9877
9878       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9879         Res = DAG.getNOT(DL, Res, Res.getValueType());
9880
9881       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9882       if (N2C == 0 || !N2C->isNullValue())
9883         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9884       return Res;
9885     }
9886   }
9887
9888   // Look past (and (setcc_carry (cmp ...)), 1).
9889   if (Cond.getOpcode() == ISD::AND &&
9890       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9891     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9892     if (C && C->getAPIntValue() == 1)
9893       Cond = Cond.getOperand(0);
9894   }
9895
9896   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9897   // setting operand in place of the X86ISD::SETCC.
9898   unsigned CondOpcode = Cond.getOpcode();
9899   if (CondOpcode == X86ISD::SETCC ||
9900       CondOpcode == X86ISD::SETCC_CARRY) {
9901     CC = Cond.getOperand(0);
9902
9903     SDValue Cmp = Cond.getOperand(1);
9904     unsigned Opc = Cmp.getOpcode();
9905     MVT VT = Op.getValueType().getSimpleVT();
9906
9907     bool IllegalFPCMov = false;
9908     if (VT.isFloatingPoint() && !VT.isVector() &&
9909         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9910       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9911
9912     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9913         Opc == X86ISD::BT) { // FIXME
9914       Cond = Cmp;
9915       addTest = false;
9916     }
9917   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9918              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9919              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9920               Cond.getOperand(0).getValueType() != MVT::i8)) {
9921     SDValue LHS = Cond.getOperand(0);
9922     SDValue RHS = Cond.getOperand(1);
9923     unsigned X86Opcode;
9924     unsigned X86Cond;
9925     SDVTList VTs;
9926     switch (CondOpcode) {
9927     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9928     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9929     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9930     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9931     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9932     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9933     default: llvm_unreachable("unexpected overflowing operator");
9934     }
9935     if (CondOpcode == ISD::UMULO)
9936       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9937                           MVT::i32);
9938     else
9939       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9940
9941     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9942
9943     if (CondOpcode == ISD::UMULO)
9944       Cond = X86Op.getValue(2);
9945     else
9946       Cond = X86Op.getValue(1);
9947
9948     CC = DAG.getConstant(X86Cond, MVT::i8);
9949     addTest = false;
9950   }
9951
9952   if (addTest) {
9953     // Look pass the truncate if the high bits are known zero.
9954     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9955         Cond = Cond.getOperand(0);
9956
9957     // We know the result of AND is compared against zero. Try to match
9958     // it to BT.
9959     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9960       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9961       if (NewSetCC.getNode()) {
9962         CC = NewSetCC.getOperand(0);
9963         Cond = NewSetCC.getOperand(1);
9964         addTest = false;
9965       }
9966     }
9967   }
9968
9969   if (addTest) {
9970     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9971     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9972   }
9973
9974   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9975   // a <  b ?  0 : -1 -> RES = setcc_carry
9976   // a >= b ? -1 :  0 -> RES = setcc_carry
9977   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9978   if (Cond.getOpcode() == X86ISD::SUB) {
9979     Cond = ConvertCmpIfNecessary(Cond, DAG);
9980     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9981
9982     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9983         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9984       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9985                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9986       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9987         return DAG.getNOT(DL, Res, Res.getValueType());
9988       return Res;
9989     }
9990   }
9991
9992   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9993   // widen the cmov and push the truncate through. This avoids introducing a new
9994   // branch during isel and doesn't add any extensions.
9995   if (Op.getValueType() == MVT::i8 &&
9996       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9997     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9998     if (T1.getValueType() == T2.getValueType() &&
9999         // Blacklist CopyFromReg to avoid partial register stalls.
10000         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10001       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10002       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10003       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10004     }
10005   }
10006
10007   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10008   // condition is true.
10009   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10010   SDValue Ops[] = { Op2, Op1, CC, Cond };
10011   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10012 }
10013
10014 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10015                                             SelectionDAG &DAG) const {
10016   MVT VT = Op->getValueType(0).getSimpleVT();
10017   SDValue In = Op->getOperand(0);
10018   MVT InVT = In.getValueType().getSimpleVT();
10019   SDLoc dl(Op);
10020
10021   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10022       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10023     return SDValue();
10024
10025   if (Subtarget->hasInt256())
10026     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10027
10028   // Optimize vectors in AVX mode
10029   // Sign extend  v8i16 to v8i32 and
10030   //              v4i32 to v4i64
10031   //
10032   // Divide input vector into two parts
10033   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10034   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10035   // concat the vectors to original VT
10036
10037   unsigned NumElems = InVT.getVectorNumElements();
10038   SDValue Undef = DAG.getUNDEF(InVT);
10039
10040   SmallVector<int,8> ShufMask1(NumElems, -1);
10041   for (unsigned i = 0; i != NumElems/2; ++i)
10042     ShufMask1[i] = i;
10043
10044   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10045
10046   SmallVector<int,8> ShufMask2(NumElems, -1);
10047   for (unsigned i = 0; i != NumElems/2; ++i)
10048     ShufMask2[i] = i + NumElems/2;
10049
10050   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10051
10052   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10053                                 VT.getVectorNumElements()/2);
10054
10055   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10056   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10057
10058   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10059 }
10060
10061 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10062 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10063 // from the AND / OR.
10064 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10065   Opc = Op.getOpcode();
10066   if (Opc != ISD::OR && Opc != ISD::AND)
10067     return false;
10068   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10069           Op.getOperand(0).hasOneUse() &&
10070           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10071           Op.getOperand(1).hasOneUse());
10072 }
10073
10074 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10075 // 1 and that the SETCC node has a single use.
10076 static bool isXor1OfSetCC(SDValue Op) {
10077   if (Op.getOpcode() != ISD::XOR)
10078     return false;
10079   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10080   if (N1C && N1C->getAPIntValue() == 1) {
10081     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10082       Op.getOperand(0).hasOneUse();
10083   }
10084   return false;
10085 }
10086
10087 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10088   bool addTest = true;
10089   SDValue Chain = Op.getOperand(0);
10090   SDValue Cond  = Op.getOperand(1);
10091   SDValue Dest  = Op.getOperand(2);
10092   SDLoc dl(Op);
10093   SDValue CC;
10094   bool Inverted = false;
10095
10096   if (Cond.getOpcode() == ISD::SETCC) {
10097     // Check for setcc([su]{add,sub,mul}o == 0).
10098     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10099         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10100         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10101         Cond.getOperand(0).getResNo() == 1 &&
10102         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10103          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10104          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10105          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10106          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10107          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10108       Inverted = true;
10109       Cond = Cond.getOperand(0);
10110     } else {
10111       SDValue NewCond = LowerSETCC(Cond, DAG);
10112       if (NewCond.getNode())
10113         Cond = NewCond;
10114     }
10115   }
10116 #if 0
10117   // FIXME: LowerXALUO doesn't handle these!!
10118   else if (Cond.getOpcode() == X86ISD::ADD  ||
10119            Cond.getOpcode() == X86ISD::SUB  ||
10120            Cond.getOpcode() == X86ISD::SMUL ||
10121            Cond.getOpcode() == X86ISD::UMUL)
10122     Cond = LowerXALUO(Cond, DAG);
10123 #endif
10124
10125   // Look pass (and (setcc_carry (cmp ...)), 1).
10126   if (Cond.getOpcode() == ISD::AND &&
10127       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10128     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10129     if (C && C->getAPIntValue() == 1)
10130       Cond = Cond.getOperand(0);
10131   }
10132
10133   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10134   // setting operand in place of the X86ISD::SETCC.
10135   unsigned CondOpcode = Cond.getOpcode();
10136   if (CondOpcode == X86ISD::SETCC ||
10137       CondOpcode == X86ISD::SETCC_CARRY) {
10138     CC = Cond.getOperand(0);
10139
10140     SDValue Cmp = Cond.getOperand(1);
10141     unsigned Opc = Cmp.getOpcode();
10142     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10143     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10144       Cond = Cmp;
10145       addTest = false;
10146     } else {
10147       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10148       default: break;
10149       case X86::COND_O:
10150       case X86::COND_B:
10151         // These can only come from an arithmetic instruction with overflow,
10152         // e.g. SADDO, UADDO.
10153         Cond = Cond.getNode()->getOperand(1);
10154         addTest = false;
10155         break;
10156       }
10157     }
10158   }
10159   CondOpcode = Cond.getOpcode();
10160   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10161       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10162       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10163        Cond.getOperand(0).getValueType() != MVT::i8)) {
10164     SDValue LHS = Cond.getOperand(0);
10165     SDValue RHS = Cond.getOperand(1);
10166     unsigned X86Opcode;
10167     unsigned X86Cond;
10168     SDVTList VTs;
10169     switch (CondOpcode) {
10170     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10171     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10172     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10173     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10174     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10175     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10176     default: llvm_unreachable("unexpected overflowing operator");
10177     }
10178     if (Inverted)
10179       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10180     if (CondOpcode == ISD::UMULO)
10181       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10182                           MVT::i32);
10183     else
10184       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10185
10186     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10187
10188     if (CondOpcode == ISD::UMULO)
10189       Cond = X86Op.getValue(2);
10190     else
10191       Cond = X86Op.getValue(1);
10192
10193     CC = DAG.getConstant(X86Cond, MVT::i8);
10194     addTest = false;
10195   } else {
10196     unsigned CondOpc;
10197     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10198       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10199       if (CondOpc == ISD::OR) {
10200         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10201         // two branches instead of an explicit OR instruction with a
10202         // separate test.
10203         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10204             isX86LogicalCmp(Cmp)) {
10205           CC = Cond.getOperand(0).getOperand(0);
10206           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10207                               Chain, Dest, CC, Cmp);
10208           CC = Cond.getOperand(1).getOperand(0);
10209           Cond = Cmp;
10210           addTest = false;
10211         }
10212       } else { // ISD::AND
10213         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10214         // two branches instead of an explicit AND instruction with a
10215         // separate test. However, we only do this if this block doesn't
10216         // have a fall-through edge, because this requires an explicit
10217         // jmp when the condition is false.
10218         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10219             isX86LogicalCmp(Cmp) &&
10220             Op.getNode()->hasOneUse()) {
10221           X86::CondCode CCode =
10222             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10223           CCode = X86::GetOppositeBranchCondition(CCode);
10224           CC = DAG.getConstant(CCode, MVT::i8);
10225           SDNode *User = *Op.getNode()->use_begin();
10226           // Look for an unconditional branch following this conditional branch.
10227           // We need this because we need to reverse the successors in order
10228           // to implement FCMP_OEQ.
10229           if (User->getOpcode() == ISD::BR) {
10230             SDValue FalseBB = User->getOperand(1);
10231             SDNode *NewBR =
10232               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10233             assert(NewBR == User);
10234             (void)NewBR;
10235             Dest = FalseBB;
10236
10237             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10238                                 Chain, Dest, CC, Cmp);
10239             X86::CondCode CCode =
10240               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10241             CCode = X86::GetOppositeBranchCondition(CCode);
10242             CC = DAG.getConstant(CCode, MVT::i8);
10243             Cond = Cmp;
10244             addTest = false;
10245           }
10246         }
10247       }
10248     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10249       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10250       // It should be transformed during dag combiner except when the condition
10251       // is set by a arithmetics with overflow node.
10252       X86::CondCode CCode =
10253         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10254       CCode = X86::GetOppositeBranchCondition(CCode);
10255       CC = DAG.getConstant(CCode, MVT::i8);
10256       Cond = Cond.getOperand(0).getOperand(1);
10257       addTest = false;
10258     } else if (Cond.getOpcode() == ISD::SETCC &&
10259                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10260       // For FCMP_OEQ, we can emit
10261       // two branches instead of an explicit AND instruction with a
10262       // separate test. However, we only do this if this block doesn't
10263       // have a fall-through edge, because this requires an explicit
10264       // jmp when the condition is false.
10265       if (Op.getNode()->hasOneUse()) {
10266         SDNode *User = *Op.getNode()->use_begin();
10267         // Look for an unconditional branch following this conditional branch.
10268         // We need this because we need to reverse the successors in order
10269         // to implement FCMP_OEQ.
10270         if (User->getOpcode() == ISD::BR) {
10271           SDValue FalseBB = User->getOperand(1);
10272           SDNode *NewBR =
10273             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10274           assert(NewBR == User);
10275           (void)NewBR;
10276           Dest = FalseBB;
10277
10278           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10279                                     Cond.getOperand(0), Cond.getOperand(1));
10280           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10281           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10282           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10283                               Chain, Dest, CC, Cmp);
10284           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10285           Cond = Cmp;
10286           addTest = false;
10287         }
10288       }
10289     } else if (Cond.getOpcode() == ISD::SETCC &&
10290                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10291       // For FCMP_UNE, we can emit
10292       // two branches instead of an explicit AND instruction with a
10293       // separate test. However, we only do this if this block doesn't
10294       // have a fall-through edge, because this requires an explicit
10295       // jmp when the condition is false.
10296       if (Op.getNode()->hasOneUse()) {
10297         SDNode *User = *Op.getNode()->use_begin();
10298         // Look for an unconditional branch following this conditional branch.
10299         // We need this because we need to reverse the successors in order
10300         // to implement FCMP_UNE.
10301         if (User->getOpcode() == ISD::BR) {
10302           SDValue FalseBB = User->getOperand(1);
10303           SDNode *NewBR =
10304             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10305           assert(NewBR == User);
10306           (void)NewBR;
10307
10308           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10309                                     Cond.getOperand(0), Cond.getOperand(1));
10310           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10311           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10312           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10313                               Chain, Dest, CC, Cmp);
10314           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10315           Cond = Cmp;
10316           addTest = false;
10317           Dest = FalseBB;
10318         }
10319       }
10320     }
10321   }
10322
10323   if (addTest) {
10324     // Look pass the truncate if the high bits are known zero.
10325     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10326         Cond = Cond.getOperand(0);
10327
10328     // We know the result of AND is compared against zero. Try to match
10329     // it to BT.
10330     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10331       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10332       if (NewSetCC.getNode()) {
10333         CC = NewSetCC.getOperand(0);
10334         Cond = NewSetCC.getOperand(1);
10335         addTest = false;
10336       }
10337     }
10338   }
10339
10340   if (addTest) {
10341     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10342     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10343   }
10344   Cond = ConvertCmpIfNecessary(Cond, DAG);
10345   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10346                      Chain, Dest, CC, Cond);
10347 }
10348
10349 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10350 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10351 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10352 // that the guard pages used by the OS virtual memory manager are allocated in
10353 // correct sequence.
10354 SDValue
10355 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10356                                            SelectionDAG &DAG) const {
10357   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10358           getTargetMachine().Options.EnableSegmentedStacks) &&
10359          "This should be used only on Windows targets or when segmented stacks "
10360          "are being used");
10361   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10362   SDLoc dl(Op);
10363
10364   // Get the inputs.
10365   SDValue Chain = Op.getOperand(0);
10366   SDValue Size  = Op.getOperand(1);
10367   // FIXME: Ensure alignment here
10368
10369   bool Is64Bit = Subtarget->is64Bit();
10370   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10371
10372   if (getTargetMachine().Options.EnableSegmentedStacks) {
10373     MachineFunction &MF = DAG.getMachineFunction();
10374     MachineRegisterInfo &MRI = MF.getRegInfo();
10375
10376     if (Is64Bit) {
10377       // The 64 bit implementation of segmented stacks needs to clobber both r10
10378       // r11. This makes it impossible to use it along with nested parameters.
10379       const Function *F = MF.getFunction();
10380
10381       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10382            I != E; ++I)
10383         if (I->hasNestAttr())
10384           report_fatal_error("Cannot use segmented stacks with functions that "
10385                              "have nested arguments.");
10386     }
10387
10388     const TargetRegisterClass *AddrRegClass =
10389       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10390     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10391     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10392     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10393                                 DAG.getRegister(Vreg, SPTy));
10394     SDValue Ops1[2] = { Value, Chain };
10395     return DAG.getMergeValues(Ops1, 2, dl);
10396   } else {
10397     SDValue Flag;
10398     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10399
10400     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10401     Flag = Chain.getValue(1);
10402     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10403
10404     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10405     Flag = Chain.getValue(1);
10406
10407     const X86RegisterInfo *RegInfo =
10408       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10409     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10410                                SPTy).getValue(1);
10411
10412     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10413     return DAG.getMergeValues(Ops1, 2, dl);
10414   }
10415 }
10416
10417 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10418   MachineFunction &MF = DAG.getMachineFunction();
10419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10420
10421   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10422   SDLoc DL(Op);
10423
10424   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10425     // vastart just stores the address of the VarArgsFrameIndex slot into the
10426     // memory location argument.
10427     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10428                                    getPointerTy());
10429     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10430                         MachinePointerInfo(SV), false, false, 0);
10431   }
10432
10433   // __va_list_tag:
10434   //   gp_offset         (0 - 6 * 8)
10435   //   fp_offset         (48 - 48 + 8 * 16)
10436   //   overflow_arg_area (point to parameters coming in memory).
10437   //   reg_save_area
10438   SmallVector<SDValue, 8> MemOps;
10439   SDValue FIN = Op.getOperand(1);
10440   // Store gp_offset
10441   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10442                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10443                                                MVT::i32),
10444                                FIN, MachinePointerInfo(SV), false, false, 0);
10445   MemOps.push_back(Store);
10446
10447   // Store fp_offset
10448   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10449                     FIN, DAG.getIntPtrConstant(4));
10450   Store = DAG.getStore(Op.getOperand(0), DL,
10451                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10452                                        MVT::i32),
10453                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10454   MemOps.push_back(Store);
10455
10456   // Store ptr to overflow_arg_area
10457   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10458                     FIN, DAG.getIntPtrConstant(4));
10459   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10460                                     getPointerTy());
10461   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10462                        MachinePointerInfo(SV, 8),
10463                        false, false, 0);
10464   MemOps.push_back(Store);
10465
10466   // Store ptr to reg_save_area.
10467   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10468                     FIN, DAG.getIntPtrConstant(8));
10469   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10470                                     getPointerTy());
10471   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10472                        MachinePointerInfo(SV, 16), false, false, 0);
10473   MemOps.push_back(Store);
10474   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10475                      &MemOps[0], MemOps.size());
10476 }
10477
10478 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10479   assert(Subtarget->is64Bit() &&
10480          "LowerVAARG only handles 64-bit va_arg!");
10481   assert((Subtarget->isTargetLinux() ||
10482           Subtarget->isTargetDarwin()) &&
10483           "Unhandled target in LowerVAARG");
10484   assert(Op.getNode()->getNumOperands() == 4);
10485   SDValue Chain = Op.getOperand(0);
10486   SDValue SrcPtr = Op.getOperand(1);
10487   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10488   unsigned Align = Op.getConstantOperandVal(3);
10489   SDLoc dl(Op);
10490
10491   EVT ArgVT = Op.getNode()->getValueType(0);
10492   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10493   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10494   uint8_t ArgMode;
10495
10496   // Decide which area this value should be read from.
10497   // TODO: Implement the AMD64 ABI in its entirety. This simple
10498   // selection mechanism works only for the basic types.
10499   if (ArgVT == MVT::f80) {
10500     llvm_unreachable("va_arg for f80 not yet implemented");
10501   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10502     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10503   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10504     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10505   } else {
10506     llvm_unreachable("Unhandled argument type in LowerVAARG");
10507   }
10508
10509   if (ArgMode == 2) {
10510     // Sanity Check: Make sure using fp_offset makes sense.
10511     assert(!getTargetMachine().Options.UseSoftFloat &&
10512            !(DAG.getMachineFunction()
10513                 .getFunction()->getAttributes()
10514                 .hasAttribute(AttributeSet::FunctionIndex,
10515                               Attribute::NoImplicitFloat)) &&
10516            Subtarget->hasSSE1());
10517   }
10518
10519   // Insert VAARG_64 node into the DAG
10520   // VAARG_64 returns two values: Variable Argument Address, Chain
10521   SmallVector<SDValue, 11> InstOps;
10522   InstOps.push_back(Chain);
10523   InstOps.push_back(SrcPtr);
10524   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10525   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10526   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10527   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10528   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10529                                           VTs, &InstOps[0], InstOps.size(),
10530                                           MVT::i64,
10531                                           MachinePointerInfo(SV),
10532                                           /*Align=*/0,
10533                                           /*Volatile=*/false,
10534                                           /*ReadMem=*/true,
10535                                           /*WriteMem=*/true);
10536   Chain = VAARG.getValue(1);
10537
10538   // Load the next argument and return it
10539   return DAG.getLoad(ArgVT, dl,
10540                      Chain,
10541                      VAARG,
10542                      MachinePointerInfo(),
10543                      false, false, false, 0);
10544 }
10545
10546 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10547                            SelectionDAG &DAG) {
10548   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10549   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10550   SDValue Chain = Op.getOperand(0);
10551   SDValue DstPtr = Op.getOperand(1);
10552   SDValue SrcPtr = Op.getOperand(2);
10553   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10554   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10555   SDLoc DL(Op);
10556
10557   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10558                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10559                        false,
10560                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10561 }
10562
10563 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10564 // may or may not be a constant. Takes immediate version of shift as input.
10565 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10566                                    SDValue SrcOp, SDValue ShAmt,
10567                                    SelectionDAG &DAG) {
10568   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10569
10570   if (isa<ConstantSDNode>(ShAmt)) {
10571     // Constant may be a TargetConstant. Use a regular constant.
10572     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10573     switch (Opc) {
10574       default: llvm_unreachable("Unknown target vector shift node");
10575       case X86ISD::VSHLI:
10576       case X86ISD::VSRLI:
10577       case X86ISD::VSRAI:
10578         return DAG.getNode(Opc, dl, VT, SrcOp,
10579                            DAG.getConstant(ShiftAmt, MVT::i32));
10580     }
10581   }
10582
10583   // Change opcode to non-immediate version
10584   switch (Opc) {
10585     default: llvm_unreachable("Unknown target vector shift node");
10586     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10587     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10588     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10589   }
10590
10591   // Need to build a vector containing shift amount
10592   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10593   SDValue ShOps[4];
10594   ShOps[0] = ShAmt;
10595   ShOps[1] = DAG.getConstant(0, MVT::i32);
10596   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10597   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10598
10599   // The return type has to be a 128-bit type with the same element
10600   // type as the input type.
10601   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10602   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10603
10604   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10605   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10606 }
10607
10608 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10609   SDLoc dl(Op);
10610   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10611   switch (IntNo) {
10612   default: return SDValue();    // Don't custom lower most intrinsics.
10613   // Comparison intrinsics.
10614   case Intrinsic::x86_sse_comieq_ss:
10615   case Intrinsic::x86_sse_comilt_ss:
10616   case Intrinsic::x86_sse_comile_ss:
10617   case Intrinsic::x86_sse_comigt_ss:
10618   case Intrinsic::x86_sse_comige_ss:
10619   case Intrinsic::x86_sse_comineq_ss:
10620   case Intrinsic::x86_sse_ucomieq_ss:
10621   case Intrinsic::x86_sse_ucomilt_ss:
10622   case Intrinsic::x86_sse_ucomile_ss:
10623   case Intrinsic::x86_sse_ucomigt_ss:
10624   case Intrinsic::x86_sse_ucomige_ss:
10625   case Intrinsic::x86_sse_ucomineq_ss:
10626   case Intrinsic::x86_sse2_comieq_sd:
10627   case Intrinsic::x86_sse2_comilt_sd:
10628   case Intrinsic::x86_sse2_comile_sd:
10629   case Intrinsic::x86_sse2_comigt_sd:
10630   case Intrinsic::x86_sse2_comige_sd:
10631   case Intrinsic::x86_sse2_comineq_sd:
10632   case Intrinsic::x86_sse2_ucomieq_sd:
10633   case Intrinsic::x86_sse2_ucomilt_sd:
10634   case Intrinsic::x86_sse2_ucomile_sd:
10635   case Intrinsic::x86_sse2_ucomigt_sd:
10636   case Intrinsic::x86_sse2_ucomige_sd:
10637   case Intrinsic::x86_sse2_ucomineq_sd: {
10638     unsigned Opc;
10639     ISD::CondCode CC;
10640     switch (IntNo) {
10641     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10642     case Intrinsic::x86_sse_comieq_ss:
10643     case Intrinsic::x86_sse2_comieq_sd:
10644       Opc = X86ISD::COMI;
10645       CC = ISD::SETEQ;
10646       break;
10647     case Intrinsic::x86_sse_comilt_ss:
10648     case Intrinsic::x86_sse2_comilt_sd:
10649       Opc = X86ISD::COMI;
10650       CC = ISD::SETLT;
10651       break;
10652     case Intrinsic::x86_sse_comile_ss:
10653     case Intrinsic::x86_sse2_comile_sd:
10654       Opc = X86ISD::COMI;
10655       CC = ISD::SETLE;
10656       break;
10657     case Intrinsic::x86_sse_comigt_ss:
10658     case Intrinsic::x86_sse2_comigt_sd:
10659       Opc = X86ISD::COMI;
10660       CC = ISD::SETGT;
10661       break;
10662     case Intrinsic::x86_sse_comige_ss:
10663     case Intrinsic::x86_sse2_comige_sd:
10664       Opc = X86ISD::COMI;
10665       CC = ISD::SETGE;
10666       break;
10667     case Intrinsic::x86_sse_comineq_ss:
10668     case Intrinsic::x86_sse2_comineq_sd:
10669       Opc = X86ISD::COMI;
10670       CC = ISD::SETNE;
10671       break;
10672     case Intrinsic::x86_sse_ucomieq_ss:
10673     case Intrinsic::x86_sse2_ucomieq_sd:
10674       Opc = X86ISD::UCOMI;
10675       CC = ISD::SETEQ;
10676       break;
10677     case Intrinsic::x86_sse_ucomilt_ss:
10678     case Intrinsic::x86_sse2_ucomilt_sd:
10679       Opc = X86ISD::UCOMI;
10680       CC = ISD::SETLT;
10681       break;
10682     case Intrinsic::x86_sse_ucomile_ss:
10683     case Intrinsic::x86_sse2_ucomile_sd:
10684       Opc = X86ISD::UCOMI;
10685       CC = ISD::SETLE;
10686       break;
10687     case Intrinsic::x86_sse_ucomigt_ss:
10688     case Intrinsic::x86_sse2_ucomigt_sd:
10689       Opc = X86ISD::UCOMI;
10690       CC = ISD::SETGT;
10691       break;
10692     case Intrinsic::x86_sse_ucomige_ss:
10693     case Intrinsic::x86_sse2_ucomige_sd:
10694       Opc = X86ISD::UCOMI;
10695       CC = ISD::SETGE;
10696       break;
10697     case Intrinsic::x86_sse_ucomineq_ss:
10698     case Intrinsic::x86_sse2_ucomineq_sd:
10699       Opc = X86ISD::UCOMI;
10700       CC = ISD::SETNE;
10701       break;
10702     }
10703
10704     SDValue LHS = Op.getOperand(1);
10705     SDValue RHS = Op.getOperand(2);
10706     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10707     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10708     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10709     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10710                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10711     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10712   }
10713
10714   // Arithmetic intrinsics.
10715   case Intrinsic::x86_sse2_pmulu_dq:
10716   case Intrinsic::x86_avx2_pmulu_dq:
10717     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10718                        Op.getOperand(1), Op.getOperand(2));
10719
10720   // SSE2/AVX2 sub with unsigned saturation intrinsics
10721   case Intrinsic::x86_sse2_psubus_b:
10722   case Intrinsic::x86_sse2_psubus_w:
10723   case Intrinsic::x86_avx2_psubus_b:
10724   case Intrinsic::x86_avx2_psubus_w:
10725     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10726                        Op.getOperand(1), Op.getOperand(2));
10727
10728   // SSE3/AVX horizontal add/sub intrinsics
10729   case Intrinsic::x86_sse3_hadd_ps:
10730   case Intrinsic::x86_sse3_hadd_pd:
10731   case Intrinsic::x86_avx_hadd_ps_256:
10732   case Intrinsic::x86_avx_hadd_pd_256:
10733   case Intrinsic::x86_sse3_hsub_ps:
10734   case Intrinsic::x86_sse3_hsub_pd:
10735   case Intrinsic::x86_avx_hsub_ps_256:
10736   case Intrinsic::x86_avx_hsub_pd_256:
10737   case Intrinsic::x86_ssse3_phadd_w_128:
10738   case Intrinsic::x86_ssse3_phadd_d_128:
10739   case Intrinsic::x86_avx2_phadd_w:
10740   case Intrinsic::x86_avx2_phadd_d:
10741   case Intrinsic::x86_ssse3_phsub_w_128:
10742   case Intrinsic::x86_ssse3_phsub_d_128:
10743   case Intrinsic::x86_avx2_phsub_w:
10744   case Intrinsic::x86_avx2_phsub_d: {
10745     unsigned Opcode;
10746     switch (IntNo) {
10747     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10748     case Intrinsic::x86_sse3_hadd_ps:
10749     case Intrinsic::x86_sse3_hadd_pd:
10750     case Intrinsic::x86_avx_hadd_ps_256:
10751     case Intrinsic::x86_avx_hadd_pd_256:
10752       Opcode = X86ISD::FHADD;
10753       break;
10754     case Intrinsic::x86_sse3_hsub_ps:
10755     case Intrinsic::x86_sse3_hsub_pd:
10756     case Intrinsic::x86_avx_hsub_ps_256:
10757     case Intrinsic::x86_avx_hsub_pd_256:
10758       Opcode = X86ISD::FHSUB;
10759       break;
10760     case Intrinsic::x86_ssse3_phadd_w_128:
10761     case Intrinsic::x86_ssse3_phadd_d_128:
10762     case Intrinsic::x86_avx2_phadd_w:
10763     case Intrinsic::x86_avx2_phadd_d:
10764       Opcode = X86ISD::HADD;
10765       break;
10766     case Intrinsic::x86_ssse3_phsub_w_128:
10767     case Intrinsic::x86_ssse3_phsub_d_128:
10768     case Intrinsic::x86_avx2_phsub_w:
10769     case Intrinsic::x86_avx2_phsub_d:
10770       Opcode = X86ISD::HSUB;
10771       break;
10772     }
10773     return DAG.getNode(Opcode, dl, Op.getValueType(),
10774                        Op.getOperand(1), Op.getOperand(2));
10775   }
10776
10777   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10778   case Intrinsic::x86_sse2_pmaxu_b:
10779   case Intrinsic::x86_sse41_pmaxuw:
10780   case Intrinsic::x86_sse41_pmaxud:
10781   case Intrinsic::x86_avx2_pmaxu_b:
10782   case Intrinsic::x86_avx2_pmaxu_w:
10783   case Intrinsic::x86_avx2_pmaxu_d:
10784   case Intrinsic::x86_sse2_pminu_b:
10785   case Intrinsic::x86_sse41_pminuw:
10786   case Intrinsic::x86_sse41_pminud:
10787   case Intrinsic::x86_avx2_pminu_b:
10788   case Intrinsic::x86_avx2_pminu_w:
10789   case Intrinsic::x86_avx2_pminu_d:
10790   case Intrinsic::x86_sse41_pmaxsb:
10791   case Intrinsic::x86_sse2_pmaxs_w:
10792   case Intrinsic::x86_sse41_pmaxsd:
10793   case Intrinsic::x86_avx2_pmaxs_b:
10794   case Intrinsic::x86_avx2_pmaxs_w:
10795   case Intrinsic::x86_avx2_pmaxs_d:
10796   case Intrinsic::x86_sse41_pminsb:
10797   case Intrinsic::x86_sse2_pmins_w:
10798   case Intrinsic::x86_sse41_pminsd:
10799   case Intrinsic::x86_avx2_pmins_b:
10800   case Intrinsic::x86_avx2_pmins_w:
10801   case Intrinsic::x86_avx2_pmins_d: {
10802     unsigned Opcode;
10803     switch (IntNo) {
10804     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10805     case Intrinsic::x86_sse2_pmaxu_b:
10806     case Intrinsic::x86_sse41_pmaxuw:
10807     case Intrinsic::x86_sse41_pmaxud:
10808     case Intrinsic::x86_avx2_pmaxu_b:
10809     case Intrinsic::x86_avx2_pmaxu_w:
10810     case Intrinsic::x86_avx2_pmaxu_d:
10811       Opcode = X86ISD::UMAX;
10812       break;
10813     case Intrinsic::x86_sse2_pminu_b:
10814     case Intrinsic::x86_sse41_pminuw:
10815     case Intrinsic::x86_sse41_pminud:
10816     case Intrinsic::x86_avx2_pminu_b:
10817     case Intrinsic::x86_avx2_pminu_w:
10818     case Intrinsic::x86_avx2_pminu_d:
10819       Opcode = X86ISD::UMIN;
10820       break;
10821     case Intrinsic::x86_sse41_pmaxsb:
10822     case Intrinsic::x86_sse2_pmaxs_w:
10823     case Intrinsic::x86_sse41_pmaxsd:
10824     case Intrinsic::x86_avx2_pmaxs_b:
10825     case Intrinsic::x86_avx2_pmaxs_w:
10826     case Intrinsic::x86_avx2_pmaxs_d:
10827       Opcode = X86ISD::SMAX;
10828       break;
10829     case Intrinsic::x86_sse41_pminsb:
10830     case Intrinsic::x86_sse2_pmins_w:
10831     case Intrinsic::x86_sse41_pminsd:
10832     case Intrinsic::x86_avx2_pmins_b:
10833     case Intrinsic::x86_avx2_pmins_w:
10834     case Intrinsic::x86_avx2_pmins_d:
10835       Opcode = X86ISD::SMIN;
10836       break;
10837     }
10838     return DAG.getNode(Opcode, dl, Op.getValueType(),
10839                        Op.getOperand(1), Op.getOperand(2));
10840   }
10841
10842   // SSE/SSE2/AVX floating point max/min intrinsics.
10843   case Intrinsic::x86_sse_max_ps:
10844   case Intrinsic::x86_sse2_max_pd:
10845   case Intrinsic::x86_avx_max_ps_256:
10846   case Intrinsic::x86_avx_max_pd_256:
10847   case Intrinsic::x86_sse_min_ps:
10848   case Intrinsic::x86_sse2_min_pd:
10849   case Intrinsic::x86_avx_min_ps_256:
10850   case Intrinsic::x86_avx_min_pd_256: {
10851     unsigned Opcode;
10852     switch (IntNo) {
10853     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10854     case Intrinsic::x86_sse_max_ps:
10855     case Intrinsic::x86_sse2_max_pd:
10856     case Intrinsic::x86_avx_max_ps_256:
10857     case Intrinsic::x86_avx_max_pd_256:
10858       Opcode = X86ISD::FMAX;
10859       break;
10860     case Intrinsic::x86_sse_min_ps:
10861     case Intrinsic::x86_sse2_min_pd:
10862     case Intrinsic::x86_avx_min_ps_256:
10863     case Intrinsic::x86_avx_min_pd_256:
10864       Opcode = X86ISD::FMIN;
10865       break;
10866     }
10867     return DAG.getNode(Opcode, dl, Op.getValueType(),
10868                        Op.getOperand(1), Op.getOperand(2));
10869   }
10870
10871   // AVX2 variable shift intrinsics
10872   case Intrinsic::x86_avx2_psllv_d:
10873   case Intrinsic::x86_avx2_psllv_q:
10874   case Intrinsic::x86_avx2_psllv_d_256:
10875   case Intrinsic::x86_avx2_psllv_q_256:
10876   case Intrinsic::x86_avx2_psrlv_d:
10877   case Intrinsic::x86_avx2_psrlv_q:
10878   case Intrinsic::x86_avx2_psrlv_d_256:
10879   case Intrinsic::x86_avx2_psrlv_q_256:
10880   case Intrinsic::x86_avx2_psrav_d:
10881   case Intrinsic::x86_avx2_psrav_d_256: {
10882     unsigned Opcode;
10883     switch (IntNo) {
10884     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10885     case Intrinsic::x86_avx2_psllv_d:
10886     case Intrinsic::x86_avx2_psllv_q:
10887     case Intrinsic::x86_avx2_psllv_d_256:
10888     case Intrinsic::x86_avx2_psllv_q_256:
10889       Opcode = ISD::SHL;
10890       break;
10891     case Intrinsic::x86_avx2_psrlv_d:
10892     case Intrinsic::x86_avx2_psrlv_q:
10893     case Intrinsic::x86_avx2_psrlv_d_256:
10894     case Intrinsic::x86_avx2_psrlv_q_256:
10895       Opcode = ISD::SRL;
10896       break;
10897     case Intrinsic::x86_avx2_psrav_d:
10898     case Intrinsic::x86_avx2_psrav_d_256:
10899       Opcode = ISD::SRA;
10900       break;
10901     }
10902     return DAG.getNode(Opcode, dl, Op.getValueType(),
10903                        Op.getOperand(1), Op.getOperand(2));
10904   }
10905
10906   case Intrinsic::x86_ssse3_pshuf_b_128:
10907   case Intrinsic::x86_avx2_pshuf_b:
10908     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10909                        Op.getOperand(1), Op.getOperand(2));
10910
10911   case Intrinsic::x86_ssse3_psign_b_128:
10912   case Intrinsic::x86_ssse3_psign_w_128:
10913   case Intrinsic::x86_ssse3_psign_d_128:
10914   case Intrinsic::x86_avx2_psign_b:
10915   case Intrinsic::x86_avx2_psign_w:
10916   case Intrinsic::x86_avx2_psign_d:
10917     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10918                        Op.getOperand(1), Op.getOperand(2));
10919
10920   case Intrinsic::x86_sse41_insertps:
10921     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10922                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10923
10924   case Intrinsic::x86_avx_vperm2f128_ps_256:
10925   case Intrinsic::x86_avx_vperm2f128_pd_256:
10926   case Intrinsic::x86_avx_vperm2f128_si_256:
10927   case Intrinsic::x86_avx2_vperm2i128:
10928     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10929                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10930
10931   case Intrinsic::x86_avx2_permd:
10932   case Intrinsic::x86_avx2_permps:
10933     // Operands intentionally swapped. Mask is last operand to intrinsic,
10934     // but second operand for node/intruction.
10935     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10936                        Op.getOperand(2), Op.getOperand(1));
10937
10938   case Intrinsic::x86_sse_sqrt_ps:
10939   case Intrinsic::x86_sse2_sqrt_pd:
10940   case Intrinsic::x86_avx_sqrt_ps_256:
10941   case Intrinsic::x86_avx_sqrt_pd_256:
10942     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10943
10944   // ptest and testp intrinsics. The intrinsic these come from are designed to
10945   // return an integer value, not just an instruction so lower it to the ptest
10946   // or testp pattern and a setcc for the result.
10947   case Intrinsic::x86_sse41_ptestz:
10948   case Intrinsic::x86_sse41_ptestc:
10949   case Intrinsic::x86_sse41_ptestnzc:
10950   case Intrinsic::x86_avx_ptestz_256:
10951   case Intrinsic::x86_avx_ptestc_256:
10952   case Intrinsic::x86_avx_ptestnzc_256:
10953   case Intrinsic::x86_avx_vtestz_ps:
10954   case Intrinsic::x86_avx_vtestc_ps:
10955   case Intrinsic::x86_avx_vtestnzc_ps:
10956   case Intrinsic::x86_avx_vtestz_pd:
10957   case Intrinsic::x86_avx_vtestc_pd:
10958   case Intrinsic::x86_avx_vtestnzc_pd:
10959   case Intrinsic::x86_avx_vtestz_ps_256:
10960   case Intrinsic::x86_avx_vtestc_ps_256:
10961   case Intrinsic::x86_avx_vtestnzc_ps_256:
10962   case Intrinsic::x86_avx_vtestz_pd_256:
10963   case Intrinsic::x86_avx_vtestc_pd_256:
10964   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10965     bool IsTestPacked = false;
10966     unsigned X86CC;
10967     switch (IntNo) {
10968     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10969     case Intrinsic::x86_avx_vtestz_ps:
10970     case Intrinsic::x86_avx_vtestz_pd:
10971     case Intrinsic::x86_avx_vtestz_ps_256:
10972     case Intrinsic::x86_avx_vtestz_pd_256:
10973       IsTestPacked = true; // Fallthrough
10974     case Intrinsic::x86_sse41_ptestz:
10975     case Intrinsic::x86_avx_ptestz_256:
10976       // ZF = 1
10977       X86CC = X86::COND_E;
10978       break;
10979     case Intrinsic::x86_avx_vtestc_ps:
10980     case Intrinsic::x86_avx_vtestc_pd:
10981     case Intrinsic::x86_avx_vtestc_ps_256:
10982     case Intrinsic::x86_avx_vtestc_pd_256:
10983       IsTestPacked = true; // Fallthrough
10984     case Intrinsic::x86_sse41_ptestc:
10985     case Intrinsic::x86_avx_ptestc_256:
10986       // CF = 1
10987       X86CC = X86::COND_B;
10988       break;
10989     case Intrinsic::x86_avx_vtestnzc_ps:
10990     case Intrinsic::x86_avx_vtestnzc_pd:
10991     case Intrinsic::x86_avx_vtestnzc_ps_256:
10992     case Intrinsic::x86_avx_vtestnzc_pd_256:
10993       IsTestPacked = true; // Fallthrough
10994     case Intrinsic::x86_sse41_ptestnzc:
10995     case Intrinsic::x86_avx_ptestnzc_256:
10996       // ZF and CF = 0
10997       X86CC = X86::COND_A;
10998       break;
10999     }
11000
11001     SDValue LHS = Op.getOperand(1);
11002     SDValue RHS = Op.getOperand(2);
11003     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11004     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11005     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11006     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11007     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11008   }
11009
11010   // SSE/AVX shift intrinsics
11011   case Intrinsic::x86_sse2_psll_w:
11012   case Intrinsic::x86_sse2_psll_d:
11013   case Intrinsic::x86_sse2_psll_q:
11014   case Intrinsic::x86_avx2_psll_w:
11015   case Intrinsic::x86_avx2_psll_d:
11016   case Intrinsic::x86_avx2_psll_q:
11017   case Intrinsic::x86_sse2_psrl_w:
11018   case Intrinsic::x86_sse2_psrl_d:
11019   case Intrinsic::x86_sse2_psrl_q:
11020   case Intrinsic::x86_avx2_psrl_w:
11021   case Intrinsic::x86_avx2_psrl_d:
11022   case Intrinsic::x86_avx2_psrl_q:
11023   case Intrinsic::x86_sse2_psra_w:
11024   case Intrinsic::x86_sse2_psra_d:
11025   case Intrinsic::x86_avx2_psra_w:
11026   case Intrinsic::x86_avx2_psra_d: {
11027     unsigned Opcode;
11028     switch (IntNo) {
11029     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11030     case Intrinsic::x86_sse2_psll_w:
11031     case Intrinsic::x86_sse2_psll_d:
11032     case Intrinsic::x86_sse2_psll_q:
11033     case Intrinsic::x86_avx2_psll_w:
11034     case Intrinsic::x86_avx2_psll_d:
11035     case Intrinsic::x86_avx2_psll_q:
11036       Opcode = X86ISD::VSHL;
11037       break;
11038     case Intrinsic::x86_sse2_psrl_w:
11039     case Intrinsic::x86_sse2_psrl_d:
11040     case Intrinsic::x86_sse2_psrl_q:
11041     case Intrinsic::x86_avx2_psrl_w:
11042     case Intrinsic::x86_avx2_psrl_d:
11043     case Intrinsic::x86_avx2_psrl_q:
11044       Opcode = X86ISD::VSRL;
11045       break;
11046     case Intrinsic::x86_sse2_psra_w:
11047     case Intrinsic::x86_sse2_psra_d:
11048     case Intrinsic::x86_avx2_psra_w:
11049     case Intrinsic::x86_avx2_psra_d:
11050       Opcode = X86ISD::VSRA;
11051       break;
11052     }
11053     return DAG.getNode(Opcode, dl, Op.getValueType(),
11054                        Op.getOperand(1), Op.getOperand(2));
11055   }
11056
11057   // SSE/AVX immediate shift intrinsics
11058   case Intrinsic::x86_sse2_pslli_w:
11059   case Intrinsic::x86_sse2_pslli_d:
11060   case Intrinsic::x86_sse2_pslli_q:
11061   case Intrinsic::x86_avx2_pslli_w:
11062   case Intrinsic::x86_avx2_pslli_d:
11063   case Intrinsic::x86_avx2_pslli_q:
11064   case Intrinsic::x86_sse2_psrli_w:
11065   case Intrinsic::x86_sse2_psrli_d:
11066   case Intrinsic::x86_sse2_psrli_q:
11067   case Intrinsic::x86_avx2_psrli_w:
11068   case Intrinsic::x86_avx2_psrli_d:
11069   case Intrinsic::x86_avx2_psrli_q:
11070   case Intrinsic::x86_sse2_psrai_w:
11071   case Intrinsic::x86_sse2_psrai_d:
11072   case Intrinsic::x86_avx2_psrai_w:
11073   case Intrinsic::x86_avx2_psrai_d: {
11074     unsigned Opcode;
11075     switch (IntNo) {
11076     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11077     case Intrinsic::x86_sse2_pslli_w:
11078     case Intrinsic::x86_sse2_pslli_d:
11079     case Intrinsic::x86_sse2_pslli_q:
11080     case Intrinsic::x86_avx2_pslli_w:
11081     case Intrinsic::x86_avx2_pslli_d:
11082     case Intrinsic::x86_avx2_pslli_q:
11083       Opcode = X86ISD::VSHLI;
11084       break;
11085     case Intrinsic::x86_sse2_psrli_w:
11086     case Intrinsic::x86_sse2_psrli_d:
11087     case Intrinsic::x86_sse2_psrli_q:
11088     case Intrinsic::x86_avx2_psrli_w:
11089     case Intrinsic::x86_avx2_psrli_d:
11090     case Intrinsic::x86_avx2_psrli_q:
11091       Opcode = X86ISD::VSRLI;
11092       break;
11093     case Intrinsic::x86_sse2_psrai_w:
11094     case Intrinsic::x86_sse2_psrai_d:
11095     case Intrinsic::x86_avx2_psrai_w:
11096     case Intrinsic::x86_avx2_psrai_d:
11097       Opcode = X86ISD::VSRAI;
11098       break;
11099     }
11100     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11101                                Op.getOperand(1), Op.getOperand(2), DAG);
11102   }
11103
11104   case Intrinsic::x86_sse42_pcmpistria128:
11105   case Intrinsic::x86_sse42_pcmpestria128:
11106   case Intrinsic::x86_sse42_pcmpistric128:
11107   case Intrinsic::x86_sse42_pcmpestric128:
11108   case Intrinsic::x86_sse42_pcmpistrio128:
11109   case Intrinsic::x86_sse42_pcmpestrio128:
11110   case Intrinsic::x86_sse42_pcmpistris128:
11111   case Intrinsic::x86_sse42_pcmpestris128:
11112   case Intrinsic::x86_sse42_pcmpistriz128:
11113   case Intrinsic::x86_sse42_pcmpestriz128: {
11114     unsigned Opcode;
11115     unsigned X86CC;
11116     switch (IntNo) {
11117     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11118     case Intrinsic::x86_sse42_pcmpistria128:
11119       Opcode = X86ISD::PCMPISTRI;
11120       X86CC = X86::COND_A;
11121       break;
11122     case Intrinsic::x86_sse42_pcmpestria128:
11123       Opcode = X86ISD::PCMPESTRI;
11124       X86CC = X86::COND_A;
11125       break;
11126     case Intrinsic::x86_sse42_pcmpistric128:
11127       Opcode = X86ISD::PCMPISTRI;
11128       X86CC = X86::COND_B;
11129       break;
11130     case Intrinsic::x86_sse42_pcmpestric128:
11131       Opcode = X86ISD::PCMPESTRI;
11132       X86CC = X86::COND_B;
11133       break;
11134     case Intrinsic::x86_sse42_pcmpistrio128:
11135       Opcode = X86ISD::PCMPISTRI;
11136       X86CC = X86::COND_O;
11137       break;
11138     case Intrinsic::x86_sse42_pcmpestrio128:
11139       Opcode = X86ISD::PCMPESTRI;
11140       X86CC = X86::COND_O;
11141       break;
11142     case Intrinsic::x86_sse42_pcmpistris128:
11143       Opcode = X86ISD::PCMPISTRI;
11144       X86CC = X86::COND_S;
11145       break;
11146     case Intrinsic::x86_sse42_pcmpestris128:
11147       Opcode = X86ISD::PCMPESTRI;
11148       X86CC = X86::COND_S;
11149       break;
11150     case Intrinsic::x86_sse42_pcmpistriz128:
11151       Opcode = X86ISD::PCMPISTRI;
11152       X86CC = X86::COND_E;
11153       break;
11154     case Intrinsic::x86_sse42_pcmpestriz128:
11155       Opcode = X86ISD::PCMPESTRI;
11156       X86CC = X86::COND_E;
11157       break;
11158     }
11159     SmallVector<SDValue, 5> NewOps;
11160     NewOps.append(Op->op_begin()+1, Op->op_end());
11161     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11162     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11163     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11164                                 DAG.getConstant(X86CC, MVT::i8),
11165                                 SDValue(PCMP.getNode(), 1));
11166     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11167   }
11168
11169   case Intrinsic::x86_sse42_pcmpistri128:
11170   case Intrinsic::x86_sse42_pcmpestri128: {
11171     unsigned Opcode;
11172     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11173       Opcode = X86ISD::PCMPISTRI;
11174     else
11175       Opcode = X86ISD::PCMPESTRI;
11176
11177     SmallVector<SDValue, 5> NewOps;
11178     NewOps.append(Op->op_begin()+1, Op->op_end());
11179     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11180     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11181   }
11182   case Intrinsic::x86_fma_vfmadd_ps:
11183   case Intrinsic::x86_fma_vfmadd_pd:
11184   case Intrinsic::x86_fma_vfmsub_ps:
11185   case Intrinsic::x86_fma_vfmsub_pd:
11186   case Intrinsic::x86_fma_vfnmadd_ps:
11187   case Intrinsic::x86_fma_vfnmadd_pd:
11188   case Intrinsic::x86_fma_vfnmsub_ps:
11189   case Intrinsic::x86_fma_vfnmsub_pd:
11190   case Intrinsic::x86_fma_vfmaddsub_ps:
11191   case Intrinsic::x86_fma_vfmaddsub_pd:
11192   case Intrinsic::x86_fma_vfmsubadd_ps:
11193   case Intrinsic::x86_fma_vfmsubadd_pd:
11194   case Intrinsic::x86_fma_vfmadd_ps_256:
11195   case Intrinsic::x86_fma_vfmadd_pd_256:
11196   case Intrinsic::x86_fma_vfmsub_ps_256:
11197   case Intrinsic::x86_fma_vfmsub_pd_256:
11198   case Intrinsic::x86_fma_vfnmadd_ps_256:
11199   case Intrinsic::x86_fma_vfnmadd_pd_256:
11200   case Intrinsic::x86_fma_vfnmsub_ps_256:
11201   case Intrinsic::x86_fma_vfnmsub_pd_256:
11202   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11203   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11204   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11205   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11206     unsigned Opc;
11207     switch (IntNo) {
11208     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11209     case Intrinsic::x86_fma_vfmadd_ps:
11210     case Intrinsic::x86_fma_vfmadd_pd:
11211     case Intrinsic::x86_fma_vfmadd_ps_256:
11212     case Intrinsic::x86_fma_vfmadd_pd_256:
11213       Opc = X86ISD::FMADD;
11214       break;
11215     case Intrinsic::x86_fma_vfmsub_ps:
11216     case Intrinsic::x86_fma_vfmsub_pd:
11217     case Intrinsic::x86_fma_vfmsub_ps_256:
11218     case Intrinsic::x86_fma_vfmsub_pd_256:
11219       Opc = X86ISD::FMSUB;
11220       break;
11221     case Intrinsic::x86_fma_vfnmadd_ps:
11222     case Intrinsic::x86_fma_vfnmadd_pd:
11223     case Intrinsic::x86_fma_vfnmadd_ps_256:
11224     case Intrinsic::x86_fma_vfnmadd_pd_256:
11225       Opc = X86ISD::FNMADD;
11226       break;
11227     case Intrinsic::x86_fma_vfnmsub_ps:
11228     case Intrinsic::x86_fma_vfnmsub_pd:
11229     case Intrinsic::x86_fma_vfnmsub_ps_256:
11230     case Intrinsic::x86_fma_vfnmsub_pd_256:
11231       Opc = X86ISD::FNMSUB;
11232       break;
11233     case Intrinsic::x86_fma_vfmaddsub_ps:
11234     case Intrinsic::x86_fma_vfmaddsub_pd:
11235     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11236     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11237       Opc = X86ISD::FMADDSUB;
11238       break;
11239     case Intrinsic::x86_fma_vfmsubadd_ps:
11240     case Intrinsic::x86_fma_vfmsubadd_pd:
11241     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11242     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11243       Opc = X86ISD::FMSUBADD;
11244       break;
11245     }
11246
11247     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11248                        Op.getOperand(2), Op.getOperand(3));
11249   }
11250   }
11251 }
11252
11253 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11254   SDLoc dl(Op);
11255   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11256   switch (IntNo) {
11257   default: return SDValue();    // Don't custom lower most intrinsics.
11258
11259   // RDRAND/RDSEED intrinsics.
11260   case Intrinsic::x86_rdrand_16:
11261   case Intrinsic::x86_rdrand_32:
11262   case Intrinsic::x86_rdrand_64:
11263   case Intrinsic::x86_rdseed_16:
11264   case Intrinsic::x86_rdseed_32:
11265   case Intrinsic::x86_rdseed_64: {
11266     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11267                        IntNo == Intrinsic::x86_rdseed_32 ||
11268                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11269                                                             X86ISD::RDRAND;
11270     // Emit the node with the right value type.
11271     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11272     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11273
11274     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11275     // Otherwise return the value from Rand, which is always 0, casted to i32.
11276     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11277                       DAG.getConstant(1, Op->getValueType(1)),
11278                       DAG.getConstant(X86::COND_B, MVT::i32),
11279                       SDValue(Result.getNode(), 1) };
11280     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11281                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11282                                   Ops, array_lengthof(Ops));
11283
11284     // Return { result, isValid, chain }.
11285     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11286                        SDValue(Result.getNode(), 2));
11287   }
11288
11289   // XTEST intrinsics.
11290   case Intrinsic::x86_xtest: {
11291     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11292     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11293     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11294                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11295                                 InTrans);
11296     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11297     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11298                        Ret, SDValue(InTrans.getNode(), 1));
11299   }
11300   }
11301 }
11302
11303 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11304                                            SelectionDAG &DAG) const {
11305   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11306   MFI->setReturnAddressIsTaken(true);
11307
11308   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11309   SDLoc dl(Op);
11310   EVT PtrVT = getPointerTy();
11311
11312   if (Depth > 0) {
11313     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11314     const X86RegisterInfo *RegInfo =
11315       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11316     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11317     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11318                        DAG.getNode(ISD::ADD, dl, PtrVT,
11319                                    FrameAddr, Offset),
11320                        MachinePointerInfo(), false, false, false, 0);
11321   }
11322
11323   // Just load the return address.
11324   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11325   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11326                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11327 }
11328
11329 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11330   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11331   MFI->setFrameAddressIsTaken(true);
11332
11333   EVT VT = Op.getValueType();
11334   SDLoc dl(Op);  // FIXME probably not meaningful
11335   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11336   const X86RegisterInfo *RegInfo =
11337     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11338   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11339   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11340           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11341          "Invalid Frame Register!");
11342   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11343   while (Depth--)
11344     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11345                             MachinePointerInfo(),
11346                             false, false, false, 0);
11347   return FrameAddr;
11348 }
11349
11350 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11351                                                      SelectionDAG &DAG) const {
11352   const X86RegisterInfo *RegInfo =
11353     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11354   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11355 }
11356
11357 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11358   SDValue Chain     = Op.getOperand(0);
11359   SDValue Offset    = Op.getOperand(1);
11360   SDValue Handler   = Op.getOperand(2);
11361   SDLoc dl      (Op);
11362
11363   EVT PtrVT = getPointerTy();
11364   const X86RegisterInfo *RegInfo =
11365     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11366   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11367   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11368           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11369          "Invalid Frame Register!");
11370   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11371   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11372
11373   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11374                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11375   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11376   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11377                        false, false, 0);
11378   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11379
11380   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11381                      DAG.getRegister(StoreAddrReg, PtrVT));
11382 }
11383
11384 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11385                                                SelectionDAG &DAG) const {
11386   SDLoc DL(Op);
11387   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11388                      DAG.getVTList(MVT::i32, MVT::Other),
11389                      Op.getOperand(0), Op.getOperand(1));
11390 }
11391
11392 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11393                                                 SelectionDAG &DAG) const {
11394   SDLoc DL(Op);
11395   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11396                      Op.getOperand(0), Op.getOperand(1));
11397 }
11398
11399 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11400   return Op.getOperand(0);
11401 }
11402
11403 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11404                                                 SelectionDAG &DAG) const {
11405   SDValue Root = Op.getOperand(0);
11406   SDValue Trmp = Op.getOperand(1); // trampoline
11407   SDValue FPtr = Op.getOperand(2); // nested function
11408   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11409   SDLoc dl (Op);
11410
11411   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11412   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11413
11414   if (Subtarget->is64Bit()) {
11415     SDValue OutChains[6];
11416
11417     // Large code-model.
11418     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11419     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11420
11421     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11422     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11423
11424     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11425
11426     // Load the pointer to the nested function into R11.
11427     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11428     SDValue Addr = Trmp;
11429     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11430                                 Addr, MachinePointerInfo(TrmpAddr),
11431                                 false, false, 0);
11432
11433     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11434                        DAG.getConstant(2, MVT::i64));
11435     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11436                                 MachinePointerInfo(TrmpAddr, 2),
11437                                 false, false, 2);
11438
11439     // Load the 'nest' parameter value into R10.
11440     // R10 is specified in X86CallingConv.td
11441     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11442     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11443                        DAG.getConstant(10, MVT::i64));
11444     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11445                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11446                                 false, false, 0);
11447
11448     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11449                        DAG.getConstant(12, MVT::i64));
11450     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11451                                 MachinePointerInfo(TrmpAddr, 12),
11452                                 false, false, 2);
11453
11454     // Jump to the nested function.
11455     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11456     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11457                        DAG.getConstant(20, MVT::i64));
11458     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11459                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11460                                 false, false, 0);
11461
11462     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11463     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11464                        DAG.getConstant(22, MVT::i64));
11465     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11466                                 MachinePointerInfo(TrmpAddr, 22),
11467                                 false, false, 0);
11468
11469     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11470   } else {
11471     const Function *Func =
11472       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11473     CallingConv::ID CC = Func->getCallingConv();
11474     unsigned NestReg;
11475
11476     switch (CC) {
11477     default:
11478       llvm_unreachable("Unsupported calling convention");
11479     case CallingConv::C:
11480     case CallingConv::X86_StdCall: {
11481       // Pass 'nest' parameter in ECX.
11482       // Must be kept in sync with X86CallingConv.td
11483       NestReg = X86::ECX;
11484
11485       // Check that ECX wasn't needed by an 'inreg' parameter.
11486       FunctionType *FTy = Func->getFunctionType();
11487       const AttributeSet &Attrs = Func->getAttributes();
11488
11489       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11490         unsigned InRegCount = 0;
11491         unsigned Idx = 1;
11492
11493         for (FunctionType::param_iterator I = FTy->param_begin(),
11494              E = FTy->param_end(); I != E; ++I, ++Idx)
11495           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11496             // FIXME: should only count parameters that are lowered to integers.
11497             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11498
11499         if (InRegCount > 2) {
11500           report_fatal_error("Nest register in use - reduce number of inreg"
11501                              " parameters!");
11502         }
11503       }
11504       break;
11505     }
11506     case CallingConv::X86_FastCall:
11507     case CallingConv::X86_ThisCall:
11508     case CallingConv::Fast:
11509       // Pass 'nest' parameter in EAX.
11510       // Must be kept in sync with X86CallingConv.td
11511       NestReg = X86::EAX;
11512       break;
11513     }
11514
11515     SDValue OutChains[4];
11516     SDValue Addr, Disp;
11517
11518     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11519                        DAG.getConstant(10, MVT::i32));
11520     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11521
11522     // This is storing the opcode for MOV32ri.
11523     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11524     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11525     OutChains[0] = DAG.getStore(Root, dl,
11526                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11527                                 Trmp, MachinePointerInfo(TrmpAddr),
11528                                 false, false, 0);
11529
11530     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11531                        DAG.getConstant(1, MVT::i32));
11532     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11533                                 MachinePointerInfo(TrmpAddr, 1),
11534                                 false, false, 1);
11535
11536     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11537     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11538                        DAG.getConstant(5, MVT::i32));
11539     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11540                                 MachinePointerInfo(TrmpAddr, 5),
11541                                 false, false, 1);
11542
11543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11544                        DAG.getConstant(6, MVT::i32));
11545     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11546                                 MachinePointerInfo(TrmpAddr, 6),
11547                                 false, false, 1);
11548
11549     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11550   }
11551 }
11552
11553 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11554                                             SelectionDAG &DAG) const {
11555   /*
11556    The rounding mode is in bits 11:10 of FPSR, and has the following
11557    settings:
11558      00 Round to nearest
11559      01 Round to -inf
11560      10 Round to +inf
11561      11 Round to 0
11562
11563   FLT_ROUNDS, on the other hand, expects the following:
11564     -1 Undefined
11565      0 Round to 0
11566      1 Round to nearest
11567      2 Round to +inf
11568      3 Round to -inf
11569
11570   To perform the conversion, we do:
11571     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11572   */
11573
11574   MachineFunction &MF = DAG.getMachineFunction();
11575   const TargetMachine &TM = MF.getTarget();
11576   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11577   unsigned StackAlignment = TFI.getStackAlignment();
11578   EVT VT = Op.getValueType();
11579   SDLoc DL(Op);
11580
11581   // Save FP Control Word to stack slot
11582   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11583   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11584
11585   MachineMemOperand *MMO =
11586    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11587                            MachineMemOperand::MOStore, 2, 2);
11588
11589   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11590   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11591                                           DAG.getVTList(MVT::Other),
11592                                           Ops, array_lengthof(Ops), MVT::i16,
11593                                           MMO);
11594
11595   // Load FP Control Word from stack slot
11596   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11597                             MachinePointerInfo(), false, false, false, 0);
11598
11599   // Transform as necessary
11600   SDValue CWD1 =
11601     DAG.getNode(ISD::SRL, DL, MVT::i16,
11602                 DAG.getNode(ISD::AND, DL, MVT::i16,
11603                             CWD, DAG.getConstant(0x800, MVT::i16)),
11604                 DAG.getConstant(11, MVT::i8));
11605   SDValue CWD2 =
11606     DAG.getNode(ISD::SRL, DL, MVT::i16,
11607                 DAG.getNode(ISD::AND, DL, MVT::i16,
11608                             CWD, DAG.getConstant(0x400, MVT::i16)),
11609                 DAG.getConstant(9, MVT::i8));
11610
11611   SDValue RetVal =
11612     DAG.getNode(ISD::AND, DL, MVT::i16,
11613                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11614                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11615                             DAG.getConstant(1, MVT::i16)),
11616                 DAG.getConstant(3, MVT::i16));
11617
11618   return DAG.getNode((VT.getSizeInBits() < 16 ?
11619                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11620 }
11621
11622 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11623   EVT VT = Op.getValueType();
11624   EVT OpVT = VT;
11625   unsigned NumBits = VT.getSizeInBits();
11626   SDLoc dl(Op);
11627
11628   Op = Op.getOperand(0);
11629   if (VT == MVT::i8) {
11630     // Zero extend to i32 since there is not an i8 bsr.
11631     OpVT = MVT::i32;
11632     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11633   }
11634
11635   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11636   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11637   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11638
11639   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11640   SDValue Ops[] = {
11641     Op,
11642     DAG.getConstant(NumBits+NumBits-1, OpVT),
11643     DAG.getConstant(X86::COND_E, MVT::i8),
11644     Op.getValue(1)
11645   };
11646   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11647
11648   // Finally xor with NumBits-1.
11649   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11650
11651   if (VT == MVT::i8)
11652     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11653   return Op;
11654 }
11655
11656 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11657   EVT VT = Op.getValueType();
11658   EVT OpVT = VT;
11659   unsigned NumBits = VT.getSizeInBits();
11660   SDLoc dl(Op);
11661
11662   Op = Op.getOperand(0);
11663   if (VT == MVT::i8) {
11664     // Zero extend to i32 since there is not an i8 bsr.
11665     OpVT = MVT::i32;
11666     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11667   }
11668
11669   // Issue a bsr (scan bits in reverse).
11670   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11671   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11672
11673   // And xor with NumBits-1.
11674   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11675
11676   if (VT == MVT::i8)
11677     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11678   return Op;
11679 }
11680
11681 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11682   EVT VT = Op.getValueType();
11683   unsigned NumBits = VT.getSizeInBits();
11684   SDLoc dl(Op);
11685   Op = Op.getOperand(0);
11686
11687   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11688   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11689   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11690
11691   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11692   SDValue Ops[] = {
11693     Op,
11694     DAG.getConstant(NumBits, VT),
11695     DAG.getConstant(X86::COND_E, MVT::i8),
11696     Op.getValue(1)
11697   };
11698   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11699 }
11700
11701 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11702 // ones, and then concatenate the result back.
11703 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11704   EVT VT = Op.getValueType();
11705
11706   assert(VT.is256BitVector() && VT.isInteger() &&
11707          "Unsupported value type for operation");
11708
11709   unsigned NumElems = VT.getVectorNumElements();
11710   SDLoc dl(Op);
11711
11712   // Extract the LHS vectors
11713   SDValue LHS = Op.getOperand(0);
11714   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11715   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11716
11717   // Extract the RHS vectors
11718   SDValue RHS = Op.getOperand(1);
11719   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11720   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11721
11722   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11723   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11724
11725   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11726                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11727                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11728 }
11729
11730 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11731   assert(Op.getValueType().is256BitVector() &&
11732          Op.getValueType().isInteger() &&
11733          "Only handle AVX 256-bit vector integer operation");
11734   return Lower256IntArith(Op, DAG);
11735 }
11736
11737 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11738   assert(Op.getValueType().is256BitVector() &&
11739          Op.getValueType().isInteger() &&
11740          "Only handle AVX 256-bit vector integer operation");
11741   return Lower256IntArith(Op, DAG);
11742 }
11743
11744 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11745                         SelectionDAG &DAG) {
11746   SDLoc dl(Op);
11747   EVT VT = Op.getValueType();
11748
11749   // Decompose 256-bit ops into smaller 128-bit ops.
11750   if (VT.is256BitVector() && !Subtarget->hasInt256())
11751     return Lower256IntArith(Op, DAG);
11752
11753   SDValue A = Op.getOperand(0);
11754   SDValue B = Op.getOperand(1);
11755
11756   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11757   if (VT == MVT::v4i32) {
11758     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11759            "Should not custom lower when pmuldq is available!");
11760
11761     // Extract the odd parts.
11762     static const int UnpackMask[] = { 1, -1, 3, -1 };
11763     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11764     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11765
11766     // Multiply the even parts.
11767     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11768     // Now multiply odd parts.
11769     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11770
11771     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11772     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11773
11774     // Merge the two vectors back together with a shuffle. This expands into 2
11775     // shuffles.
11776     static const int ShufMask[] = { 0, 4, 2, 6 };
11777     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11778   }
11779
11780   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11781          "Only know how to lower V2I64/V4I64 multiply");
11782
11783   //  Ahi = psrlqi(a, 32);
11784   //  Bhi = psrlqi(b, 32);
11785   //
11786   //  AloBlo = pmuludq(a, b);
11787   //  AloBhi = pmuludq(a, Bhi);
11788   //  AhiBlo = pmuludq(Ahi, b);
11789
11790   //  AloBhi = psllqi(AloBhi, 32);
11791   //  AhiBlo = psllqi(AhiBlo, 32);
11792   //  return AloBlo + AloBhi + AhiBlo;
11793
11794   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11795
11796   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11797   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11798
11799   // Bit cast to 32-bit vectors for MULUDQ
11800   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11801   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11802   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11803   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11804   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11805
11806   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11807   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11808   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11809
11810   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11811   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11812
11813   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11814   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11815 }
11816
11817 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11818   EVT VT = Op.getValueType();
11819   EVT EltTy = VT.getVectorElementType();
11820   unsigned NumElts = VT.getVectorNumElements();
11821   SDValue N0 = Op.getOperand(0);
11822   SDLoc dl(Op);
11823
11824   // Lower sdiv X, pow2-const.
11825   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11826   if (!C)
11827     return SDValue();
11828
11829   APInt SplatValue, SplatUndef;
11830   unsigned SplatBitSize;
11831   bool HasAnyUndefs;
11832   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11833                           HasAnyUndefs) ||
11834       EltTy.getSizeInBits() < SplatBitSize)
11835     return SDValue();
11836
11837   if ((SplatValue != 0) &&
11838       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11839     unsigned lg2 = SplatValue.countTrailingZeros();
11840     // Splat the sign bit.
11841     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11842     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11843     // Add (N0 < 0) ? abs2 - 1 : 0;
11844     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11845     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11846     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11847     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11848     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11849
11850     // If we're dividing by a positive value, we're done.  Otherwise, we must
11851     // negate the result.
11852     if (SplatValue.isNonNegative())
11853       return SRA;
11854
11855     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11856     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11857     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11858   }
11859   return SDValue();
11860 }
11861
11862 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11863                                          const X86Subtarget *Subtarget) {
11864   EVT VT = Op.getValueType();
11865   SDLoc dl(Op);
11866   SDValue R = Op.getOperand(0);
11867   SDValue Amt = Op.getOperand(1);
11868
11869   // Optimize shl/srl/sra with constant shift amount.
11870   if (isSplatVector(Amt.getNode())) {
11871     SDValue SclrAmt = Amt->getOperand(0);
11872     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11873       uint64_t ShiftAmt = C->getZExtValue();
11874
11875       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11876           (Subtarget->hasInt256() &&
11877            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11878         if (Op.getOpcode() == ISD::SHL)
11879           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11880                              DAG.getConstant(ShiftAmt, MVT::i32));
11881         if (Op.getOpcode() == ISD::SRL)
11882           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11883                              DAG.getConstant(ShiftAmt, MVT::i32));
11884         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11885           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11886                              DAG.getConstant(ShiftAmt, MVT::i32));
11887       }
11888
11889       if (VT == MVT::v16i8) {
11890         if (Op.getOpcode() == ISD::SHL) {
11891           // Make a large shift.
11892           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11893                                     DAG.getConstant(ShiftAmt, MVT::i32));
11894           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11895           // Zero out the rightmost bits.
11896           SmallVector<SDValue, 16> V(16,
11897                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11898                                                      MVT::i8));
11899           return DAG.getNode(ISD::AND, dl, VT, SHL,
11900                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11901         }
11902         if (Op.getOpcode() == ISD::SRL) {
11903           // Make a large shift.
11904           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11905                                     DAG.getConstant(ShiftAmt, MVT::i32));
11906           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11907           // Zero out the leftmost bits.
11908           SmallVector<SDValue, 16> V(16,
11909                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11910                                                      MVT::i8));
11911           return DAG.getNode(ISD::AND, dl, VT, SRL,
11912                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11913         }
11914         if (Op.getOpcode() == ISD::SRA) {
11915           if (ShiftAmt == 7) {
11916             // R s>> 7  ===  R s< 0
11917             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11918             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11919           }
11920
11921           // R s>> a === ((R u>> a) ^ m) - m
11922           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11923           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11924                                                          MVT::i8));
11925           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11926           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11927           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11928           return Res;
11929         }
11930         llvm_unreachable("Unknown shift opcode.");
11931       }
11932
11933       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11934         if (Op.getOpcode() == ISD::SHL) {
11935           // Make a large shift.
11936           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11937                                     DAG.getConstant(ShiftAmt, MVT::i32));
11938           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11939           // Zero out the rightmost bits.
11940           SmallVector<SDValue, 32> V(32,
11941                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11942                                                      MVT::i8));
11943           return DAG.getNode(ISD::AND, dl, VT, SHL,
11944                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11945         }
11946         if (Op.getOpcode() == ISD::SRL) {
11947           // Make a large shift.
11948           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11949                                     DAG.getConstant(ShiftAmt, MVT::i32));
11950           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11951           // Zero out the leftmost bits.
11952           SmallVector<SDValue, 32> V(32,
11953                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11954                                                      MVT::i8));
11955           return DAG.getNode(ISD::AND, dl, VT, SRL,
11956                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11957         }
11958         if (Op.getOpcode() == ISD::SRA) {
11959           if (ShiftAmt == 7) {
11960             // R s>> 7  ===  R s< 0
11961             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11962             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11963           }
11964
11965           // R s>> a === ((R u>> a) ^ m) - m
11966           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11967           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11968                                                          MVT::i8));
11969           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11970           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11971           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11972           return Res;
11973         }
11974         llvm_unreachable("Unknown shift opcode.");
11975       }
11976     }
11977   }
11978
11979   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11980   if (!Subtarget->is64Bit() &&
11981       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11982       Amt.getOpcode() == ISD::BITCAST &&
11983       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11984     Amt = Amt.getOperand(0);
11985     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11986                      VT.getVectorNumElements();
11987     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11988     uint64_t ShiftAmt = 0;
11989     for (unsigned i = 0; i != Ratio; ++i) {
11990       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11991       if (C == 0)
11992         return SDValue();
11993       // 6 == Log2(64)
11994       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11995     }
11996     // Check remaining shift amounts.
11997     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11998       uint64_t ShAmt = 0;
11999       for (unsigned j = 0; j != Ratio; ++j) {
12000         ConstantSDNode *C =
12001           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12002         if (C == 0)
12003           return SDValue();
12004         // 6 == Log2(64)
12005         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12006       }
12007       if (ShAmt != ShiftAmt)
12008         return SDValue();
12009     }
12010     switch (Op.getOpcode()) {
12011     default:
12012       llvm_unreachable("Unknown shift opcode!");
12013     case ISD::SHL:
12014       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12015                          DAG.getConstant(ShiftAmt, MVT::i32));
12016     case ISD::SRL:
12017       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12018                          DAG.getConstant(ShiftAmt, MVT::i32));
12019     case ISD::SRA:
12020       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12021                          DAG.getConstant(ShiftAmt, MVT::i32));
12022     }
12023   }
12024
12025   return SDValue();
12026 }
12027
12028 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12029                                         const X86Subtarget* Subtarget) {
12030   EVT VT = Op.getValueType();
12031   SDLoc dl(Op);
12032   SDValue R = Op.getOperand(0);
12033   SDValue Amt = Op.getOperand(1);
12034
12035   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12036       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12037       (Subtarget->hasInt256() &&
12038        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12039         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12040     SDValue BaseShAmt;
12041     EVT EltVT = VT.getVectorElementType();
12042
12043     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12044       unsigned NumElts = VT.getVectorNumElements();
12045       unsigned i, j;
12046       for (i = 0; i != NumElts; ++i) {
12047         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12048           continue;
12049         break;
12050       }
12051       for (j = i; j != NumElts; ++j) {
12052         SDValue Arg = Amt.getOperand(j);
12053         if (Arg.getOpcode() == ISD::UNDEF) continue;
12054         if (Arg != Amt.getOperand(i))
12055           break;
12056       }
12057       if (i != NumElts && j == NumElts)
12058         BaseShAmt = Amt.getOperand(i);
12059     } else {
12060       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12061         Amt = Amt.getOperand(0);
12062       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12063                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12064         SDValue InVec = Amt.getOperand(0);
12065         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12066           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12067           unsigned i = 0;
12068           for (; i != NumElts; ++i) {
12069             SDValue Arg = InVec.getOperand(i);
12070             if (Arg.getOpcode() == ISD::UNDEF) continue;
12071             BaseShAmt = Arg;
12072             break;
12073           }
12074         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12075            if (ConstantSDNode *C =
12076                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12077              unsigned SplatIdx =
12078                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12079              if (C->getZExtValue() == SplatIdx)
12080                BaseShAmt = InVec.getOperand(1);
12081            }
12082         }
12083         if (BaseShAmt.getNode() == 0)
12084           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12085                                   DAG.getIntPtrConstant(0));
12086       }
12087     }
12088
12089     if (BaseShAmt.getNode()) {
12090       if (EltVT.bitsGT(MVT::i32))
12091         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12092       else if (EltVT.bitsLT(MVT::i32))
12093         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12094
12095       switch (Op.getOpcode()) {
12096       default:
12097         llvm_unreachable("Unknown shift opcode!");
12098       case ISD::SHL:
12099         switch (VT.getSimpleVT().SimpleTy) {
12100         default: return SDValue();
12101         case MVT::v2i64:
12102         case MVT::v4i32:
12103         case MVT::v8i16:
12104         case MVT::v4i64:
12105         case MVT::v8i32:
12106         case MVT::v16i16:
12107           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12108         }
12109       case ISD::SRA:
12110         switch (VT.getSimpleVT().SimpleTy) {
12111         default: return SDValue();
12112         case MVT::v4i32:
12113         case MVT::v8i16:
12114         case MVT::v8i32:
12115         case MVT::v16i16:
12116           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12117         }
12118       case ISD::SRL:
12119         switch (VT.getSimpleVT().SimpleTy) {
12120         default: return SDValue();
12121         case MVT::v2i64:
12122         case MVT::v4i32:
12123         case MVT::v8i16:
12124         case MVT::v4i64:
12125         case MVT::v8i32:
12126         case MVT::v16i16:
12127           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12128         }
12129       }
12130     }
12131   }
12132
12133   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12134   if (!Subtarget->is64Bit() &&
12135       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12136       Amt.getOpcode() == ISD::BITCAST &&
12137       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12138     Amt = Amt.getOperand(0);
12139     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12140                      VT.getVectorNumElements();
12141     std::vector<SDValue> Vals(Ratio);
12142     for (unsigned i = 0; i != Ratio; ++i)
12143       Vals[i] = Amt.getOperand(i);
12144     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12145       for (unsigned j = 0; j != Ratio; ++j)
12146         if (Vals[j] != Amt.getOperand(i + j))
12147           return SDValue();
12148     }
12149     switch (Op.getOpcode()) {
12150     default:
12151       llvm_unreachable("Unknown shift opcode!");
12152     case ISD::SHL:
12153       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12154     case ISD::SRL:
12155       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12156     case ISD::SRA:
12157       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12158     }
12159   }
12160
12161   return SDValue();
12162 }
12163
12164 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12165
12166   EVT VT = Op.getValueType();
12167   SDLoc dl(Op);
12168   SDValue R = Op.getOperand(0);
12169   SDValue Amt = Op.getOperand(1);
12170   SDValue V;
12171
12172   if (!Subtarget->hasSSE2())
12173     return SDValue();
12174
12175   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12176   if (V.getNode())
12177     return V;
12178
12179   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12180   if (V.getNode())
12181       return V;
12182
12183   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12184   if (Subtarget->hasInt256()) {
12185     if (Op.getOpcode() == ISD::SRL &&
12186         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12187          VT == MVT::v4i64 || VT == MVT::v8i32))
12188       return Op;
12189     if (Op.getOpcode() == ISD::SHL &&
12190         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12191          VT == MVT::v4i64 || VT == MVT::v8i32))
12192       return Op;
12193     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12194       return Op;
12195   }
12196
12197   // Lower SHL with variable shift amount.
12198   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12199     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12200
12201     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12202     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12203     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12204     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12205   }
12206   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12207     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12208
12209     // a = a << 5;
12210     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12211     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12212
12213     // Turn 'a' into a mask suitable for VSELECT
12214     SDValue VSelM = DAG.getConstant(0x80, VT);
12215     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12216     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12217
12218     SDValue CM1 = DAG.getConstant(0x0f, VT);
12219     SDValue CM2 = DAG.getConstant(0x3f, VT);
12220
12221     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12222     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12223     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12224                             DAG.getConstant(4, MVT::i32), DAG);
12225     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12226     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12227
12228     // a += a
12229     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12230     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12231     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12232
12233     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12234     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12235     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12236                             DAG.getConstant(2, MVT::i32), DAG);
12237     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12238     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12239
12240     // a += a
12241     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12242     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12243     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12244
12245     // return VSELECT(r, r+r, a);
12246     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12247                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12248     return R;
12249   }
12250
12251   // Decompose 256-bit shifts into smaller 128-bit shifts.
12252   if (VT.is256BitVector()) {
12253     unsigned NumElems = VT.getVectorNumElements();
12254     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12255     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12256
12257     // Extract the two vectors
12258     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12259     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12260
12261     // Recreate the shift amount vectors
12262     SDValue Amt1, Amt2;
12263     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12264       // Constant shift amount
12265       SmallVector<SDValue, 4> Amt1Csts;
12266       SmallVector<SDValue, 4> Amt2Csts;
12267       for (unsigned i = 0; i != NumElems/2; ++i)
12268         Amt1Csts.push_back(Amt->getOperand(i));
12269       for (unsigned i = NumElems/2; i != NumElems; ++i)
12270         Amt2Csts.push_back(Amt->getOperand(i));
12271
12272       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12273                                  &Amt1Csts[0], NumElems/2);
12274       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12275                                  &Amt2Csts[0], NumElems/2);
12276     } else {
12277       // Variable shift amount
12278       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12279       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12280     }
12281
12282     // Issue new vector shifts for the smaller types
12283     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12284     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12285
12286     // Concatenate the result back
12287     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12288   }
12289
12290   return SDValue();
12291 }
12292
12293 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12294   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12295   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12296   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12297   // has only one use.
12298   SDNode *N = Op.getNode();
12299   SDValue LHS = N->getOperand(0);
12300   SDValue RHS = N->getOperand(1);
12301   unsigned BaseOp = 0;
12302   unsigned Cond = 0;
12303   SDLoc DL(Op);
12304   switch (Op.getOpcode()) {
12305   default: llvm_unreachable("Unknown ovf instruction!");
12306   case ISD::SADDO:
12307     // A subtract of one will be selected as a INC. Note that INC doesn't
12308     // set CF, so we can't do this for UADDO.
12309     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12310       if (C->isOne()) {
12311         BaseOp = X86ISD::INC;
12312         Cond = X86::COND_O;
12313         break;
12314       }
12315     BaseOp = X86ISD::ADD;
12316     Cond = X86::COND_O;
12317     break;
12318   case ISD::UADDO:
12319     BaseOp = X86ISD::ADD;
12320     Cond = X86::COND_B;
12321     break;
12322   case ISD::SSUBO:
12323     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12324     // set CF, so we can't do this for USUBO.
12325     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12326       if (C->isOne()) {
12327         BaseOp = X86ISD::DEC;
12328         Cond = X86::COND_O;
12329         break;
12330       }
12331     BaseOp = X86ISD::SUB;
12332     Cond = X86::COND_O;
12333     break;
12334   case ISD::USUBO:
12335     BaseOp = X86ISD::SUB;
12336     Cond = X86::COND_B;
12337     break;
12338   case ISD::SMULO:
12339     BaseOp = X86ISD::SMUL;
12340     Cond = X86::COND_O;
12341     break;
12342   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12343     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12344                                  MVT::i32);
12345     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12346
12347     SDValue SetCC =
12348       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12349                   DAG.getConstant(X86::COND_O, MVT::i32),
12350                   SDValue(Sum.getNode(), 2));
12351
12352     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12353   }
12354   }
12355
12356   // Also sets EFLAGS.
12357   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12358   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12359
12360   SDValue SetCC =
12361     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12362                 DAG.getConstant(Cond, MVT::i32),
12363                 SDValue(Sum.getNode(), 1));
12364
12365   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12366 }
12367
12368 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12369                                                   SelectionDAG &DAG) const {
12370   SDLoc dl(Op);
12371   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12372   EVT VT = Op.getValueType();
12373
12374   if (!Subtarget->hasSSE2() || !VT.isVector())
12375     return SDValue();
12376
12377   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12378                       ExtraVT.getScalarType().getSizeInBits();
12379   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12380
12381   switch (VT.getSimpleVT().SimpleTy) {
12382     default: return SDValue();
12383     case MVT::v8i32:
12384     case MVT::v16i16:
12385       if (!Subtarget->hasFp256())
12386         return SDValue();
12387       if (!Subtarget->hasInt256()) {
12388         // needs to be split
12389         unsigned NumElems = VT.getVectorNumElements();
12390
12391         // Extract the LHS vectors
12392         SDValue LHS = Op.getOperand(0);
12393         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12394         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12395
12396         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12397         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12398
12399         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12400         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12401         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12402                                    ExtraNumElems/2);
12403         SDValue Extra = DAG.getValueType(ExtraVT);
12404
12405         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12406         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12407
12408         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12409       }
12410       // fall through
12411     case MVT::v4i32:
12412     case MVT::v8i16: {
12413       // (sext (vzext x)) -> (vsext x)
12414       SDValue Op0 = Op.getOperand(0);
12415       SDValue Op00 = Op0.getOperand(0);
12416       SDValue Tmp1;
12417       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12418       if (Op0.getOpcode() == ISD::BITCAST &&
12419           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12420         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12421       if (Tmp1.getNode()) {
12422         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12423         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12424                "This optimization is invalid without a VZEXT.");
12425         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12426       }
12427
12428       // If the above didn't work, then just use Shift-Left + Shift-Right.
12429       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12430       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12431     }
12432   }
12433 }
12434
12435 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12436                                  SelectionDAG &DAG) {
12437   SDLoc dl(Op);
12438   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12439     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12440   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12441     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12442
12443   // The only fence that needs an instruction is a sequentially-consistent
12444   // cross-thread fence.
12445   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12446     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12447     // no-sse2). There isn't any reason to disable it if the target processor
12448     // supports it.
12449     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12450       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12451
12452     SDValue Chain = Op.getOperand(0);
12453     SDValue Zero = DAG.getConstant(0, MVT::i32);
12454     SDValue Ops[] = {
12455       DAG.getRegister(X86::ESP, MVT::i32), // Base
12456       DAG.getTargetConstant(1, MVT::i8),   // Scale
12457       DAG.getRegister(0, MVT::i32),        // Index
12458       DAG.getTargetConstant(0, MVT::i32),  // Disp
12459       DAG.getRegister(0, MVT::i32),        // Segment.
12460       Zero,
12461       Chain
12462     };
12463     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12464     return SDValue(Res, 0);
12465   }
12466
12467   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12468   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12469 }
12470
12471 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12472                              SelectionDAG &DAG) {
12473   EVT T = Op.getValueType();
12474   SDLoc DL(Op);
12475   unsigned Reg = 0;
12476   unsigned size = 0;
12477   switch(T.getSimpleVT().SimpleTy) {
12478   default: llvm_unreachable("Invalid value type!");
12479   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12480   case MVT::i16: Reg = X86::AX;  size = 2; break;
12481   case MVT::i32: Reg = X86::EAX; size = 4; break;
12482   case MVT::i64:
12483     assert(Subtarget->is64Bit() && "Node not type legal!");
12484     Reg = X86::RAX; size = 8;
12485     break;
12486   }
12487   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12488                                     Op.getOperand(2), SDValue());
12489   SDValue Ops[] = { cpIn.getValue(0),
12490                     Op.getOperand(1),
12491                     Op.getOperand(3),
12492                     DAG.getTargetConstant(size, MVT::i8),
12493                     cpIn.getValue(1) };
12494   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12495   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12496   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12497                                            Ops, array_lengthof(Ops), T, MMO);
12498   SDValue cpOut =
12499     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12500   return cpOut;
12501 }
12502
12503 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12504                                      SelectionDAG &DAG) {
12505   assert(Subtarget->is64Bit() && "Result not type legalized?");
12506   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12507   SDValue TheChain = Op.getOperand(0);
12508   SDLoc dl(Op);
12509   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12510   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12511   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12512                                    rax.getValue(2));
12513   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12514                             DAG.getConstant(32, MVT::i8));
12515   SDValue Ops[] = {
12516     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12517     rdx.getValue(1)
12518   };
12519   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12520 }
12521
12522 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12523   EVT SrcVT = Op.getOperand(0).getValueType();
12524   EVT DstVT = Op.getValueType();
12525   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12526          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12527   assert((DstVT == MVT::i64 ||
12528           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12529          "Unexpected custom BITCAST");
12530   // i64 <=> MMX conversions are Legal.
12531   if (SrcVT==MVT::i64 && DstVT.isVector())
12532     return Op;
12533   if (DstVT==MVT::i64 && SrcVT.isVector())
12534     return Op;
12535   // MMX <=> MMX conversions are Legal.
12536   if (SrcVT.isVector() && DstVT.isVector())
12537     return Op;
12538   // All other conversions need to be expanded.
12539   return SDValue();
12540 }
12541
12542 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12543   SDNode *Node = Op.getNode();
12544   SDLoc dl(Node);
12545   EVT T = Node->getValueType(0);
12546   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12547                               DAG.getConstant(0, T), Node->getOperand(2));
12548   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12549                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12550                        Node->getOperand(0),
12551                        Node->getOperand(1), negOp,
12552                        cast<AtomicSDNode>(Node)->getSrcValue(),
12553                        cast<AtomicSDNode>(Node)->getAlignment(),
12554                        cast<AtomicSDNode>(Node)->getOrdering(),
12555                        cast<AtomicSDNode>(Node)->getSynchScope());
12556 }
12557
12558 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12559   SDNode *Node = Op.getNode();
12560   SDLoc dl(Node);
12561   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12562
12563   // Convert seq_cst store -> xchg
12564   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12565   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12566   //        (The only way to get a 16-byte store is cmpxchg16b)
12567   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12568   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12569       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12570     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12571                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12572                                  Node->getOperand(0),
12573                                  Node->getOperand(1), Node->getOperand(2),
12574                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12575                                  cast<AtomicSDNode>(Node)->getOrdering(),
12576                                  cast<AtomicSDNode>(Node)->getSynchScope());
12577     return Swap.getValue(1);
12578   }
12579   // Other atomic stores have a simple pattern.
12580   return Op;
12581 }
12582
12583 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12584   EVT VT = Op.getNode()->getValueType(0);
12585
12586   // Let legalize expand this if it isn't a legal type yet.
12587   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12588     return SDValue();
12589
12590   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12591
12592   unsigned Opc;
12593   bool ExtraOp = false;
12594   switch (Op.getOpcode()) {
12595   default: llvm_unreachable("Invalid code");
12596   case ISD::ADDC: Opc = X86ISD::ADD; break;
12597   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12598   case ISD::SUBC: Opc = X86ISD::SUB; break;
12599   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12600   }
12601
12602   if (!ExtraOp)
12603     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12604                        Op.getOperand(1));
12605   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12606                      Op.getOperand(1), Op.getOperand(2));
12607 }
12608
12609 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12610   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12611
12612   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12613   // which returns the values as { float, float } (in XMM0) or
12614   // { double, double } (which is returned in XMM0, XMM1).
12615   SDLoc dl(Op);
12616   SDValue Arg = Op.getOperand(0);
12617   EVT ArgVT = Arg.getValueType();
12618   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12619
12620   ArgListTy Args;
12621   ArgListEntry Entry;
12622
12623   Entry.Node = Arg;
12624   Entry.Ty = ArgTy;
12625   Entry.isSExt = false;
12626   Entry.isZExt = false;
12627   Args.push_back(Entry);
12628
12629   bool isF64 = ArgVT == MVT::f64;
12630   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12631   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12632   // the results are returned via SRet in memory.
12633   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12634   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12635
12636   Type *RetTy = isF64
12637     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12638     : (Type*)VectorType::get(ArgTy, 4);
12639   TargetLowering::
12640     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12641                          false, false, false, false, 0,
12642                          CallingConv::C, /*isTaillCall=*/false,
12643                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12644                          Callee, Args, DAG, dl);
12645   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12646
12647   if (isF64)
12648     // Returned in xmm0 and xmm1.
12649     return CallResult.first;
12650
12651   // Returned in bits 0:31 and 32:64 xmm0.
12652   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12653                                CallResult.first, DAG.getIntPtrConstant(0));
12654   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12655                                CallResult.first, DAG.getIntPtrConstant(1));
12656   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12657   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12658 }
12659
12660 /// LowerOperation - Provide custom lowering hooks for some operations.
12661 ///
12662 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12663   switch (Op.getOpcode()) {
12664   default: llvm_unreachable("Should not custom lower this!");
12665   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12666   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12667   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12668   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12669   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12670   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12671   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12672   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12673   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12674   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12675   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12676   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12677   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12678   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12679   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12680   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12681   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12682   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12683   case ISD::SHL_PARTS:
12684   case ISD::SRA_PARTS:
12685   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12686   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12687   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12688   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12689   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12690   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12691   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12692   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12693   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12694   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12695   case ISD::FABS:               return LowerFABS(Op, DAG);
12696   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12697   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12698   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12699   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12700   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12701   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12702   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12703   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12704   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12705   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12706   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12707   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12708   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12709   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12710   case ISD::FRAME_TO_ARGS_OFFSET:
12711                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12712   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12713   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12714   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12715   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12716   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12717   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12718   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12719   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12720   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12721   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12722   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12723   case ISD::SRA:
12724   case ISD::SRL:
12725   case ISD::SHL:                return LowerShift(Op, DAG);
12726   case ISD::SADDO:
12727   case ISD::UADDO:
12728   case ISD::SSUBO:
12729   case ISD::USUBO:
12730   case ISD::SMULO:
12731   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12732   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12733   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12734   case ISD::ADDC:
12735   case ISD::ADDE:
12736   case ISD::SUBC:
12737   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12738   case ISD::ADD:                return LowerADD(Op, DAG);
12739   case ISD::SUB:                return LowerSUB(Op, DAG);
12740   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12741   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12742   }
12743 }
12744
12745 static void ReplaceATOMIC_LOAD(SDNode *Node,
12746                                   SmallVectorImpl<SDValue> &Results,
12747                                   SelectionDAG &DAG) {
12748   SDLoc dl(Node);
12749   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12750
12751   // Convert wide load -> cmpxchg8b/cmpxchg16b
12752   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12753   //        (The only way to get a 16-byte load is cmpxchg16b)
12754   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12755   SDValue Zero = DAG.getConstant(0, VT);
12756   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12757                                Node->getOperand(0),
12758                                Node->getOperand(1), Zero, Zero,
12759                                cast<AtomicSDNode>(Node)->getMemOperand(),
12760                                cast<AtomicSDNode>(Node)->getOrdering(),
12761                                cast<AtomicSDNode>(Node)->getSynchScope());
12762   Results.push_back(Swap.getValue(0));
12763   Results.push_back(Swap.getValue(1));
12764 }
12765
12766 static void
12767 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12768                         SelectionDAG &DAG, unsigned NewOp) {
12769   SDLoc dl(Node);
12770   assert (Node->getValueType(0) == MVT::i64 &&
12771           "Only know how to expand i64 atomics");
12772
12773   SDValue Chain = Node->getOperand(0);
12774   SDValue In1 = Node->getOperand(1);
12775   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12776                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12777   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12778                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12779   SDValue Ops[] = { Chain, In1, In2L, In2H };
12780   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12781   SDValue Result =
12782     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12783                             cast<MemSDNode>(Node)->getMemOperand());
12784   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12785   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12786   Results.push_back(Result.getValue(2));
12787 }
12788
12789 /// ReplaceNodeResults - Replace a node with an illegal result type
12790 /// with a new node built out of custom code.
12791 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12792                                            SmallVectorImpl<SDValue>&Results,
12793                                            SelectionDAG &DAG) const {
12794   SDLoc dl(N);
12795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12796   switch (N->getOpcode()) {
12797   default:
12798     llvm_unreachable("Do not know how to custom type legalize this operation!");
12799   case ISD::SIGN_EXTEND_INREG:
12800   case ISD::ADDC:
12801   case ISD::ADDE:
12802   case ISD::SUBC:
12803   case ISD::SUBE:
12804     // We don't want to expand or promote these.
12805     return;
12806   case ISD::FP_TO_SINT:
12807   case ISD::FP_TO_UINT: {
12808     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12809
12810     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12811       return;
12812
12813     std::pair<SDValue,SDValue> Vals =
12814         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12815     SDValue FIST = Vals.first, StackSlot = Vals.second;
12816     if (FIST.getNode() != 0) {
12817       EVT VT = N->getValueType(0);
12818       // Return a load from the stack slot.
12819       if (StackSlot.getNode() != 0)
12820         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12821                                       MachinePointerInfo(),
12822                                       false, false, false, 0));
12823       else
12824         Results.push_back(FIST);
12825     }
12826     return;
12827   }
12828   case ISD::UINT_TO_FP: {
12829     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12830     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12831         N->getValueType(0) != MVT::v2f32)
12832       return;
12833     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12834                                  N->getOperand(0));
12835     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12836                                      MVT::f64);
12837     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12838     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12839                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12840     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12841     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12842     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12843     return;
12844   }
12845   case ISD::FP_ROUND: {
12846     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12847         return;
12848     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12849     Results.push_back(V);
12850     return;
12851   }
12852   case ISD::READCYCLECOUNTER: {
12853     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12854     SDValue TheChain = N->getOperand(0);
12855     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12856     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12857                                      rd.getValue(1));
12858     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12859                                      eax.getValue(2));
12860     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12861     SDValue Ops[] = { eax, edx };
12862     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12863                                   array_lengthof(Ops)));
12864     Results.push_back(edx.getValue(1));
12865     return;
12866   }
12867   case ISD::ATOMIC_CMP_SWAP: {
12868     EVT T = N->getValueType(0);
12869     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12870     bool Regs64bit = T == MVT::i128;
12871     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12872     SDValue cpInL, cpInH;
12873     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12874                         DAG.getConstant(0, HalfT));
12875     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12876                         DAG.getConstant(1, HalfT));
12877     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12878                              Regs64bit ? X86::RAX : X86::EAX,
12879                              cpInL, SDValue());
12880     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12881                              Regs64bit ? X86::RDX : X86::EDX,
12882                              cpInH, cpInL.getValue(1));
12883     SDValue swapInL, swapInH;
12884     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12885                           DAG.getConstant(0, HalfT));
12886     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12887                           DAG.getConstant(1, HalfT));
12888     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12889                                Regs64bit ? X86::RBX : X86::EBX,
12890                                swapInL, cpInH.getValue(1));
12891     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12892                                Regs64bit ? X86::RCX : X86::ECX,
12893                                swapInH, swapInL.getValue(1));
12894     SDValue Ops[] = { swapInH.getValue(0),
12895                       N->getOperand(1),
12896                       swapInH.getValue(1) };
12897     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12898     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12899     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12900                                   X86ISD::LCMPXCHG8_DAG;
12901     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12902                                              Ops, array_lengthof(Ops), T, MMO);
12903     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12904                                         Regs64bit ? X86::RAX : X86::EAX,
12905                                         HalfT, Result.getValue(1));
12906     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12907                                         Regs64bit ? X86::RDX : X86::EDX,
12908                                         HalfT, cpOutL.getValue(2));
12909     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12910     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12911     Results.push_back(cpOutH.getValue(1));
12912     return;
12913   }
12914   case ISD::ATOMIC_LOAD_ADD:
12915   case ISD::ATOMIC_LOAD_AND:
12916   case ISD::ATOMIC_LOAD_NAND:
12917   case ISD::ATOMIC_LOAD_OR:
12918   case ISD::ATOMIC_LOAD_SUB:
12919   case ISD::ATOMIC_LOAD_XOR:
12920   case ISD::ATOMIC_LOAD_MAX:
12921   case ISD::ATOMIC_LOAD_MIN:
12922   case ISD::ATOMIC_LOAD_UMAX:
12923   case ISD::ATOMIC_LOAD_UMIN:
12924   case ISD::ATOMIC_SWAP: {
12925     unsigned Opc;
12926     switch (N->getOpcode()) {
12927     default: llvm_unreachable("Unexpected opcode");
12928     case ISD::ATOMIC_LOAD_ADD:
12929       Opc = X86ISD::ATOMADD64_DAG;
12930       break;
12931     case ISD::ATOMIC_LOAD_AND:
12932       Opc = X86ISD::ATOMAND64_DAG;
12933       break;
12934     case ISD::ATOMIC_LOAD_NAND:
12935       Opc = X86ISD::ATOMNAND64_DAG;
12936       break;
12937     case ISD::ATOMIC_LOAD_OR:
12938       Opc = X86ISD::ATOMOR64_DAG;
12939       break;
12940     case ISD::ATOMIC_LOAD_SUB:
12941       Opc = X86ISD::ATOMSUB64_DAG;
12942       break;
12943     case ISD::ATOMIC_LOAD_XOR:
12944       Opc = X86ISD::ATOMXOR64_DAG;
12945       break;
12946     case ISD::ATOMIC_LOAD_MAX:
12947       Opc = X86ISD::ATOMMAX64_DAG;
12948       break;
12949     case ISD::ATOMIC_LOAD_MIN:
12950       Opc = X86ISD::ATOMMIN64_DAG;
12951       break;
12952     case ISD::ATOMIC_LOAD_UMAX:
12953       Opc = X86ISD::ATOMUMAX64_DAG;
12954       break;
12955     case ISD::ATOMIC_LOAD_UMIN:
12956       Opc = X86ISD::ATOMUMIN64_DAG;
12957       break;
12958     case ISD::ATOMIC_SWAP:
12959       Opc = X86ISD::ATOMSWAP64_DAG;
12960       break;
12961     }
12962     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12963     return;
12964   }
12965   case ISD::ATOMIC_LOAD:
12966     ReplaceATOMIC_LOAD(N, Results, DAG);
12967   }
12968 }
12969
12970 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12971   switch (Opcode) {
12972   default: return NULL;
12973   case X86ISD::BSF:                return "X86ISD::BSF";
12974   case X86ISD::BSR:                return "X86ISD::BSR";
12975   case X86ISD::SHLD:               return "X86ISD::SHLD";
12976   case X86ISD::SHRD:               return "X86ISD::SHRD";
12977   case X86ISD::FAND:               return "X86ISD::FAND";
12978   case X86ISD::FOR:                return "X86ISD::FOR";
12979   case X86ISD::FXOR:               return "X86ISD::FXOR";
12980   case X86ISD::FSRL:               return "X86ISD::FSRL";
12981   case X86ISD::FILD:               return "X86ISD::FILD";
12982   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12983   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12984   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12985   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12986   case X86ISD::FLD:                return "X86ISD::FLD";
12987   case X86ISD::FST:                return "X86ISD::FST";
12988   case X86ISD::CALL:               return "X86ISD::CALL";
12989   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12990   case X86ISD::BT:                 return "X86ISD::BT";
12991   case X86ISD::CMP:                return "X86ISD::CMP";
12992   case X86ISD::COMI:               return "X86ISD::COMI";
12993   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12994   case X86ISD::SETCC:              return "X86ISD::SETCC";
12995   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12996   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12997   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12998   case X86ISD::CMOV:               return "X86ISD::CMOV";
12999   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13000   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13001   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13002   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13003   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13004   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13005   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13006   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13007   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13008   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13009   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13010   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13011   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13012   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13013   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13014   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13015   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13016   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13017   case X86ISD::HADD:               return "X86ISD::HADD";
13018   case X86ISD::HSUB:               return "X86ISD::HSUB";
13019   case X86ISD::FHADD:              return "X86ISD::FHADD";
13020   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13021   case X86ISD::UMAX:               return "X86ISD::UMAX";
13022   case X86ISD::UMIN:               return "X86ISD::UMIN";
13023   case X86ISD::SMAX:               return "X86ISD::SMAX";
13024   case X86ISD::SMIN:               return "X86ISD::SMIN";
13025   case X86ISD::FMAX:               return "X86ISD::FMAX";
13026   case X86ISD::FMIN:               return "X86ISD::FMIN";
13027   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13028   case X86ISD::FMINC:              return "X86ISD::FMINC";
13029   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13030   case X86ISD::FRCP:               return "X86ISD::FRCP";
13031   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13032   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13033   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13034   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13035   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13036   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13037   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13038   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13039   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13040   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13041   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13042   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13043   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13044   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13045   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13046   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13047   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13048   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13049   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13050   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13051   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13052   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13053   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13054   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13055   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13056   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13057   case X86ISD::VSHL:               return "X86ISD::VSHL";
13058   case X86ISD::VSRL:               return "X86ISD::VSRL";
13059   case X86ISD::VSRA:               return "X86ISD::VSRA";
13060   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13061   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13062   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13063   case X86ISD::CMPP:               return "X86ISD::CMPP";
13064   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13065   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13066   case X86ISD::ADD:                return "X86ISD::ADD";
13067   case X86ISD::SUB:                return "X86ISD::SUB";
13068   case X86ISD::ADC:                return "X86ISD::ADC";
13069   case X86ISD::SBB:                return "X86ISD::SBB";
13070   case X86ISD::SMUL:               return "X86ISD::SMUL";
13071   case X86ISD::UMUL:               return "X86ISD::UMUL";
13072   case X86ISD::INC:                return "X86ISD::INC";
13073   case X86ISD::DEC:                return "X86ISD::DEC";
13074   case X86ISD::OR:                 return "X86ISD::OR";
13075   case X86ISD::XOR:                return "X86ISD::XOR";
13076   case X86ISD::AND:                return "X86ISD::AND";
13077   case X86ISD::BLSI:               return "X86ISD::BLSI";
13078   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13079   case X86ISD::BLSR:               return "X86ISD::BLSR";
13080   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13081   case X86ISD::PTEST:              return "X86ISD::PTEST";
13082   case X86ISD::TESTP:              return "X86ISD::TESTP";
13083   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13084   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13085   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13086   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13087   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13088   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13089   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13090   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13091   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13092   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13093   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13094   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13095   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13096   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13097   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13098   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13099   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13100   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13101   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13102   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13103   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13104   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13105   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13106   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13107   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13108   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13109   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13110   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13111   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13112   case X86ISD::SAHF:               return "X86ISD::SAHF";
13113   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13114   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13115   case X86ISD::FMADD:              return "X86ISD::FMADD";
13116   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13117   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13118   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13119   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13120   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13121   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13122   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13123   case X86ISD::XTEST:              return "X86ISD::XTEST";
13124   }
13125 }
13126
13127 // isLegalAddressingMode - Return true if the addressing mode represented
13128 // by AM is legal for this target, for a load/store of the specified type.
13129 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13130                                               Type *Ty) const {
13131   // X86 supports extremely general addressing modes.
13132   CodeModel::Model M = getTargetMachine().getCodeModel();
13133   Reloc::Model R = getTargetMachine().getRelocationModel();
13134
13135   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13136   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13137     return false;
13138
13139   if (AM.BaseGV) {
13140     unsigned GVFlags =
13141       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13142
13143     // If a reference to this global requires an extra load, we can't fold it.
13144     if (isGlobalStubReference(GVFlags))
13145       return false;
13146
13147     // If BaseGV requires a register for the PIC base, we cannot also have a
13148     // BaseReg specified.
13149     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13150       return false;
13151
13152     // If lower 4G is not available, then we must use rip-relative addressing.
13153     if ((M != CodeModel::Small || R != Reloc::Static) &&
13154         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13155       return false;
13156   }
13157
13158   switch (AM.Scale) {
13159   case 0:
13160   case 1:
13161   case 2:
13162   case 4:
13163   case 8:
13164     // These scales always work.
13165     break;
13166   case 3:
13167   case 5:
13168   case 9:
13169     // These scales are formed with basereg+scalereg.  Only accept if there is
13170     // no basereg yet.
13171     if (AM.HasBaseReg)
13172       return false;
13173     break;
13174   default:  // Other stuff never works.
13175     return false;
13176   }
13177
13178   return true;
13179 }
13180
13181 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13182   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13183     return false;
13184   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13185   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13186   return NumBits1 > NumBits2;
13187 }
13188
13189 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13190   return isInt<32>(Imm);
13191 }
13192
13193 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13194   // Can also use sub to handle negated immediates.
13195   return isInt<32>(Imm);
13196 }
13197
13198 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13199   if (!VT1.isInteger() || !VT2.isInteger())
13200     return false;
13201   unsigned NumBits1 = VT1.getSizeInBits();
13202   unsigned NumBits2 = VT2.getSizeInBits();
13203   return NumBits1 > NumBits2;
13204 }
13205
13206 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13207   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13208   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13209 }
13210
13211 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13212   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13213   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13214 }
13215
13216 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13217   EVT VT1 = Val.getValueType();
13218   if (isZExtFree(VT1, VT2))
13219     return true;
13220
13221   if (Val.getOpcode() != ISD::LOAD)
13222     return false;
13223
13224   if (!VT1.isSimple() || !VT1.isInteger() ||
13225       !VT2.isSimple() || !VT2.isInteger())
13226     return false;
13227
13228   switch (VT1.getSimpleVT().SimpleTy) {
13229   default: break;
13230   case MVT::i8:
13231   case MVT::i16:
13232   case MVT::i32:
13233     // X86 has 8, 16, and 32-bit zero-extending loads.
13234     return true;
13235   }
13236
13237   return false;
13238 }
13239
13240 bool
13241 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13242   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13243     return false;
13244
13245   VT = VT.getScalarType();
13246
13247   if (!VT.isSimple())
13248     return false;
13249
13250   switch (VT.getSimpleVT().SimpleTy) {
13251   case MVT::f32:
13252   case MVT::f64:
13253     return true;
13254   default:
13255     break;
13256   }
13257
13258   return false;
13259 }
13260
13261 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13262   // i16 instructions are longer (0x66 prefix) and potentially slower.
13263   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13264 }
13265
13266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13269 /// are assumed to be legal.
13270 bool
13271 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13272                                       EVT VT) const {
13273   // Very little shuffling can be done for 64-bit vectors right now.
13274   if (VT.getSizeInBits() == 64)
13275     return false;
13276
13277   // FIXME: pshufb, blends, shifts.
13278   return (VT.getVectorNumElements() == 2 ||
13279           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13280           isMOVLMask(M, VT) ||
13281           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13282           isPSHUFDMask(M, VT) ||
13283           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13284           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13285           isPALIGNRMask(M, VT, Subtarget) ||
13286           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13287           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13288           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13289           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13290 }
13291
13292 bool
13293 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13294                                           EVT VT) const {
13295   unsigned NumElts = VT.getVectorNumElements();
13296   // FIXME: This collection of masks seems suspect.
13297   if (NumElts == 2)
13298     return true;
13299   if (NumElts == 4 && VT.is128BitVector()) {
13300     return (isMOVLMask(Mask, VT)  ||
13301             isCommutedMOVLMask(Mask, VT, true) ||
13302             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13303             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13304   }
13305   return false;
13306 }
13307
13308 //===----------------------------------------------------------------------===//
13309 //                           X86 Scheduler Hooks
13310 //===----------------------------------------------------------------------===//
13311
13312 /// Utility function to emit xbegin specifying the start of an RTM region.
13313 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13314                                      const TargetInstrInfo *TII) {
13315   DebugLoc DL = MI->getDebugLoc();
13316
13317   const BasicBlock *BB = MBB->getBasicBlock();
13318   MachineFunction::iterator I = MBB;
13319   ++I;
13320
13321   // For the v = xbegin(), we generate
13322   //
13323   // thisMBB:
13324   //  xbegin sinkMBB
13325   //
13326   // mainMBB:
13327   //  eax = -1
13328   //
13329   // sinkMBB:
13330   //  v = eax
13331
13332   MachineBasicBlock *thisMBB = MBB;
13333   MachineFunction *MF = MBB->getParent();
13334   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13335   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13336   MF->insert(I, mainMBB);
13337   MF->insert(I, sinkMBB);
13338
13339   // Transfer the remainder of BB and its successor edges to sinkMBB.
13340   sinkMBB->splice(sinkMBB->begin(), MBB,
13341                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13342   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13343
13344   // thisMBB:
13345   //  xbegin sinkMBB
13346   //  # fallthrough to mainMBB
13347   //  # abortion to sinkMBB
13348   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13349   thisMBB->addSuccessor(mainMBB);
13350   thisMBB->addSuccessor(sinkMBB);
13351
13352   // mainMBB:
13353   //  EAX = -1
13354   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13355   mainMBB->addSuccessor(sinkMBB);
13356
13357   // sinkMBB:
13358   // EAX is live into the sinkMBB
13359   sinkMBB->addLiveIn(X86::EAX);
13360   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13361           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13362     .addReg(X86::EAX);
13363
13364   MI->eraseFromParent();
13365   return sinkMBB;
13366 }
13367
13368 // Get CMPXCHG opcode for the specified data type.
13369 static unsigned getCmpXChgOpcode(EVT VT) {
13370   switch (VT.getSimpleVT().SimpleTy) {
13371   case MVT::i8:  return X86::LCMPXCHG8;
13372   case MVT::i16: return X86::LCMPXCHG16;
13373   case MVT::i32: return X86::LCMPXCHG32;
13374   case MVT::i64: return X86::LCMPXCHG64;
13375   default:
13376     break;
13377   }
13378   llvm_unreachable("Invalid operand size!");
13379 }
13380
13381 // Get LOAD opcode for the specified data type.
13382 static unsigned getLoadOpcode(EVT VT) {
13383   switch (VT.getSimpleVT().SimpleTy) {
13384   case MVT::i8:  return X86::MOV8rm;
13385   case MVT::i16: return X86::MOV16rm;
13386   case MVT::i32: return X86::MOV32rm;
13387   case MVT::i64: return X86::MOV64rm;
13388   default:
13389     break;
13390   }
13391   llvm_unreachable("Invalid operand size!");
13392 }
13393
13394 // Get opcode of the non-atomic one from the specified atomic instruction.
13395 static unsigned getNonAtomicOpcode(unsigned Opc) {
13396   switch (Opc) {
13397   case X86::ATOMAND8:  return X86::AND8rr;
13398   case X86::ATOMAND16: return X86::AND16rr;
13399   case X86::ATOMAND32: return X86::AND32rr;
13400   case X86::ATOMAND64: return X86::AND64rr;
13401   case X86::ATOMOR8:   return X86::OR8rr;
13402   case X86::ATOMOR16:  return X86::OR16rr;
13403   case X86::ATOMOR32:  return X86::OR32rr;
13404   case X86::ATOMOR64:  return X86::OR64rr;
13405   case X86::ATOMXOR8:  return X86::XOR8rr;
13406   case X86::ATOMXOR16: return X86::XOR16rr;
13407   case X86::ATOMXOR32: return X86::XOR32rr;
13408   case X86::ATOMXOR64: return X86::XOR64rr;
13409   }
13410   llvm_unreachable("Unhandled atomic-load-op opcode!");
13411 }
13412
13413 // Get opcode of the non-atomic one from the specified atomic instruction with
13414 // extra opcode.
13415 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13416                                                unsigned &ExtraOpc) {
13417   switch (Opc) {
13418   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13419   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13420   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13421   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13422   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13423   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13424   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13425   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13426   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13427   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13428   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13429   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13430   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13431   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13432   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13433   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13434   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13435   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13436   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13437   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13438   }
13439   llvm_unreachable("Unhandled atomic-load-op opcode!");
13440 }
13441
13442 // Get opcode of the non-atomic one from the specified atomic instruction for
13443 // 64-bit data type on 32-bit target.
13444 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13445   switch (Opc) {
13446   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13447   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13448   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13449   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13450   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13451   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13452   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13453   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13454   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13455   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13456   }
13457   llvm_unreachable("Unhandled atomic-load-op opcode!");
13458 }
13459
13460 // Get opcode of the non-atomic one from the specified atomic instruction for
13461 // 64-bit data type on 32-bit target with extra opcode.
13462 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13463                                                    unsigned &HiOpc,
13464                                                    unsigned &ExtraOpc) {
13465   switch (Opc) {
13466   case X86::ATOMNAND6432:
13467     ExtraOpc = X86::NOT32r;
13468     HiOpc = X86::AND32rr;
13469     return X86::AND32rr;
13470   }
13471   llvm_unreachable("Unhandled atomic-load-op opcode!");
13472 }
13473
13474 // Get pseudo CMOV opcode from the specified data type.
13475 static unsigned getPseudoCMOVOpc(EVT VT) {
13476   switch (VT.getSimpleVT().SimpleTy) {
13477   case MVT::i8:  return X86::CMOV_GR8;
13478   case MVT::i16: return X86::CMOV_GR16;
13479   case MVT::i32: return X86::CMOV_GR32;
13480   default:
13481     break;
13482   }
13483   llvm_unreachable("Unknown CMOV opcode!");
13484 }
13485
13486 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13487 // They will be translated into a spin-loop or compare-exchange loop from
13488 //
13489 //    ...
13490 //    dst = atomic-fetch-op MI.addr, MI.val
13491 //    ...
13492 //
13493 // to
13494 //
13495 //    ...
13496 //    t1 = LOAD MI.addr
13497 // loop:
13498 //    t4 = phi(t1, t3 / loop)
13499 //    t2 = OP MI.val, t4
13500 //    EAX = t4
13501 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13502 //    t3 = EAX
13503 //    JNE loop
13504 // sink:
13505 //    dst = t3
13506 //    ...
13507 MachineBasicBlock *
13508 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13509                                        MachineBasicBlock *MBB) const {
13510   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13511   DebugLoc DL = MI->getDebugLoc();
13512
13513   MachineFunction *MF = MBB->getParent();
13514   MachineRegisterInfo &MRI = MF->getRegInfo();
13515
13516   const BasicBlock *BB = MBB->getBasicBlock();
13517   MachineFunction::iterator I = MBB;
13518   ++I;
13519
13520   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13521          "Unexpected number of operands");
13522
13523   assert(MI->hasOneMemOperand() &&
13524          "Expected atomic-load-op to have one memoperand");
13525
13526   // Memory Reference
13527   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13528   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13529
13530   unsigned DstReg, SrcReg;
13531   unsigned MemOpndSlot;
13532
13533   unsigned CurOp = 0;
13534
13535   DstReg = MI->getOperand(CurOp++).getReg();
13536   MemOpndSlot = CurOp;
13537   CurOp += X86::AddrNumOperands;
13538   SrcReg = MI->getOperand(CurOp++).getReg();
13539
13540   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13541   MVT::SimpleValueType VT = *RC->vt_begin();
13542   unsigned t1 = MRI.createVirtualRegister(RC);
13543   unsigned t2 = MRI.createVirtualRegister(RC);
13544   unsigned t3 = MRI.createVirtualRegister(RC);
13545   unsigned t4 = MRI.createVirtualRegister(RC);
13546   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13547
13548   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13549   unsigned LOADOpc = getLoadOpcode(VT);
13550
13551   // For the atomic load-arith operator, we generate
13552   //
13553   //  thisMBB:
13554   //    t1 = LOAD [MI.addr]
13555   //  mainMBB:
13556   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13557   //    t1 = OP MI.val, EAX
13558   //    EAX = t4
13559   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13560   //    t3 = EAX
13561   //    JNE mainMBB
13562   //  sinkMBB:
13563   //    dst = t3
13564
13565   MachineBasicBlock *thisMBB = MBB;
13566   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13567   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13568   MF->insert(I, mainMBB);
13569   MF->insert(I, sinkMBB);
13570
13571   MachineInstrBuilder MIB;
13572
13573   // Transfer the remainder of BB and its successor edges to sinkMBB.
13574   sinkMBB->splice(sinkMBB->begin(), MBB,
13575                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13576   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13577
13578   // thisMBB:
13579   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13580   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13581     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13582     if (NewMO.isReg())
13583       NewMO.setIsKill(false);
13584     MIB.addOperand(NewMO);
13585   }
13586   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13587     unsigned flags = (*MMOI)->getFlags();
13588     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13589     MachineMemOperand *MMO =
13590       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13591                                (*MMOI)->getSize(),
13592                                (*MMOI)->getBaseAlignment(),
13593                                (*MMOI)->getTBAAInfo(),
13594                                (*MMOI)->getRanges());
13595     MIB.addMemOperand(MMO);
13596   }
13597
13598   thisMBB->addSuccessor(mainMBB);
13599
13600   // mainMBB:
13601   MachineBasicBlock *origMainMBB = mainMBB;
13602
13603   // Add a PHI.
13604   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13605                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13606
13607   unsigned Opc = MI->getOpcode();
13608   switch (Opc) {
13609   default:
13610     llvm_unreachable("Unhandled atomic-load-op opcode!");
13611   case X86::ATOMAND8:
13612   case X86::ATOMAND16:
13613   case X86::ATOMAND32:
13614   case X86::ATOMAND64:
13615   case X86::ATOMOR8:
13616   case X86::ATOMOR16:
13617   case X86::ATOMOR32:
13618   case X86::ATOMOR64:
13619   case X86::ATOMXOR8:
13620   case X86::ATOMXOR16:
13621   case X86::ATOMXOR32:
13622   case X86::ATOMXOR64: {
13623     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13624     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13625       .addReg(t4);
13626     break;
13627   }
13628   case X86::ATOMNAND8:
13629   case X86::ATOMNAND16:
13630   case X86::ATOMNAND32:
13631   case X86::ATOMNAND64: {
13632     unsigned Tmp = MRI.createVirtualRegister(RC);
13633     unsigned NOTOpc;
13634     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13635     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13636       .addReg(t4);
13637     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13638     break;
13639   }
13640   case X86::ATOMMAX8:
13641   case X86::ATOMMAX16:
13642   case X86::ATOMMAX32:
13643   case X86::ATOMMAX64:
13644   case X86::ATOMMIN8:
13645   case X86::ATOMMIN16:
13646   case X86::ATOMMIN32:
13647   case X86::ATOMMIN64:
13648   case X86::ATOMUMAX8:
13649   case X86::ATOMUMAX16:
13650   case X86::ATOMUMAX32:
13651   case X86::ATOMUMAX64:
13652   case X86::ATOMUMIN8:
13653   case X86::ATOMUMIN16:
13654   case X86::ATOMUMIN32:
13655   case X86::ATOMUMIN64: {
13656     unsigned CMPOpc;
13657     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13658
13659     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13660       .addReg(SrcReg)
13661       .addReg(t4);
13662
13663     if (Subtarget->hasCMov()) {
13664       if (VT != MVT::i8) {
13665         // Native support
13666         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13667           .addReg(SrcReg)
13668           .addReg(t4);
13669       } else {
13670         // Promote i8 to i32 to use CMOV32
13671         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13672         const TargetRegisterClass *RC32 =
13673           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13674         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13675         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13676         unsigned Tmp = MRI.createVirtualRegister(RC32);
13677
13678         unsigned Undef = MRI.createVirtualRegister(RC32);
13679         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13680
13681         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13682           .addReg(Undef)
13683           .addReg(SrcReg)
13684           .addImm(X86::sub_8bit);
13685         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13686           .addReg(Undef)
13687           .addReg(t4)
13688           .addImm(X86::sub_8bit);
13689
13690         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13691           .addReg(SrcReg32)
13692           .addReg(AccReg32);
13693
13694         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13695           .addReg(Tmp, 0, X86::sub_8bit);
13696       }
13697     } else {
13698       // Use pseudo select and lower them.
13699       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13700              "Invalid atomic-load-op transformation!");
13701       unsigned SelOpc = getPseudoCMOVOpc(VT);
13702       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13703       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13704       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13705               .addReg(SrcReg).addReg(t4)
13706               .addImm(CC);
13707       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13708       // Replace the original PHI node as mainMBB is changed after CMOV
13709       // lowering.
13710       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13711         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13712       Phi->eraseFromParent();
13713     }
13714     break;
13715   }
13716   }
13717
13718   // Copy PhyReg back from virtual register.
13719   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13720     .addReg(t4);
13721
13722   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13723   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13724     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13725     if (NewMO.isReg())
13726       NewMO.setIsKill(false);
13727     MIB.addOperand(NewMO);
13728   }
13729   MIB.addReg(t2);
13730   MIB.setMemRefs(MMOBegin, MMOEnd);
13731
13732   // Copy PhyReg back to virtual register.
13733   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13734     .addReg(PhyReg);
13735
13736   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13737
13738   mainMBB->addSuccessor(origMainMBB);
13739   mainMBB->addSuccessor(sinkMBB);
13740
13741   // sinkMBB:
13742   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13743           TII->get(TargetOpcode::COPY), DstReg)
13744     .addReg(t3);
13745
13746   MI->eraseFromParent();
13747   return sinkMBB;
13748 }
13749
13750 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13751 // instructions. They will be translated into a spin-loop or compare-exchange
13752 // loop from
13753 //
13754 //    ...
13755 //    dst = atomic-fetch-op MI.addr, MI.val
13756 //    ...
13757 //
13758 // to
13759 //
13760 //    ...
13761 //    t1L = LOAD [MI.addr + 0]
13762 //    t1H = LOAD [MI.addr + 4]
13763 // loop:
13764 //    t4L = phi(t1L, t3L / loop)
13765 //    t4H = phi(t1H, t3H / loop)
13766 //    t2L = OP MI.val.lo, t4L
13767 //    t2H = OP MI.val.hi, t4H
13768 //    EAX = t4L
13769 //    EDX = t4H
13770 //    EBX = t2L
13771 //    ECX = t2H
13772 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13773 //    t3L = EAX
13774 //    t3H = EDX
13775 //    JNE loop
13776 // sink:
13777 //    dstL = t3L
13778 //    dstH = t3H
13779 //    ...
13780 MachineBasicBlock *
13781 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13782                                            MachineBasicBlock *MBB) const {
13783   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13784   DebugLoc DL = MI->getDebugLoc();
13785
13786   MachineFunction *MF = MBB->getParent();
13787   MachineRegisterInfo &MRI = MF->getRegInfo();
13788
13789   const BasicBlock *BB = MBB->getBasicBlock();
13790   MachineFunction::iterator I = MBB;
13791   ++I;
13792
13793   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13794          "Unexpected number of operands");
13795
13796   assert(MI->hasOneMemOperand() &&
13797          "Expected atomic-load-op32 to have one memoperand");
13798
13799   // Memory Reference
13800   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13801   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13802
13803   unsigned DstLoReg, DstHiReg;
13804   unsigned SrcLoReg, SrcHiReg;
13805   unsigned MemOpndSlot;
13806
13807   unsigned CurOp = 0;
13808
13809   DstLoReg = MI->getOperand(CurOp++).getReg();
13810   DstHiReg = MI->getOperand(CurOp++).getReg();
13811   MemOpndSlot = CurOp;
13812   CurOp += X86::AddrNumOperands;
13813   SrcLoReg = MI->getOperand(CurOp++).getReg();
13814   SrcHiReg = MI->getOperand(CurOp++).getReg();
13815
13816   const TargetRegisterClass *RC = &X86::GR32RegClass;
13817   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13818
13819   unsigned t1L = MRI.createVirtualRegister(RC);
13820   unsigned t1H = MRI.createVirtualRegister(RC);
13821   unsigned t2L = MRI.createVirtualRegister(RC);
13822   unsigned t2H = MRI.createVirtualRegister(RC);
13823   unsigned t3L = MRI.createVirtualRegister(RC);
13824   unsigned t3H = MRI.createVirtualRegister(RC);
13825   unsigned t4L = MRI.createVirtualRegister(RC);
13826   unsigned t4H = MRI.createVirtualRegister(RC);
13827
13828   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13829   unsigned LOADOpc = X86::MOV32rm;
13830
13831   // For the atomic load-arith operator, we generate
13832   //
13833   //  thisMBB:
13834   //    t1L = LOAD [MI.addr + 0]
13835   //    t1H = LOAD [MI.addr + 4]
13836   //  mainMBB:
13837   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13838   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13839   //    t2L = OP MI.val.lo, t4L
13840   //    t2H = OP MI.val.hi, t4H
13841   //    EBX = t2L
13842   //    ECX = t2H
13843   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13844   //    t3L = EAX
13845   //    t3H = EDX
13846   //    JNE loop
13847   //  sinkMBB:
13848   //    dstL = t3L
13849   //    dstH = t3H
13850
13851   MachineBasicBlock *thisMBB = MBB;
13852   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13853   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13854   MF->insert(I, mainMBB);
13855   MF->insert(I, sinkMBB);
13856
13857   MachineInstrBuilder MIB;
13858
13859   // Transfer the remainder of BB and its successor edges to sinkMBB.
13860   sinkMBB->splice(sinkMBB->begin(), MBB,
13861                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13862   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13863
13864   // thisMBB:
13865   // Lo
13866   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13867   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13868     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13869     if (NewMO.isReg())
13870       NewMO.setIsKill(false);
13871     MIB.addOperand(NewMO);
13872   }
13873   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13874     unsigned flags = (*MMOI)->getFlags();
13875     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13876     MachineMemOperand *MMO =
13877       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13878                                (*MMOI)->getSize(),
13879                                (*MMOI)->getBaseAlignment(),
13880                                (*MMOI)->getTBAAInfo(),
13881                                (*MMOI)->getRanges());
13882     MIB.addMemOperand(MMO);
13883   };
13884   MachineInstr *LowMI = MIB;
13885
13886   // Hi
13887   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13888   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13889     if (i == X86::AddrDisp) {
13890       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13891     } else {
13892       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13893       if (NewMO.isReg())
13894         NewMO.setIsKill(false);
13895       MIB.addOperand(NewMO);
13896     }
13897   }
13898   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13899
13900   thisMBB->addSuccessor(mainMBB);
13901
13902   // mainMBB:
13903   MachineBasicBlock *origMainMBB = mainMBB;
13904
13905   // Add PHIs.
13906   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13907                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13908   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13909                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13910
13911   unsigned Opc = MI->getOpcode();
13912   switch (Opc) {
13913   default:
13914     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13915   case X86::ATOMAND6432:
13916   case X86::ATOMOR6432:
13917   case X86::ATOMXOR6432:
13918   case X86::ATOMADD6432:
13919   case X86::ATOMSUB6432: {
13920     unsigned HiOpc;
13921     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13922     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13923       .addReg(SrcLoReg);
13924     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13925       .addReg(SrcHiReg);
13926     break;
13927   }
13928   case X86::ATOMNAND6432: {
13929     unsigned HiOpc, NOTOpc;
13930     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13931     unsigned TmpL = MRI.createVirtualRegister(RC);
13932     unsigned TmpH = MRI.createVirtualRegister(RC);
13933     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13934       .addReg(t4L);
13935     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13936       .addReg(t4H);
13937     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13938     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13939     break;
13940   }
13941   case X86::ATOMMAX6432:
13942   case X86::ATOMMIN6432:
13943   case X86::ATOMUMAX6432:
13944   case X86::ATOMUMIN6432: {
13945     unsigned HiOpc;
13946     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13947     unsigned cL = MRI.createVirtualRegister(RC8);
13948     unsigned cH = MRI.createVirtualRegister(RC8);
13949     unsigned cL32 = MRI.createVirtualRegister(RC);
13950     unsigned cH32 = MRI.createVirtualRegister(RC);
13951     unsigned cc = MRI.createVirtualRegister(RC);
13952     // cl := cmp src_lo, lo
13953     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13954       .addReg(SrcLoReg).addReg(t4L);
13955     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13956     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13957     // ch := cmp src_hi, hi
13958     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13959       .addReg(SrcHiReg).addReg(t4H);
13960     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13961     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13962     // cc := if (src_hi == hi) ? cl : ch;
13963     if (Subtarget->hasCMov()) {
13964       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13965         .addReg(cH32).addReg(cL32);
13966     } else {
13967       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13968               .addReg(cH32).addReg(cL32)
13969               .addImm(X86::COND_E);
13970       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13971     }
13972     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13973     if (Subtarget->hasCMov()) {
13974       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13975         .addReg(SrcLoReg).addReg(t4L);
13976       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13977         .addReg(SrcHiReg).addReg(t4H);
13978     } else {
13979       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13980               .addReg(SrcLoReg).addReg(t4L)
13981               .addImm(X86::COND_NE);
13982       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13983       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13984       // 2nd CMOV lowering.
13985       mainMBB->addLiveIn(X86::EFLAGS);
13986       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13987               .addReg(SrcHiReg).addReg(t4H)
13988               .addImm(X86::COND_NE);
13989       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13990       // Replace the original PHI node as mainMBB is changed after CMOV
13991       // lowering.
13992       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13993         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13994       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13995         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13996       PhiL->eraseFromParent();
13997       PhiH->eraseFromParent();
13998     }
13999     break;
14000   }
14001   case X86::ATOMSWAP6432: {
14002     unsigned HiOpc;
14003     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14004     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14005     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14006     break;
14007   }
14008   }
14009
14010   // Copy EDX:EAX back from HiReg:LoReg
14011   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14012   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14013   // Copy ECX:EBX from t1H:t1L
14014   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14015   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14016
14017   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14018   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14019     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14020     if (NewMO.isReg())
14021       NewMO.setIsKill(false);
14022     MIB.addOperand(NewMO);
14023   }
14024   MIB.setMemRefs(MMOBegin, MMOEnd);
14025
14026   // Copy EDX:EAX back to t3H:t3L
14027   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14028   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14029
14030   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14031
14032   mainMBB->addSuccessor(origMainMBB);
14033   mainMBB->addSuccessor(sinkMBB);
14034
14035   // sinkMBB:
14036   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14037           TII->get(TargetOpcode::COPY), DstLoReg)
14038     .addReg(t3L);
14039   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14040           TII->get(TargetOpcode::COPY), DstHiReg)
14041     .addReg(t3H);
14042
14043   MI->eraseFromParent();
14044   return sinkMBB;
14045 }
14046
14047 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14048 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14049 // in the .td file.
14050 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14051                                        const TargetInstrInfo *TII) {
14052   unsigned Opc;
14053   switch (MI->getOpcode()) {
14054   default: llvm_unreachable("illegal opcode!");
14055   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14056   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14057   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14058   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14059   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14060   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14061   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14062   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14063   }
14064
14065   DebugLoc dl = MI->getDebugLoc();
14066   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14067
14068   unsigned NumArgs = MI->getNumOperands();
14069   for (unsigned i = 1; i < NumArgs; ++i) {
14070     MachineOperand &Op = MI->getOperand(i);
14071     if (!(Op.isReg() && Op.isImplicit()))
14072       MIB.addOperand(Op);
14073   }
14074   if (MI->hasOneMemOperand())
14075     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14076
14077   BuildMI(*BB, MI, dl,
14078     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14079     .addReg(X86::XMM0);
14080
14081   MI->eraseFromParent();
14082   return BB;
14083 }
14084
14085 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14086 // defs in an instruction pattern
14087 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14088                                        const TargetInstrInfo *TII) {
14089   unsigned Opc;
14090   switch (MI->getOpcode()) {
14091   default: llvm_unreachable("illegal opcode!");
14092   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14093   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14094   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14095   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14096   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14097   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14098   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14099   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14100   }
14101
14102   DebugLoc dl = MI->getDebugLoc();
14103   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14104
14105   unsigned NumArgs = MI->getNumOperands(); // remove the results
14106   for (unsigned i = 1; i < NumArgs; ++i) {
14107     MachineOperand &Op = MI->getOperand(i);
14108     if (!(Op.isReg() && Op.isImplicit()))
14109       MIB.addOperand(Op);
14110   }
14111   if (MI->hasOneMemOperand())
14112     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14113
14114   BuildMI(*BB, MI, dl,
14115     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14116     .addReg(X86::ECX);
14117
14118   MI->eraseFromParent();
14119   return BB;
14120 }
14121
14122 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14123                                        const TargetInstrInfo *TII,
14124                                        const X86Subtarget* Subtarget) {
14125   DebugLoc dl = MI->getDebugLoc();
14126
14127   // Address into RAX/EAX, other two args into ECX, EDX.
14128   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14129   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14130   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14131   for (int i = 0; i < X86::AddrNumOperands; ++i)
14132     MIB.addOperand(MI->getOperand(i));
14133
14134   unsigned ValOps = X86::AddrNumOperands;
14135   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14136     .addReg(MI->getOperand(ValOps).getReg());
14137   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14138     .addReg(MI->getOperand(ValOps+1).getReg());
14139
14140   // The instruction doesn't actually take any operands though.
14141   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14142
14143   MI->eraseFromParent(); // The pseudo is gone now.
14144   return BB;
14145 }
14146
14147 MachineBasicBlock *
14148 X86TargetLowering::EmitVAARG64WithCustomInserter(
14149                    MachineInstr *MI,
14150                    MachineBasicBlock *MBB) const {
14151   // Emit va_arg instruction on X86-64.
14152
14153   // Operands to this pseudo-instruction:
14154   // 0  ) Output        : destination address (reg)
14155   // 1-5) Input         : va_list address (addr, i64mem)
14156   // 6  ) ArgSize       : Size (in bytes) of vararg type
14157   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14158   // 8  ) Align         : Alignment of type
14159   // 9  ) EFLAGS (implicit-def)
14160
14161   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14162   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14163
14164   unsigned DestReg = MI->getOperand(0).getReg();
14165   MachineOperand &Base = MI->getOperand(1);
14166   MachineOperand &Scale = MI->getOperand(2);
14167   MachineOperand &Index = MI->getOperand(3);
14168   MachineOperand &Disp = MI->getOperand(4);
14169   MachineOperand &Segment = MI->getOperand(5);
14170   unsigned ArgSize = MI->getOperand(6).getImm();
14171   unsigned ArgMode = MI->getOperand(7).getImm();
14172   unsigned Align = MI->getOperand(8).getImm();
14173
14174   // Memory Reference
14175   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14176   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14177   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14178
14179   // Machine Information
14180   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14181   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14182   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14183   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14184   DebugLoc DL = MI->getDebugLoc();
14185
14186   // struct va_list {
14187   //   i32   gp_offset
14188   //   i32   fp_offset
14189   //   i64   overflow_area (address)
14190   //   i64   reg_save_area (address)
14191   // }
14192   // sizeof(va_list) = 24
14193   // alignment(va_list) = 8
14194
14195   unsigned TotalNumIntRegs = 6;
14196   unsigned TotalNumXMMRegs = 8;
14197   bool UseGPOffset = (ArgMode == 1);
14198   bool UseFPOffset = (ArgMode == 2);
14199   unsigned MaxOffset = TotalNumIntRegs * 8 +
14200                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14201
14202   /* Align ArgSize to a multiple of 8 */
14203   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14204   bool NeedsAlign = (Align > 8);
14205
14206   MachineBasicBlock *thisMBB = MBB;
14207   MachineBasicBlock *overflowMBB;
14208   MachineBasicBlock *offsetMBB;
14209   MachineBasicBlock *endMBB;
14210
14211   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14212   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14213   unsigned OffsetReg = 0;
14214
14215   if (!UseGPOffset && !UseFPOffset) {
14216     // If we only pull from the overflow region, we don't create a branch.
14217     // We don't need to alter control flow.
14218     OffsetDestReg = 0; // unused
14219     OverflowDestReg = DestReg;
14220
14221     offsetMBB = NULL;
14222     overflowMBB = thisMBB;
14223     endMBB = thisMBB;
14224   } else {
14225     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14226     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14227     // If not, pull from overflow_area. (branch to overflowMBB)
14228     //
14229     //       thisMBB
14230     //         |     .
14231     //         |        .
14232     //     offsetMBB   overflowMBB
14233     //         |        .
14234     //         |     .
14235     //        endMBB
14236
14237     // Registers for the PHI in endMBB
14238     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14239     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14240
14241     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14242     MachineFunction *MF = MBB->getParent();
14243     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14244     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14245     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14246
14247     MachineFunction::iterator MBBIter = MBB;
14248     ++MBBIter;
14249
14250     // Insert the new basic blocks
14251     MF->insert(MBBIter, offsetMBB);
14252     MF->insert(MBBIter, overflowMBB);
14253     MF->insert(MBBIter, endMBB);
14254
14255     // Transfer the remainder of MBB and its successor edges to endMBB.
14256     endMBB->splice(endMBB->begin(), thisMBB,
14257                     llvm::next(MachineBasicBlock::iterator(MI)),
14258                     thisMBB->end());
14259     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14260
14261     // Make offsetMBB and overflowMBB successors of thisMBB
14262     thisMBB->addSuccessor(offsetMBB);
14263     thisMBB->addSuccessor(overflowMBB);
14264
14265     // endMBB is a successor of both offsetMBB and overflowMBB
14266     offsetMBB->addSuccessor(endMBB);
14267     overflowMBB->addSuccessor(endMBB);
14268
14269     // Load the offset value into a register
14270     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14271     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14272       .addOperand(Base)
14273       .addOperand(Scale)
14274       .addOperand(Index)
14275       .addDisp(Disp, UseFPOffset ? 4 : 0)
14276       .addOperand(Segment)
14277       .setMemRefs(MMOBegin, MMOEnd);
14278
14279     // Check if there is enough room left to pull this argument.
14280     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14281       .addReg(OffsetReg)
14282       .addImm(MaxOffset + 8 - ArgSizeA8);
14283
14284     // Branch to "overflowMBB" if offset >= max
14285     // Fall through to "offsetMBB" otherwise
14286     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14287       .addMBB(overflowMBB);
14288   }
14289
14290   // In offsetMBB, emit code to use the reg_save_area.
14291   if (offsetMBB) {
14292     assert(OffsetReg != 0);
14293
14294     // Read the reg_save_area address.
14295     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14296     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14297       .addOperand(Base)
14298       .addOperand(Scale)
14299       .addOperand(Index)
14300       .addDisp(Disp, 16)
14301       .addOperand(Segment)
14302       .setMemRefs(MMOBegin, MMOEnd);
14303
14304     // Zero-extend the offset
14305     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14306       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14307         .addImm(0)
14308         .addReg(OffsetReg)
14309         .addImm(X86::sub_32bit);
14310
14311     // Add the offset to the reg_save_area to get the final address.
14312     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14313       .addReg(OffsetReg64)
14314       .addReg(RegSaveReg);
14315
14316     // Compute the offset for the next argument
14317     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14318     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14319       .addReg(OffsetReg)
14320       .addImm(UseFPOffset ? 16 : 8);
14321
14322     // Store it back into the va_list.
14323     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14324       .addOperand(Base)
14325       .addOperand(Scale)
14326       .addOperand(Index)
14327       .addDisp(Disp, UseFPOffset ? 4 : 0)
14328       .addOperand(Segment)
14329       .addReg(NextOffsetReg)
14330       .setMemRefs(MMOBegin, MMOEnd);
14331
14332     // Jump to endMBB
14333     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14334       .addMBB(endMBB);
14335   }
14336
14337   //
14338   // Emit code to use overflow area
14339   //
14340
14341   // Load the overflow_area address into a register.
14342   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14343   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14344     .addOperand(Base)
14345     .addOperand(Scale)
14346     .addOperand(Index)
14347     .addDisp(Disp, 8)
14348     .addOperand(Segment)
14349     .setMemRefs(MMOBegin, MMOEnd);
14350
14351   // If we need to align it, do so. Otherwise, just copy the address
14352   // to OverflowDestReg.
14353   if (NeedsAlign) {
14354     // Align the overflow address
14355     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14356     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14357
14358     // aligned_addr = (addr + (align-1)) & ~(align-1)
14359     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14360       .addReg(OverflowAddrReg)
14361       .addImm(Align-1);
14362
14363     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14364       .addReg(TmpReg)
14365       .addImm(~(uint64_t)(Align-1));
14366   } else {
14367     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14368       .addReg(OverflowAddrReg);
14369   }
14370
14371   // Compute the next overflow address after this argument.
14372   // (the overflow address should be kept 8-byte aligned)
14373   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14374   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14375     .addReg(OverflowDestReg)
14376     .addImm(ArgSizeA8);
14377
14378   // Store the new overflow address.
14379   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14380     .addOperand(Base)
14381     .addOperand(Scale)
14382     .addOperand(Index)
14383     .addDisp(Disp, 8)
14384     .addOperand(Segment)
14385     .addReg(NextAddrReg)
14386     .setMemRefs(MMOBegin, MMOEnd);
14387
14388   // If we branched, emit the PHI to the front of endMBB.
14389   if (offsetMBB) {
14390     BuildMI(*endMBB, endMBB->begin(), DL,
14391             TII->get(X86::PHI), DestReg)
14392       .addReg(OffsetDestReg).addMBB(offsetMBB)
14393       .addReg(OverflowDestReg).addMBB(overflowMBB);
14394   }
14395
14396   // Erase the pseudo instruction
14397   MI->eraseFromParent();
14398
14399   return endMBB;
14400 }
14401
14402 MachineBasicBlock *
14403 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14404                                                  MachineInstr *MI,
14405                                                  MachineBasicBlock *MBB) const {
14406   // Emit code to save XMM registers to the stack. The ABI says that the
14407   // number of registers to save is given in %al, so it's theoretically
14408   // possible to do an indirect jump trick to avoid saving all of them,
14409   // however this code takes a simpler approach and just executes all
14410   // of the stores if %al is non-zero. It's less code, and it's probably
14411   // easier on the hardware branch predictor, and stores aren't all that
14412   // expensive anyway.
14413
14414   // Create the new basic blocks. One block contains all the XMM stores,
14415   // and one block is the final destination regardless of whether any
14416   // stores were performed.
14417   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14418   MachineFunction *F = MBB->getParent();
14419   MachineFunction::iterator MBBIter = MBB;
14420   ++MBBIter;
14421   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14422   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14423   F->insert(MBBIter, XMMSaveMBB);
14424   F->insert(MBBIter, EndMBB);
14425
14426   // Transfer the remainder of MBB and its successor edges to EndMBB.
14427   EndMBB->splice(EndMBB->begin(), MBB,
14428                  llvm::next(MachineBasicBlock::iterator(MI)),
14429                  MBB->end());
14430   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14431
14432   // The original block will now fall through to the XMM save block.
14433   MBB->addSuccessor(XMMSaveMBB);
14434   // The XMMSaveMBB will fall through to the end block.
14435   XMMSaveMBB->addSuccessor(EndMBB);
14436
14437   // Now add the instructions.
14438   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14439   DebugLoc DL = MI->getDebugLoc();
14440
14441   unsigned CountReg = MI->getOperand(0).getReg();
14442   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14443   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14444
14445   if (!Subtarget->isTargetWin64()) {
14446     // If %al is 0, branch around the XMM save block.
14447     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14448     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14449     MBB->addSuccessor(EndMBB);
14450   }
14451
14452   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14453   // In the XMM save block, save all the XMM argument registers.
14454   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14455     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14456     MachineMemOperand *MMO =
14457       F->getMachineMemOperand(
14458           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14459         MachineMemOperand::MOStore,
14460         /*Size=*/16, /*Align=*/16);
14461     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14462       .addFrameIndex(RegSaveFrameIndex)
14463       .addImm(/*Scale=*/1)
14464       .addReg(/*IndexReg=*/0)
14465       .addImm(/*Disp=*/Offset)
14466       .addReg(/*Segment=*/0)
14467       .addReg(MI->getOperand(i).getReg())
14468       .addMemOperand(MMO);
14469   }
14470
14471   MI->eraseFromParent();   // The pseudo instruction is gone now.
14472
14473   return EndMBB;
14474 }
14475
14476 // The EFLAGS operand of SelectItr might be missing a kill marker
14477 // because there were multiple uses of EFLAGS, and ISel didn't know
14478 // which to mark. Figure out whether SelectItr should have had a
14479 // kill marker, and set it if it should. Returns the correct kill
14480 // marker value.
14481 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14482                                      MachineBasicBlock* BB,
14483                                      const TargetRegisterInfo* TRI) {
14484   // Scan forward through BB for a use/def of EFLAGS.
14485   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14486   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14487     const MachineInstr& mi = *miI;
14488     if (mi.readsRegister(X86::EFLAGS))
14489       return false;
14490     if (mi.definesRegister(X86::EFLAGS))
14491       break; // Should have kill-flag - update below.
14492   }
14493
14494   // If we hit the end of the block, check whether EFLAGS is live into a
14495   // successor.
14496   if (miI == BB->end()) {
14497     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14498                                           sEnd = BB->succ_end();
14499          sItr != sEnd; ++sItr) {
14500       MachineBasicBlock* succ = *sItr;
14501       if (succ->isLiveIn(X86::EFLAGS))
14502         return false;
14503     }
14504   }
14505
14506   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14507   // out. SelectMI should have a kill flag on EFLAGS.
14508   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14509   return true;
14510 }
14511
14512 MachineBasicBlock *
14513 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14514                                      MachineBasicBlock *BB) const {
14515   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14516   DebugLoc DL = MI->getDebugLoc();
14517
14518   // To "insert" a SELECT_CC instruction, we actually have to insert the
14519   // diamond control-flow pattern.  The incoming instruction knows the
14520   // destination vreg to set, the condition code register to branch on, the
14521   // true/false values to select between, and a branch opcode to use.
14522   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14523   MachineFunction::iterator It = BB;
14524   ++It;
14525
14526   //  thisMBB:
14527   //  ...
14528   //   TrueVal = ...
14529   //   cmpTY ccX, r1, r2
14530   //   bCC copy1MBB
14531   //   fallthrough --> copy0MBB
14532   MachineBasicBlock *thisMBB = BB;
14533   MachineFunction *F = BB->getParent();
14534   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14535   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14536   F->insert(It, copy0MBB);
14537   F->insert(It, sinkMBB);
14538
14539   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14540   // live into the sink and copy blocks.
14541   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14542   if (!MI->killsRegister(X86::EFLAGS) &&
14543       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14544     copy0MBB->addLiveIn(X86::EFLAGS);
14545     sinkMBB->addLiveIn(X86::EFLAGS);
14546   }
14547
14548   // Transfer the remainder of BB and its successor edges to sinkMBB.
14549   sinkMBB->splice(sinkMBB->begin(), BB,
14550                   llvm::next(MachineBasicBlock::iterator(MI)),
14551                   BB->end());
14552   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14553
14554   // Add the true and fallthrough blocks as its successors.
14555   BB->addSuccessor(copy0MBB);
14556   BB->addSuccessor(sinkMBB);
14557
14558   // Create the conditional branch instruction.
14559   unsigned Opc =
14560     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14561   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14562
14563   //  copy0MBB:
14564   //   %FalseValue = ...
14565   //   # fallthrough to sinkMBB
14566   copy0MBB->addSuccessor(sinkMBB);
14567
14568   //  sinkMBB:
14569   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14570   //  ...
14571   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14572           TII->get(X86::PHI), MI->getOperand(0).getReg())
14573     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14574     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14575
14576   MI->eraseFromParent();   // The pseudo instruction is gone now.
14577   return sinkMBB;
14578 }
14579
14580 MachineBasicBlock *
14581 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14582                                         bool Is64Bit) const {
14583   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14584   DebugLoc DL = MI->getDebugLoc();
14585   MachineFunction *MF = BB->getParent();
14586   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14587
14588   assert(getTargetMachine().Options.EnableSegmentedStacks);
14589
14590   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14591   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14592
14593   // BB:
14594   //  ... [Till the alloca]
14595   // If stacklet is not large enough, jump to mallocMBB
14596   //
14597   // bumpMBB:
14598   //  Allocate by subtracting from RSP
14599   //  Jump to continueMBB
14600   //
14601   // mallocMBB:
14602   //  Allocate by call to runtime
14603   //
14604   // continueMBB:
14605   //  ...
14606   //  [rest of original BB]
14607   //
14608
14609   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14610   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14611   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14612
14613   MachineRegisterInfo &MRI = MF->getRegInfo();
14614   const TargetRegisterClass *AddrRegClass =
14615     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14616
14617   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14618     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14619     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14620     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14621     sizeVReg = MI->getOperand(1).getReg(),
14622     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14623
14624   MachineFunction::iterator MBBIter = BB;
14625   ++MBBIter;
14626
14627   MF->insert(MBBIter, bumpMBB);
14628   MF->insert(MBBIter, mallocMBB);
14629   MF->insert(MBBIter, continueMBB);
14630
14631   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14632                       (MachineBasicBlock::iterator(MI)), BB->end());
14633   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14634
14635   // Add code to the main basic block to check if the stack limit has been hit,
14636   // and if so, jump to mallocMBB otherwise to bumpMBB.
14637   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14638   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14639     .addReg(tmpSPVReg).addReg(sizeVReg);
14640   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14641     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14642     .addReg(SPLimitVReg);
14643   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14644
14645   // bumpMBB simply decreases the stack pointer, since we know the current
14646   // stacklet has enough space.
14647   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14648     .addReg(SPLimitVReg);
14649   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14650     .addReg(SPLimitVReg);
14651   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14652
14653   // Calls into a routine in libgcc to allocate more space from the heap.
14654   const uint32_t *RegMask =
14655     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14656   if (Is64Bit) {
14657     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14658       .addReg(sizeVReg);
14659     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14660       .addExternalSymbol("__morestack_allocate_stack_space")
14661       .addRegMask(RegMask)
14662       .addReg(X86::RDI, RegState::Implicit)
14663       .addReg(X86::RAX, RegState::ImplicitDefine);
14664   } else {
14665     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14666       .addImm(12);
14667     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14668     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14669       .addExternalSymbol("__morestack_allocate_stack_space")
14670       .addRegMask(RegMask)
14671       .addReg(X86::EAX, RegState::ImplicitDefine);
14672   }
14673
14674   if (!Is64Bit)
14675     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14676       .addImm(16);
14677
14678   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14679     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14680   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14681
14682   // Set up the CFG correctly.
14683   BB->addSuccessor(bumpMBB);
14684   BB->addSuccessor(mallocMBB);
14685   mallocMBB->addSuccessor(continueMBB);
14686   bumpMBB->addSuccessor(continueMBB);
14687
14688   // Take care of the PHI nodes.
14689   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14690           MI->getOperand(0).getReg())
14691     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14692     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14693
14694   // Delete the original pseudo instruction.
14695   MI->eraseFromParent();
14696
14697   // And we're done.
14698   return continueMBB;
14699 }
14700
14701 MachineBasicBlock *
14702 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14703                                           MachineBasicBlock *BB) const {
14704   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14705   DebugLoc DL = MI->getDebugLoc();
14706
14707   assert(!Subtarget->isTargetEnvMacho());
14708
14709   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14710   // non-trivial part is impdef of ESP.
14711
14712   if (Subtarget->isTargetWin64()) {
14713     if (Subtarget->isTargetCygMing()) {
14714       // ___chkstk(Mingw64):
14715       // Clobbers R10, R11, RAX and EFLAGS.
14716       // Updates RSP.
14717       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14718         .addExternalSymbol("___chkstk")
14719         .addReg(X86::RAX, RegState::Implicit)
14720         .addReg(X86::RSP, RegState::Implicit)
14721         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14722         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14723         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14724     } else {
14725       // __chkstk(MSVCRT): does not update stack pointer.
14726       // Clobbers R10, R11 and EFLAGS.
14727       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14728         .addExternalSymbol("__chkstk")
14729         .addReg(X86::RAX, RegState::Implicit)
14730         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14731       // RAX has the offset to be subtracted from RSP.
14732       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14733         .addReg(X86::RSP)
14734         .addReg(X86::RAX);
14735     }
14736   } else {
14737     const char *StackProbeSymbol =
14738       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14739
14740     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14741       .addExternalSymbol(StackProbeSymbol)
14742       .addReg(X86::EAX, RegState::Implicit)
14743       .addReg(X86::ESP, RegState::Implicit)
14744       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14745       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14746       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14747   }
14748
14749   MI->eraseFromParent();   // The pseudo instruction is gone now.
14750   return BB;
14751 }
14752
14753 MachineBasicBlock *
14754 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14755                                       MachineBasicBlock *BB) const {
14756   // This is pretty easy.  We're taking the value that we received from
14757   // our load from the relocation, sticking it in either RDI (x86-64)
14758   // or EAX and doing an indirect call.  The return value will then
14759   // be in the normal return register.
14760   const X86InstrInfo *TII
14761     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14762   DebugLoc DL = MI->getDebugLoc();
14763   MachineFunction *F = BB->getParent();
14764
14765   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14766   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14767
14768   // Get a register mask for the lowered call.
14769   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14770   // proper register mask.
14771   const uint32_t *RegMask =
14772     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14773   if (Subtarget->is64Bit()) {
14774     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14775                                       TII->get(X86::MOV64rm), X86::RDI)
14776     .addReg(X86::RIP)
14777     .addImm(0).addReg(0)
14778     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14779                       MI->getOperand(3).getTargetFlags())
14780     .addReg(0);
14781     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14782     addDirectMem(MIB, X86::RDI);
14783     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14784   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14785     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14786                                       TII->get(X86::MOV32rm), X86::EAX)
14787     .addReg(0)
14788     .addImm(0).addReg(0)
14789     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14790                       MI->getOperand(3).getTargetFlags())
14791     .addReg(0);
14792     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14793     addDirectMem(MIB, X86::EAX);
14794     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14795   } else {
14796     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14797                                       TII->get(X86::MOV32rm), X86::EAX)
14798     .addReg(TII->getGlobalBaseReg(F))
14799     .addImm(0).addReg(0)
14800     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14801                       MI->getOperand(3).getTargetFlags())
14802     .addReg(0);
14803     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14804     addDirectMem(MIB, X86::EAX);
14805     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14806   }
14807
14808   MI->eraseFromParent(); // The pseudo instruction is gone now.
14809   return BB;
14810 }
14811
14812 MachineBasicBlock *
14813 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14814                                     MachineBasicBlock *MBB) const {
14815   DebugLoc DL = MI->getDebugLoc();
14816   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14817
14818   MachineFunction *MF = MBB->getParent();
14819   MachineRegisterInfo &MRI = MF->getRegInfo();
14820
14821   const BasicBlock *BB = MBB->getBasicBlock();
14822   MachineFunction::iterator I = MBB;
14823   ++I;
14824
14825   // Memory Reference
14826   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14827   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14828
14829   unsigned DstReg;
14830   unsigned MemOpndSlot = 0;
14831
14832   unsigned CurOp = 0;
14833
14834   DstReg = MI->getOperand(CurOp++).getReg();
14835   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14836   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14837   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14838   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14839
14840   MemOpndSlot = CurOp;
14841
14842   MVT PVT = getPointerTy();
14843   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14844          "Invalid Pointer Size!");
14845
14846   // For v = setjmp(buf), we generate
14847   //
14848   // thisMBB:
14849   //  buf[LabelOffset] = restoreMBB
14850   //  SjLjSetup restoreMBB
14851   //
14852   // mainMBB:
14853   //  v_main = 0
14854   //
14855   // sinkMBB:
14856   //  v = phi(main, restore)
14857   //
14858   // restoreMBB:
14859   //  v_restore = 1
14860
14861   MachineBasicBlock *thisMBB = MBB;
14862   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14863   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14864   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14865   MF->insert(I, mainMBB);
14866   MF->insert(I, sinkMBB);
14867   MF->push_back(restoreMBB);
14868
14869   MachineInstrBuilder MIB;
14870
14871   // Transfer the remainder of BB and its successor edges to sinkMBB.
14872   sinkMBB->splice(sinkMBB->begin(), MBB,
14873                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14874   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14875
14876   // thisMBB:
14877   unsigned PtrStoreOpc = 0;
14878   unsigned LabelReg = 0;
14879   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14880   Reloc::Model RM = getTargetMachine().getRelocationModel();
14881   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14882                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14883
14884   // Prepare IP either in reg or imm.
14885   if (!UseImmLabel) {
14886     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14887     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14888     LabelReg = MRI.createVirtualRegister(PtrRC);
14889     if (Subtarget->is64Bit()) {
14890       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14891               .addReg(X86::RIP)
14892               .addImm(0)
14893               .addReg(0)
14894               .addMBB(restoreMBB)
14895               .addReg(0);
14896     } else {
14897       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14898       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14899               .addReg(XII->getGlobalBaseReg(MF))
14900               .addImm(0)
14901               .addReg(0)
14902               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14903               .addReg(0);
14904     }
14905   } else
14906     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14907   // Store IP
14908   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14909   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14910     if (i == X86::AddrDisp)
14911       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14912     else
14913       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14914   }
14915   if (!UseImmLabel)
14916     MIB.addReg(LabelReg);
14917   else
14918     MIB.addMBB(restoreMBB);
14919   MIB.setMemRefs(MMOBegin, MMOEnd);
14920   // Setup
14921   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14922           .addMBB(restoreMBB);
14923
14924   const X86RegisterInfo *RegInfo =
14925     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14926   MIB.addRegMask(RegInfo->getNoPreservedMask());
14927   thisMBB->addSuccessor(mainMBB);
14928   thisMBB->addSuccessor(restoreMBB);
14929
14930   // mainMBB:
14931   //  EAX = 0
14932   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14933   mainMBB->addSuccessor(sinkMBB);
14934
14935   // sinkMBB:
14936   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14937           TII->get(X86::PHI), DstReg)
14938     .addReg(mainDstReg).addMBB(mainMBB)
14939     .addReg(restoreDstReg).addMBB(restoreMBB);
14940
14941   // restoreMBB:
14942   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14943   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14944   restoreMBB->addSuccessor(sinkMBB);
14945
14946   MI->eraseFromParent();
14947   return sinkMBB;
14948 }
14949
14950 MachineBasicBlock *
14951 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14952                                      MachineBasicBlock *MBB) const {
14953   DebugLoc DL = MI->getDebugLoc();
14954   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14955
14956   MachineFunction *MF = MBB->getParent();
14957   MachineRegisterInfo &MRI = MF->getRegInfo();
14958
14959   // Memory Reference
14960   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14961   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14962
14963   MVT PVT = getPointerTy();
14964   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14965          "Invalid Pointer Size!");
14966
14967   const TargetRegisterClass *RC =
14968     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14969   unsigned Tmp = MRI.createVirtualRegister(RC);
14970   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14971   const X86RegisterInfo *RegInfo =
14972     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14973   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14974   unsigned SP = RegInfo->getStackRegister();
14975
14976   MachineInstrBuilder MIB;
14977
14978   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14979   const int64_t SPOffset = 2 * PVT.getStoreSize();
14980
14981   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14982   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14983
14984   // Reload FP
14985   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14986   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14987     MIB.addOperand(MI->getOperand(i));
14988   MIB.setMemRefs(MMOBegin, MMOEnd);
14989   // Reload IP
14990   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14991   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14992     if (i == X86::AddrDisp)
14993       MIB.addDisp(MI->getOperand(i), LabelOffset);
14994     else
14995       MIB.addOperand(MI->getOperand(i));
14996   }
14997   MIB.setMemRefs(MMOBegin, MMOEnd);
14998   // Reload SP
14999   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15000   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15001     if (i == X86::AddrDisp)
15002       MIB.addDisp(MI->getOperand(i), SPOffset);
15003     else
15004       MIB.addOperand(MI->getOperand(i));
15005   }
15006   MIB.setMemRefs(MMOBegin, MMOEnd);
15007   // Jump
15008   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15009
15010   MI->eraseFromParent();
15011   return MBB;
15012 }
15013
15014 MachineBasicBlock *
15015 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15016                                                MachineBasicBlock *BB) const {
15017   switch (MI->getOpcode()) {
15018   default: llvm_unreachable("Unexpected instr type to insert");
15019   case X86::TAILJMPd64:
15020   case X86::TAILJMPr64:
15021   case X86::TAILJMPm64:
15022     llvm_unreachable("TAILJMP64 would not be touched here.");
15023   case X86::TCRETURNdi64:
15024   case X86::TCRETURNri64:
15025   case X86::TCRETURNmi64:
15026     return BB;
15027   case X86::WIN_ALLOCA:
15028     return EmitLoweredWinAlloca(MI, BB);
15029   case X86::SEG_ALLOCA_32:
15030     return EmitLoweredSegAlloca(MI, BB, false);
15031   case X86::SEG_ALLOCA_64:
15032     return EmitLoweredSegAlloca(MI, BB, true);
15033   case X86::TLSCall_32:
15034   case X86::TLSCall_64:
15035     return EmitLoweredTLSCall(MI, BB);
15036   case X86::CMOV_GR8:
15037   case X86::CMOV_FR32:
15038   case X86::CMOV_FR64:
15039   case X86::CMOV_V4F32:
15040   case X86::CMOV_V2F64:
15041   case X86::CMOV_V2I64:
15042   case X86::CMOV_V8F32:
15043   case X86::CMOV_V4F64:
15044   case X86::CMOV_V4I64:
15045   case X86::CMOV_GR16:
15046   case X86::CMOV_GR32:
15047   case X86::CMOV_RFP32:
15048   case X86::CMOV_RFP64:
15049   case X86::CMOV_RFP80:
15050     return EmitLoweredSelect(MI, BB);
15051
15052   case X86::FP32_TO_INT16_IN_MEM:
15053   case X86::FP32_TO_INT32_IN_MEM:
15054   case X86::FP32_TO_INT64_IN_MEM:
15055   case X86::FP64_TO_INT16_IN_MEM:
15056   case X86::FP64_TO_INT32_IN_MEM:
15057   case X86::FP64_TO_INT64_IN_MEM:
15058   case X86::FP80_TO_INT16_IN_MEM:
15059   case X86::FP80_TO_INT32_IN_MEM:
15060   case X86::FP80_TO_INT64_IN_MEM: {
15061     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15062     DebugLoc DL = MI->getDebugLoc();
15063
15064     // Change the floating point control register to use "round towards zero"
15065     // mode when truncating to an integer value.
15066     MachineFunction *F = BB->getParent();
15067     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15068     addFrameReference(BuildMI(*BB, MI, DL,
15069                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15070
15071     // Load the old value of the high byte of the control word...
15072     unsigned OldCW =
15073       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15074     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15075                       CWFrameIdx);
15076
15077     // Set the high part to be round to zero...
15078     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15079       .addImm(0xC7F);
15080
15081     // Reload the modified control word now...
15082     addFrameReference(BuildMI(*BB, MI, DL,
15083                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15084
15085     // Restore the memory image of control word to original value
15086     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15087       .addReg(OldCW);
15088
15089     // Get the X86 opcode to use.
15090     unsigned Opc;
15091     switch (MI->getOpcode()) {
15092     default: llvm_unreachable("illegal opcode!");
15093     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15094     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15095     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15096     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15097     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15098     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15099     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15100     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15101     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15102     }
15103
15104     X86AddressMode AM;
15105     MachineOperand &Op = MI->getOperand(0);
15106     if (Op.isReg()) {
15107       AM.BaseType = X86AddressMode::RegBase;
15108       AM.Base.Reg = Op.getReg();
15109     } else {
15110       AM.BaseType = X86AddressMode::FrameIndexBase;
15111       AM.Base.FrameIndex = Op.getIndex();
15112     }
15113     Op = MI->getOperand(1);
15114     if (Op.isImm())
15115       AM.Scale = Op.getImm();
15116     Op = MI->getOperand(2);
15117     if (Op.isImm())
15118       AM.IndexReg = Op.getImm();
15119     Op = MI->getOperand(3);
15120     if (Op.isGlobal()) {
15121       AM.GV = Op.getGlobal();
15122     } else {
15123       AM.Disp = Op.getImm();
15124     }
15125     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15126                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15127
15128     // Reload the original control word now.
15129     addFrameReference(BuildMI(*BB, MI, DL,
15130                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15131
15132     MI->eraseFromParent();   // The pseudo instruction is gone now.
15133     return BB;
15134   }
15135     // String/text processing lowering.
15136   case X86::PCMPISTRM128REG:
15137   case X86::VPCMPISTRM128REG:
15138   case X86::PCMPISTRM128MEM:
15139   case X86::VPCMPISTRM128MEM:
15140   case X86::PCMPESTRM128REG:
15141   case X86::VPCMPESTRM128REG:
15142   case X86::PCMPESTRM128MEM:
15143   case X86::VPCMPESTRM128MEM:
15144     assert(Subtarget->hasSSE42() &&
15145            "Target must have SSE4.2 or AVX features enabled");
15146     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15147
15148   // String/text processing lowering.
15149   case X86::PCMPISTRIREG:
15150   case X86::VPCMPISTRIREG:
15151   case X86::PCMPISTRIMEM:
15152   case X86::VPCMPISTRIMEM:
15153   case X86::PCMPESTRIREG:
15154   case X86::VPCMPESTRIREG:
15155   case X86::PCMPESTRIMEM:
15156   case X86::VPCMPESTRIMEM:
15157     assert(Subtarget->hasSSE42() &&
15158            "Target must have SSE4.2 or AVX features enabled");
15159     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15160
15161   // Thread synchronization.
15162   case X86::MONITOR:
15163     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15164
15165   // xbegin
15166   case X86::XBEGIN:
15167     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15168
15169   // Atomic Lowering.
15170   case X86::ATOMAND8:
15171   case X86::ATOMAND16:
15172   case X86::ATOMAND32:
15173   case X86::ATOMAND64:
15174     // Fall through
15175   case X86::ATOMOR8:
15176   case X86::ATOMOR16:
15177   case X86::ATOMOR32:
15178   case X86::ATOMOR64:
15179     // Fall through
15180   case X86::ATOMXOR16:
15181   case X86::ATOMXOR8:
15182   case X86::ATOMXOR32:
15183   case X86::ATOMXOR64:
15184     // Fall through
15185   case X86::ATOMNAND8:
15186   case X86::ATOMNAND16:
15187   case X86::ATOMNAND32:
15188   case X86::ATOMNAND64:
15189     // Fall through
15190   case X86::ATOMMAX8:
15191   case X86::ATOMMAX16:
15192   case X86::ATOMMAX32:
15193   case X86::ATOMMAX64:
15194     // Fall through
15195   case X86::ATOMMIN8:
15196   case X86::ATOMMIN16:
15197   case X86::ATOMMIN32:
15198   case X86::ATOMMIN64:
15199     // Fall through
15200   case X86::ATOMUMAX8:
15201   case X86::ATOMUMAX16:
15202   case X86::ATOMUMAX32:
15203   case X86::ATOMUMAX64:
15204     // Fall through
15205   case X86::ATOMUMIN8:
15206   case X86::ATOMUMIN16:
15207   case X86::ATOMUMIN32:
15208   case X86::ATOMUMIN64:
15209     return EmitAtomicLoadArith(MI, BB);
15210
15211   // This group does 64-bit operations on a 32-bit host.
15212   case X86::ATOMAND6432:
15213   case X86::ATOMOR6432:
15214   case X86::ATOMXOR6432:
15215   case X86::ATOMNAND6432:
15216   case X86::ATOMADD6432:
15217   case X86::ATOMSUB6432:
15218   case X86::ATOMMAX6432:
15219   case X86::ATOMMIN6432:
15220   case X86::ATOMUMAX6432:
15221   case X86::ATOMUMIN6432:
15222   case X86::ATOMSWAP6432:
15223     return EmitAtomicLoadArith6432(MI, BB);
15224
15225   case X86::VASTART_SAVE_XMM_REGS:
15226     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15227
15228   case X86::VAARG_64:
15229     return EmitVAARG64WithCustomInserter(MI, BB);
15230
15231   case X86::EH_SjLj_SetJmp32:
15232   case X86::EH_SjLj_SetJmp64:
15233     return emitEHSjLjSetJmp(MI, BB);
15234
15235   case X86::EH_SjLj_LongJmp32:
15236   case X86::EH_SjLj_LongJmp64:
15237     return emitEHSjLjLongJmp(MI, BB);
15238   }
15239 }
15240
15241 //===----------------------------------------------------------------------===//
15242 //                           X86 Optimization Hooks
15243 //===----------------------------------------------------------------------===//
15244
15245 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15246                                                        APInt &KnownZero,
15247                                                        APInt &KnownOne,
15248                                                        const SelectionDAG &DAG,
15249                                                        unsigned Depth) const {
15250   unsigned BitWidth = KnownZero.getBitWidth();
15251   unsigned Opc = Op.getOpcode();
15252   assert((Opc >= ISD::BUILTIN_OP_END ||
15253           Opc == ISD::INTRINSIC_WO_CHAIN ||
15254           Opc == ISD::INTRINSIC_W_CHAIN ||
15255           Opc == ISD::INTRINSIC_VOID) &&
15256          "Should use MaskedValueIsZero if you don't know whether Op"
15257          " is a target node!");
15258
15259   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15260   switch (Opc) {
15261   default: break;
15262   case X86ISD::ADD:
15263   case X86ISD::SUB:
15264   case X86ISD::ADC:
15265   case X86ISD::SBB:
15266   case X86ISD::SMUL:
15267   case X86ISD::UMUL:
15268   case X86ISD::INC:
15269   case X86ISD::DEC:
15270   case X86ISD::OR:
15271   case X86ISD::XOR:
15272   case X86ISD::AND:
15273     // These nodes' second result is a boolean.
15274     if (Op.getResNo() == 0)
15275       break;
15276     // Fallthrough
15277   case X86ISD::SETCC:
15278     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15279     break;
15280   case ISD::INTRINSIC_WO_CHAIN: {
15281     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15282     unsigned NumLoBits = 0;
15283     switch (IntId) {
15284     default: break;
15285     case Intrinsic::x86_sse_movmsk_ps:
15286     case Intrinsic::x86_avx_movmsk_ps_256:
15287     case Intrinsic::x86_sse2_movmsk_pd:
15288     case Intrinsic::x86_avx_movmsk_pd_256:
15289     case Intrinsic::x86_mmx_pmovmskb:
15290     case Intrinsic::x86_sse2_pmovmskb_128:
15291     case Intrinsic::x86_avx2_pmovmskb: {
15292       // High bits of movmskp{s|d}, pmovmskb are known zero.
15293       switch (IntId) {
15294         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15295         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15296         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15297         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15298         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15299         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15300         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15301         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15302       }
15303       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15304       break;
15305     }
15306     }
15307     break;
15308   }
15309   }
15310 }
15311
15312 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15313                                                          unsigned Depth) const {
15314   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15315   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15316     return Op.getValueType().getScalarType().getSizeInBits();
15317
15318   // Fallback case.
15319   return 1;
15320 }
15321
15322 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15323 /// node is a GlobalAddress + offset.
15324 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15325                                        const GlobalValue* &GA,
15326                                        int64_t &Offset) const {
15327   if (N->getOpcode() == X86ISD::Wrapper) {
15328     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15329       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15330       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15331       return true;
15332     }
15333   }
15334   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15335 }
15336
15337 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15338 /// same as extracting the high 128-bit part of 256-bit vector and then
15339 /// inserting the result into the low part of a new 256-bit vector
15340 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15341   EVT VT = SVOp->getValueType(0);
15342   unsigned NumElems = VT.getVectorNumElements();
15343
15344   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15345   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15346     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15347         SVOp->getMaskElt(j) >= 0)
15348       return false;
15349
15350   return true;
15351 }
15352
15353 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15354 /// same as extracting the low 128-bit part of 256-bit vector and then
15355 /// inserting the result into the high part of a new 256-bit vector
15356 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15357   EVT VT = SVOp->getValueType(0);
15358   unsigned NumElems = VT.getVectorNumElements();
15359
15360   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15361   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15362     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15363         SVOp->getMaskElt(j) >= 0)
15364       return false;
15365
15366   return true;
15367 }
15368
15369 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15370 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15371                                         TargetLowering::DAGCombinerInfo &DCI,
15372                                         const X86Subtarget* Subtarget) {
15373   SDLoc dl(N);
15374   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15375   SDValue V1 = SVOp->getOperand(0);
15376   SDValue V2 = SVOp->getOperand(1);
15377   EVT VT = SVOp->getValueType(0);
15378   unsigned NumElems = VT.getVectorNumElements();
15379
15380   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15381       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15382     //
15383     //                   0,0,0,...
15384     //                      |
15385     //    V      UNDEF    BUILD_VECTOR    UNDEF
15386     //     \      /           \           /
15387     //  CONCAT_VECTOR         CONCAT_VECTOR
15388     //         \                  /
15389     //          \                /
15390     //          RESULT: V + zero extended
15391     //
15392     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15393         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15394         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15395       return SDValue();
15396
15397     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15398       return SDValue();
15399
15400     // To match the shuffle mask, the first half of the mask should
15401     // be exactly the first vector, and all the rest a splat with the
15402     // first element of the second one.
15403     for (unsigned i = 0; i != NumElems/2; ++i)
15404       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15405           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15406         return SDValue();
15407
15408     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15409     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15410       if (Ld->hasNUsesOfValue(1, 0)) {
15411         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15412         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15413         SDValue ResNode =
15414           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15415                                   array_lengthof(Ops),
15416                                   Ld->getMemoryVT(),
15417                                   Ld->getPointerInfo(),
15418                                   Ld->getAlignment(),
15419                                   false/*isVolatile*/, true/*ReadMem*/,
15420                                   false/*WriteMem*/);
15421
15422         // Make sure the newly-created LOAD is in the same position as Ld in
15423         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15424         // and update uses of Ld's output chain to use the TokenFactor.
15425         if (Ld->hasAnyUseOfValue(1)) {
15426           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15427                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15428           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15429           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15430                                  SDValue(ResNode.getNode(), 1));
15431         }
15432
15433         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15434       }
15435     }
15436
15437     // Emit a zeroed vector and insert the desired subvector on its
15438     // first half.
15439     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15440     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15441     return DCI.CombineTo(N, InsV);
15442   }
15443
15444   //===--------------------------------------------------------------------===//
15445   // Combine some shuffles into subvector extracts and inserts:
15446   //
15447
15448   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15449   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15450     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15451     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15452     return DCI.CombineTo(N, InsV);
15453   }
15454
15455   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15456   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15457     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15458     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15459     return DCI.CombineTo(N, InsV);
15460   }
15461
15462   return SDValue();
15463 }
15464
15465 /// PerformShuffleCombine - Performs several different shuffle combines.
15466 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15467                                      TargetLowering::DAGCombinerInfo &DCI,
15468                                      const X86Subtarget *Subtarget) {
15469   SDLoc dl(N);
15470   EVT VT = N->getValueType(0);
15471
15472   // Don't create instructions with illegal types after legalize types has run.
15473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15474   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15475     return SDValue();
15476
15477   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15478   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15479       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15480     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15481
15482   // Only handle 128 wide vector from here on.
15483   if (!VT.is128BitVector())
15484     return SDValue();
15485
15486   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15487   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15488   // consecutive, non-overlapping, and in the right order.
15489   SmallVector<SDValue, 16> Elts;
15490   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15491     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15492
15493   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15494 }
15495
15496 /// PerformTruncateCombine - Converts truncate operation to
15497 /// a sequence of vector shuffle operations.
15498 /// It is possible when we truncate 256-bit vector to 128-bit vector
15499 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15500                                       TargetLowering::DAGCombinerInfo &DCI,
15501                                       const X86Subtarget *Subtarget)  {
15502   return SDValue();
15503 }
15504
15505 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15506 /// specific shuffle of a load can be folded into a single element load.
15507 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15508 /// shuffles have been customed lowered so we need to handle those here.
15509 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15510                                          TargetLowering::DAGCombinerInfo &DCI) {
15511   if (DCI.isBeforeLegalizeOps())
15512     return SDValue();
15513
15514   SDValue InVec = N->getOperand(0);
15515   SDValue EltNo = N->getOperand(1);
15516
15517   if (!isa<ConstantSDNode>(EltNo))
15518     return SDValue();
15519
15520   EVT VT = InVec.getValueType();
15521
15522   bool HasShuffleIntoBitcast = false;
15523   if (InVec.getOpcode() == ISD::BITCAST) {
15524     // Don't duplicate a load with other uses.
15525     if (!InVec.hasOneUse())
15526       return SDValue();
15527     EVT BCVT = InVec.getOperand(0).getValueType();
15528     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15529       return SDValue();
15530     InVec = InVec.getOperand(0);
15531     HasShuffleIntoBitcast = true;
15532   }
15533
15534   if (!isTargetShuffle(InVec.getOpcode()))
15535     return SDValue();
15536
15537   // Don't duplicate a load with other uses.
15538   if (!InVec.hasOneUse())
15539     return SDValue();
15540
15541   SmallVector<int, 16> ShuffleMask;
15542   bool UnaryShuffle;
15543   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15544                             UnaryShuffle))
15545     return SDValue();
15546
15547   // Select the input vector, guarding against out of range extract vector.
15548   unsigned NumElems = VT.getVectorNumElements();
15549   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15550   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15551   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15552                                          : InVec.getOperand(1);
15553
15554   // If inputs to shuffle are the same for both ops, then allow 2 uses
15555   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15556
15557   if (LdNode.getOpcode() == ISD::BITCAST) {
15558     // Don't duplicate a load with other uses.
15559     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15560       return SDValue();
15561
15562     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15563     LdNode = LdNode.getOperand(0);
15564   }
15565
15566   if (!ISD::isNormalLoad(LdNode.getNode()))
15567     return SDValue();
15568
15569   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15570
15571   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15572     return SDValue();
15573
15574   if (HasShuffleIntoBitcast) {
15575     // If there's a bitcast before the shuffle, check if the load type and
15576     // alignment is valid.
15577     unsigned Align = LN0->getAlignment();
15578     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15579     unsigned NewAlign = TLI.getDataLayout()->
15580       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15581
15582     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15583       return SDValue();
15584   }
15585
15586   // All checks match so transform back to vector_shuffle so that DAG combiner
15587   // can finish the job
15588   SDLoc dl(N);
15589
15590   // Create shuffle node taking into account the case that its a unary shuffle
15591   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15592   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15593                                  InVec.getOperand(0), Shuffle,
15594                                  &ShuffleMask[0]);
15595   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15596   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15597                      EltNo);
15598 }
15599
15600 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15601 /// generation and convert it from being a bunch of shuffles and extracts
15602 /// to a simple store and scalar loads to extract the elements.
15603 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15604                                          TargetLowering::DAGCombinerInfo &DCI) {
15605   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15606   if (NewOp.getNode())
15607     return NewOp;
15608
15609   SDValue InputVector = N->getOperand(0);
15610   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15611   // from mmx to v2i32 has a single usage.
15612   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15613       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15614       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15615     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15616                        N->getValueType(0),
15617                        InputVector.getNode()->getOperand(0));
15618
15619   // Only operate on vectors of 4 elements, where the alternative shuffling
15620   // gets to be more expensive.
15621   if (InputVector.getValueType() != MVT::v4i32)
15622     return SDValue();
15623
15624   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15625   // single use which is a sign-extend or zero-extend, and all elements are
15626   // used.
15627   SmallVector<SDNode *, 4> Uses;
15628   unsigned ExtractedElements = 0;
15629   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15630        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15631     if (UI.getUse().getResNo() != InputVector.getResNo())
15632       return SDValue();
15633
15634     SDNode *Extract = *UI;
15635     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15636       return SDValue();
15637
15638     if (Extract->getValueType(0) != MVT::i32)
15639       return SDValue();
15640     if (!Extract->hasOneUse())
15641       return SDValue();
15642     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15643         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15644       return SDValue();
15645     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15646       return SDValue();
15647
15648     // Record which element was extracted.
15649     ExtractedElements |=
15650       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15651
15652     Uses.push_back(Extract);
15653   }
15654
15655   // If not all the elements were used, this may not be worthwhile.
15656   if (ExtractedElements != 15)
15657     return SDValue();
15658
15659   // Ok, we've now decided to do the transformation.
15660   SDLoc dl(InputVector);
15661
15662   // Store the value to a temporary stack slot.
15663   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15664   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15665                             MachinePointerInfo(), false, false, 0);
15666
15667   // Replace each use (extract) with a load of the appropriate element.
15668   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15669        UE = Uses.end(); UI != UE; ++UI) {
15670     SDNode *Extract = *UI;
15671
15672     // cOMpute the element's address.
15673     SDValue Idx = Extract->getOperand(1);
15674     unsigned EltSize =
15675         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15676     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15677     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15678     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15679
15680     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15681                                      StackPtr, OffsetVal);
15682
15683     // Load the scalar.
15684     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15685                                      ScalarAddr, MachinePointerInfo(),
15686                                      false, false, false, 0);
15687
15688     // Replace the exact with the load.
15689     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15690   }
15691
15692   // The replacement was made in place; don't return anything.
15693   return SDValue();
15694 }
15695
15696 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15697 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15698                                    SDValue RHS, SelectionDAG &DAG,
15699                                    const X86Subtarget *Subtarget) {
15700   if (!VT.isVector())
15701     return 0;
15702
15703   switch (VT.getSimpleVT().SimpleTy) {
15704   default: return 0;
15705   case MVT::v32i8:
15706   case MVT::v16i16:
15707   case MVT::v8i32:
15708     if (!Subtarget->hasAVX2())
15709       return 0;
15710   case MVT::v16i8:
15711   case MVT::v8i16:
15712   case MVT::v4i32:
15713     if (!Subtarget->hasSSE2())
15714       return 0;
15715   }
15716
15717   // SSE2 has only a small subset of the operations.
15718   bool hasUnsigned = Subtarget->hasSSE41() ||
15719                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15720   bool hasSigned = Subtarget->hasSSE41() ||
15721                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15722
15723   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15724
15725   // Check for x CC y ? x : y.
15726   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15727       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15728     switch (CC) {
15729     default: break;
15730     case ISD::SETULT:
15731     case ISD::SETULE:
15732       return hasUnsigned ? X86ISD::UMIN : 0;
15733     case ISD::SETUGT:
15734     case ISD::SETUGE:
15735       return hasUnsigned ? X86ISD::UMAX : 0;
15736     case ISD::SETLT:
15737     case ISD::SETLE:
15738       return hasSigned ? X86ISD::SMIN : 0;
15739     case ISD::SETGT:
15740     case ISD::SETGE:
15741       return hasSigned ? X86ISD::SMAX : 0;
15742     }
15743   // Check for x CC y ? y : x -- a min/max with reversed arms.
15744   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15745              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15746     switch (CC) {
15747     default: break;
15748     case ISD::SETULT:
15749     case ISD::SETULE:
15750       return hasUnsigned ? X86ISD::UMAX : 0;
15751     case ISD::SETUGT:
15752     case ISD::SETUGE:
15753       return hasUnsigned ? X86ISD::UMIN : 0;
15754     case ISD::SETLT:
15755     case ISD::SETLE:
15756       return hasSigned ? X86ISD::SMAX : 0;
15757     case ISD::SETGT:
15758     case ISD::SETGE:
15759       return hasSigned ? X86ISD::SMIN : 0;
15760     }
15761   }
15762
15763   return 0;
15764 }
15765
15766 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15767 /// nodes.
15768 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15769                                     TargetLowering::DAGCombinerInfo &DCI,
15770                                     const X86Subtarget *Subtarget) {
15771   SDLoc DL(N);
15772   SDValue Cond = N->getOperand(0);
15773   // Get the LHS/RHS of the select.
15774   SDValue LHS = N->getOperand(1);
15775   SDValue RHS = N->getOperand(2);
15776   EVT VT = LHS.getValueType();
15777
15778   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15779   // instructions match the semantics of the common C idiom x<y?x:y but not
15780   // x<=y?x:y, because of how they handle negative zero (which can be
15781   // ignored in unsafe-math mode).
15782   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15783       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15784       (Subtarget->hasSSE2() ||
15785        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15786     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15787
15788     unsigned Opcode = 0;
15789     // Check for x CC y ? x : y.
15790     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15791         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15792       switch (CC) {
15793       default: break;
15794       case ISD::SETULT:
15795         // Converting this to a min would handle NaNs incorrectly, and swapping
15796         // the operands would cause it to handle comparisons between positive
15797         // and negative zero incorrectly.
15798         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15799           if (!DAG.getTarget().Options.UnsafeFPMath &&
15800               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15801             break;
15802           std::swap(LHS, RHS);
15803         }
15804         Opcode = X86ISD::FMIN;
15805         break;
15806       case ISD::SETOLE:
15807         // Converting this to a min would handle comparisons between positive
15808         // and negative zero incorrectly.
15809         if (!DAG.getTarget().Options.UnsafeFPMath &&
15810             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15811           break;
15812         Opcode = X86ISD::FMIN;
15813         break;
15814       case ISD::SETULE:
15815         // Converting this to a min would handle both negative zeros and NaNs
15816         // incorrectly, but we can swap the operands to fix both.
15817         std::swap(LHS, RHS);
15818       case ISD::SETOLT:
15819       case ISD::SETLT:
15820       case ISD::SETLE:
15821         Opcode = X86ISD::FMIN;
15822         break;
15823
15824       case ISD::SETOGE:
15825         // Converting this to a max would handle comparisons between positive
15826         // and negative zero incorrectly.
15827         if (!DAG.getTarget().Options.UnsafeFPMath &&
15828             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15829           break;
15830         Opcode = X86ISD::FMAX;
15831         break;
15832       case ISD::SETUGT:
15833         // Converting this to a max would handle NaNs incorrectly, and swapping
15834         // the operands would cause it to handle comparisons between positive
15835         // and negative zero incorrectly.
15836         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15837           if (!DAG.getTarget().Options.UnsafeFPMath &&
15838               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15839             break;
15840           std::swap(LHS, RHS);
15841         }
15842         Opcode = X86ISD::FMAX;
15843         break;
15844       case ISD::SETUGE:
15845         // Converting this to a max would handle both negative zeros and NaNs
15846         // incorrectly, but we can swap the operands to fix both.
15847         std::swap(LHS, RHS);
15848       case ISD::SETOGT:
15849       case ISD::SETGT:
15850       case ISD::SETGE:
15851         Opcode = X86ISD::FMAX;
15852         break;
15853       }
15854     // Check for x CC y ? y : x -- a min/max with reversed arms.
15855     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15856                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15857       switch (CC) {
15858       default: break;
15859       case ISD::SETOGE:
15860         // Converting this to a min would handle comparisons between positive
15861         // and negative zero incorrectly, and swapping the operands would
15862         // cause it to handle NaNs incorrectly.
15863         if (!DAG.getTarget().Options.UnsafeFPMath &&
15864             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15865           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15866             break;
15867           std::swap(LHS, RHS);
15868         }
15869         Opcode = X86ISD::FMIN;
15870         break;
15871       case ISD::SETUGT:
15872         // Converting this to a min would handle NaNs incorrectly.
15873         if (!DAG.getTarget().Options.UnsafeFPMath &&
15874             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15875           break;
15876         Opcode = X86ISD::FMIN;
15877         break;
15878       case ISD::SETUGE:
15879         // Converting this to a min would handle both negative zeros and NaNs
15880         // incorrectly, but we can swap the operands to fix both.
15881         std::swap(LHS, RHS);
15882       case ISD::SETOGT:
15883       case ISD::SETGT:
15884       case ISD::SETGE:
15885         Opcode = X86ISD::FMIN;
15886         break;
15887
15888       case ISD::SETULT:
15889         // Converting this to a max would handle NaNs incorrectly.
15890         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15891           break;
15892         Opcode = X86ISD::FMAX;
15893         break;
15894       case ISD::SETOLE:
15895         // Converting this to a max would handle comparisons between positive
15896         // and negative zero incorrectly, and swapping the operands would
15897         // cause it to handle NaNs incorrectly.
15898         if (!DAG.getTarget().Options.UnsafeFPMath &&
15899             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15900           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15901             break;
15902           std::swap(LHS, RHS);
15903         }
15904         Opcode = X86ISD::FMAX;
15905         break;
15906       case ISD::SETULE:
15907         // Converting this to a max would handle both negative zeros and NaNs
15908         // incorrectly, but we can swap the operands to fix both.
15909         std::swap(LHS, RHS);
15910       case ISD::SETOLT:
15911       case ISD::SETLT:
15912       case ISD::SETLE:
15913         Opcode = X86ISD::FMAX;
15914         break;
15915       }
15916     }
15917
15918     if (Opcode)
15919       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15920   }
15921
15922   // If this is a select between two integer constants, try to do some
15923   // optimizations.
15924   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15925     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15926       // Don't do this for crazy integer types.
15927       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15928         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15929         // so that TrueC (the true value) is larger than FalseC.
15930         bool NeedsCondInvert = false;
15931
15932         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15933             // Efficiently invertible.
15934             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15935              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15936               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15937           NeedsCondInvert = true;
15938           std::swap(TrueC, FalseC);
15939         }
15940
15941         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15942         if (FalseC->getAPIntValue() == 0 &&
15943             TrueC->getAPIntValue().isPowerOf2()) {
15944           if (NeedsCondInvert) // Invert the condition if needed.
15945             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15946                                DAG.getConstant(1, Cond.getValueType()));
15947
15948           // Zero extend the condition if needed.
15949           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15950
15951           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15952           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15953                              DAG.getConstant(ShAmt, MVT::i8));
15954         }
15955
15956         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15957         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15958           if (NeedsCondInvert) // Invert the condition if needed.
15959             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15960                                DAG.getConstant(1, Cond.getValueType()));
15961
15962           // Zero extend the condition if needed.
15963           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15964                              FalseC->getValueType(0), Cond);
15965           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15966                              SDValue(FalseC, 0));
15967         }
15968
15969         // Optimize cases that will turn into an LEA instruction.  This requires
15970         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15971         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15972           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15973           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15974
15975           bool isFastMultiplier = false;
15976           if (Diff < 10) {
15977             switch ((unsigned char)Diff) {
15978               default: break;
15979               case 1:  // result = add base, cond
15980               case 2:  // result = lea base(    , cond*2)
15981               case 3:  // result = lea base(cond, cond*2)
15982               case 4:  // result = lea base(    , cond*4)
15983               case 5:  // result = lea base(cond, cond*4)
15984               case 8:  // result = lea base(    , cond*8)
15985               case 9:  // result = lea base(cond, cond*8)
15986                 isFastMultiplier = true;
15987                 break;
15988             }
15989           }
15990
15991           if (isFastMultiplier) {
15992             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15993             if (NeedsCondInvert) // Invert the condition if needed.
15994               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15995                                  DAG.getConstant(1, Cond.getValueType()));
15996
15997             // Zero extend the condition if needed.
15998             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15999                                Cond);
16000             // Scale the condition by the difference.
16001             if (Diff != 1)
16002               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16003                                  DAG.getConstant(Diff, Cond.getValueType()));
16004
16005             // Add the base if non-zero.
16006             if (FalseC->getAPIntValue() != 0)
16007               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16008                                  SDValue(FalseC, 0));
16009             return Cond;
16010           }
16011         }
16012       }
16013   }
16014
16015   // Canonicalize max and min:
16016   // (x > y) ? x : y -> (x >= y) ? x : y
16017   // (x < y) ? x : y -> (x <= y) ? x : y
16018   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16019   // the need for an extra compare
16020   // against zero. e.g.
16021   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16022   // subl   %esi, %edi
16023   // testl  %edi, %edi
16024   // movl   $0, %eax
16025   // cmovgl %edi, %eax
16026   // =>
16027   // xorl   %eax, %eax
16028   // subl   %esi, $edi
16029   // cmovsl %eax, %edi
16030   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16031       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16032       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16033     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16034     switch (CC) {
16035     default: break;
16036     case ISD::SETLT:
16037     case ISD::SETGT: {
16038       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16039       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16040                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16041       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16042     }
16043     }
16044   }
16045
16046   // Match VSELECTs into subs with unsigned saturation.
16047   if (!DCI.isBeforeLegalize() &&
16048       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16049       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16050       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16051        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16052     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16053
16054     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16055     // left side invert the predicate to simplify logic below.
16056     SDValue Other;
16057     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16058       Other = RHS;
16059       CC = ISD::getSetCCInverse(CC, true);
16060     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16061       Other = LHS;
16062     }
16063
16064     if (Other.getNode() && Other->getNumOperands() == 2 &&
16065         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16066       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16067       SDValue CondRHS = Cond->getOperand(1);
16068
16069       // Look for a general sub with unsigned saturation first.
16070       // x >= y ? x-y : 0 --> subus x, y
16071       // x >  y ? x-y : 0 --> subus x, y
16072       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16073           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16074         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16075
16076       // If the RHS is a constant we have to reverse the const canonicalization.
16077       // x > C-1 ? x+-C : 0 --> subus x, C
16078       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16079           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16080         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16081         if (CondRHS.getConstantOperandVal(0) == -A-1)
16082           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16083                              DAG.getConstant(-A, VT));
16084       }
16085
16086       // Another special case: If C was a sign bit, the sub has been
16087       // canonicalized into a xor.
16088       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16089       //        it's safe to decanonicalize the xor?
16090       // x s< 0 ? x^C : 0 --> subus x, C
16091       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16092           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16093           isSplatVector(OpRHS.getNode())) {
16094         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16095         if (A.isSignBit())
16096           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16097       }
16098     }
16099   }
16100
16101   // Try to match a min/max vector operation.
16102   if (!DCI.isBeforeLegalize() &&
16103       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16104     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16105       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16106
16107   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16108   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16109       Cond.getOpcode() == ISD::SETCC) {
16110
16111     assert(Cond.getValueType().isVector() &&
16112            "vector select expects a vector selector!");
16113
16114     EVT IntVT = Cond.getValueType();
16115     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16116     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16117
16118     if (!TValIsAllOnes && !FValIsAllZeros) {
16119       // Try invert the condition if true value is not all 1s and false value
16120       // is not all 0s.
16121       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16122       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16123
16124       if (TValIsAllZeros || FValIsAllOnes) {
16125         SDValue CC = Cond.getOperand(2);
16126         ISD::CondCode NewCC =
16127           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16128                                Cond.getOperand(0).getValueType().isInteger());
16129         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16130         std::swap(LHS, RHS);
16131         TValIsAllOnes = FValIsAllOnes;
16132         FValIsAllZeros = TValIsAllZeros;
16133       }
16134     }
16135
16136     if (TValIsAllOnes || FValIsAllZeros) {
16137       SDValue Ret;
16138
16139       if (TValIsAllOnes && FValIsAllZeros)
16140         Ret = Cond;
16141       else if (TValIsAllOnes)
16142         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16143                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16144       else if (FValIsAllZeros)
16145         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16146                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16147
16148       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16149     }
16150   }
16151
16152   // If we know that this node is legal then we know that it is going to be
16153   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16154   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16155   // to simplify previous instructions.
16156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16157   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16158       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16159     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16160
16161     // Don't optimize vector selects that map to mask-registers.
16162     if (BitWidth == 1)
16163       return SDValue();
16164
16165     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16166     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16167
16168     APInt KnownZero, KnownOne;
16169     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16170                                           DCI.isBeforeLegalizeOps());
16171     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16172         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16173       DCI.CommitTargetLoweringOpt(TLO);
16174   }
16175
16176   return SDValue();
16177 }
16178
16179 // Check whether a boolean test is testing a boolean value generated by
16180 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16181 // code.
16182 //
16183 // Simplify the following patterns:
16184 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16185 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16186 // to (Op EFLAGS Cond)
16187 //
16188 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16189 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16190 // to (Op EFLAGS !Cond)
16191 //
16192 // where Op could be BRCOND or CMOV.
16193 //
16194 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16195   // Quit if not CMP and SUB with its value result used.
16196   if (Cmp.getOpcode() != X86ISD::CMP &&
16197       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16198       return SDValue();
16199
16200   // Quit if not used as a boolean value.
16201   if (CC != X86::COND_E && CC != X86::COND_NE)
16202     return SDValue();
16203
16204   // Check CMP operands. One of them should be 0 or 1 and the other should be
16205   // an SetCC or extended from it.
16206   SDValue Op1 = Cmp.getOperand(0);
16207   SDValue Op2 = Cmp.getOperand(1);
16208
16209   SDValue SetCC;
16210   const ConstantSDNode* C = 0;
16211   bool needOppositeCond = (CC == X86::COND_E);
16212   bool checkAgainstTrue = false; // Is it a comparison against 1?
16213
16214   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16215     SetCC = Op2;
16216   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16217     SetCC = Op1;
16218   else // Quit if all operands are not constants.
16219     return SDValue();
16220
16221   if (C->getZExtValue() == 1) {
16222     needOppositeCond = !needOppositeCond;
16223     checkAgainstTrue = true;
16224   } else if (C->getZExtValue() != 0)
16225     // Quit if the constant is neither 0 or 1.
16226     return SDValue();
16227
16228   bool truncatedToBoolWithAnd = false;
16229   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16230   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16231          SetCC.getOpcode() == ISD::TRUNCATE ||
16232          SetCC.getOpcode() == ISD::AND) {
16233     if (SetCC.getOpcode() == ISD::AND) {
16234       int OpIdx = -1;
16235       ConstantSDNode *CS;
16236       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16237           CS->getZExtValue() == 1)
16238         OpIdx = 1;
16239       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16240           CS->getZExtValue() == 1)
16241         OpIdx = 0;
16242       if (OpIdx == -1)
16243         break;
16244       SetCC = SetCC.getOperand(OpIdx);
16245       truncatedToBoolWithAnd = true;
16246     } else
16247       SetCC = SetCC.getOperand(0);
16248   }
16249
16250   switch (SetCC.getOpcode()) {
16251   case X86ISD::SETCC_CARRY:
16252     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16253     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16254     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16255     // truncated to i1 using 'and'.
16256     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16257       break;
16258     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16259            "Invalid use of SETCC_CARRY!");
16260     // FALL THROUGH
16261   case X86ISD::SETCC:
16262     // Set the condition code or opposite one if necessary.
16263     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16264     if (needOppositeCond)
16265       CC = X86::GetOppositeBranchCondition(CC);
16266     return SetCC.getOperand(1);
16267   case X86ISD::CMOV: {
16268     // Check whether false/true value has canonical one, i.e. 0 or 1.
16269     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16270     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16271     // Quit if true value is not a constant.
16272     if (!TVal)
16273       return SDValue();
16274     // Quit if false value is not a constant.
16275     if (!FVal) {
16276       SDValue Op = SetCC.getOperand(0);
16277       // Skip 'zext' or 'trunc' node.
16278       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16279           Op.getOpcode() == ISD::TRUNCATE)
16280         Op = Op.getOperand(0);
16281       // A special case for rdrand/rdseed, where 0 is set if false cond is
16282       // found.
16283       if ((Op.getOpcode() != X86ISD::RDRAND &&
16284            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16285         return SDValue();
16286     }
16287     // Quit if false value is not the constant 0 or 1.
16288     bool FValIsFalse = true;
16289     if (FVal && FVal->getZExtValue() != 0) {
16290       if (FVal->getZExtValue() != 1)
16291         return SDValue();
16292       // If FVal is 1, opposite cond is needed.
16293       needOppositeCond = !needOppositeCond;
16294       FValIsFalse = false;
16295     }
16296     // Quit if TVal is not the constant opposite of FVal.
16297     if (FValIsFalse && TVal->getZExtValue() != 1)
16298       return SDValue();
16299     if (!FValIsFalse && TVal->getZExtValue() != 0)
16300       return SDValue();
16301     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16302     if (needOppositeCond)
16303       CC = X86::GetOppositeBranchCondition(CC);
16304     return SetCC.getOperand(3);
16305   }
16306   }
16307
16308   return SDValue();
16309 }
16310
16311 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16312 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16313                                   TargetLowering::DAGCombinerInfo &DCI,
16314                                   const X86Subtarget *Subtarget) {
16315   SDLoc DL(N);
16316
16317   // If the flag operand isn't dead, don't touch this CMOV.
16318   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16319     return SDValue();
16320
16321   SDValue FalseOp = N->getOperand(0);
16322   SDValue TrueOp = N->getOperand(1);
16323   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16324   SDValue Cond = N->getOperand(3);
16325
16326   if (CC == X86::COND_E || CC == X86::COND_NE) {
16327     switch (Cond.getOpcode()) {
16328     default: break;
16329     case X86ISD::BSR:
16330     case X86ISD::BSF:
16331       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16332       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16333         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16334     }
16335   }
16336
16337   SDValue Flags;
16338
16339   Flags = checkBoolTestSetCCCombine(Cond, CC);
16340   if (Flags.getNode() &&
16341       // Extra check as FCMOV only supports a subset of X86 cond.
16342       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16343     SDValue Ops[] = { FalseOp, TrueOp,
16344                       DAG.getConstant(CC, MVT::i8), Flags };
16345     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16346                        Ops, array_lengthof(Ops));
16347   }
16348
16349   // If this is a select between two integer constants, try to do some
16350   // optimizations.  Note that the operands are ordered the opposite of SELECT
16351   // operands.
16352   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16353     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16354       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16355       // larger than FalseC (the false value).
16356       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16357         CC = X86::GetOppositeBranchCondition(CC);
16358         std::swap(TrueC, FalseC);
16359         std::swap(TrueOp, FalseOp);
16360       }
16361
16362       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16363       // This is efficient for any integer data type (including i8/i16) and
16364       // shift amount.
16365       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16366         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16367                            DAG.getConstant(CC, MVT::i8), Cond);
16368
16369         // Zero extend the condition if needed.
16370         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16371
16372         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16373         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16374                            DAG.getConstant(ShAmt, MVT::i8));
16375         if (N->getNumValues() == 2)  // Dead flag value?
16376           return DCI.CombineTo(N, Cond, SDValue());
16377         return Cond;
16378       }
16379
16380       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16381       // for any integer data type, including i8/i16.
16382       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16383         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16384                            DAG.getConstant(CC, MVT::i8), Cond);
16385
16386         // Zero extend the condition if needed.
16387         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16388                            FalseC->getValueType(0), Cond);
16389         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16390                            SDValue(FalseC, 0));
16391
16392         if (N->getNumValues() == 2)  // Dead flag value?
16393           return DCI.CombineTo(N, Cond, SDValue());
16394         return Cond;
16395       }
16396
16397       // Optimize cases that will turn into an LEA instruction.  This requires
16398       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16399       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16400         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16401         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16402
16403         bool isFastMultiplier = false;
16404         if (Diff < 10) {
16405           switch ((unsigned char)Diff) {
16406           default: break;
16407           case 1:  // result = add base, cond
16408           case 2:  // result = lea base(    , cond*2)
16409           case 3:  // result = lea base(cond, cond*2)
16410           case 4:  // result = lea base(    , cond*4)
16411           case 5:  // result = lea base(cond, cond*4)
16412           case 8:  // result = lea base(    , cond*8)
16413           case 9:  // result = lea base(cond, cond*8)
16414             isFastMultiplier = true;
16415             break;
16416           }
16417         }
16418
16419         if (isFastMultiplier) {
16420           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16421           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16422                              DAG.getConstant(CC, MVT::i8), Cond);
16423           // Zero extend the condition if needed.
16424           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16425                              Cond);
16426           // Scale the condition by the difference.
16427           if (Diff != 1)
16428             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16429                                DAG.getConstant(Diff, Cond.getValueType()));
16430
16431           // Add the base if non-zero.
16432           if (FalseC->getAPIntValue() != 0)
16433             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16434                                SDValue(FalseC, 0));
16435           if (N->getNumValues() == 2)  // Dead flag value?
16436             return DCI.CombineTo(N, Cond, SDValue());
16437           return Cond;
16438         }
16439       }
16440     }
16441   }
16442
16443   // Handle these cases:
16444   //   (select (x != c), e, c) -> select (x != c), e, x),
16445   //   (select (x == c), c, e) -> select (x == c), x, e)
16446   // where the c is an integer constant, and the "select" is the combination
16447   // of CMOV and CMP.
16448   //
16449   // The rationale for this change is that the conditional-move from a constant
16450   // needs two instructions, however, conditional-move from a register needs
16451   // only one instruction.
16452   //
16453   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16454   //  some instruction-combining opportunities. This opt needs to be
16455   //  postponed as late as possible.
16456   //
16457   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16458     // the DCI.xxxx conditions are provided to postpone the optimization as
16459     // late as possible.
16460
16461     ConstantSDNode *CmpAgainst = 0;
16462     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16463         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16464         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16465
16466       if (CC == X86::COND_NE &&
16467           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16468         CC = X86::GetOppositeBranchCondition(CC);
16469         std::swap(TrueOp, FalseOp);
16470       }
16471
16472       if (CC == X86::COND_E &&
16473           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16474         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16475                           DAG.getConstant(CC, MVT::i8), Cond };
16476         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16477                            array_lengthof(Ops));
16478       }
16479     }
16480   }
16481
16482   return SDValue();
16483 }
16484
16485 /// PerformMulCombine - Optimize a single multiply with constant into two
16486 /// in order to implement it with two cheaper instructions, e.g.
16487 /// LEA + SHL, LEA + LEA.
16488 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16489                                  TargetLowering::DAGCombinerInfo &DCI) {
16490   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16491     return SDValue();
16492
16493   EVT VT = N->getValueType(0);
16494   if (VT != MVT::i64)
16495     return SDValue();
16496
16497   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16498   if (!C)
16499     return SDValue();
16500   uint64_t MulAmt = C->getZExtValue();
16501   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16502     return SDValue();
16503
16504   uint64_t MulAmt1 = 0;
16505   uint64_t MulAmt2 = 0;
16506   if ((MulAmt % 9) == 0) {
16507     MulAmt1 = 9;
16508     MulAmt2 = MulAmt / 9;
16509   } else if ((MulAmt % 5) == 0) {
16510     MulAmt1 = 5;
16511     MulAmt2 = MulAmt / 5;
16512   } else if ((MulAmt % 3) == 0) {
16513     MulAmt1 = 3;
16514     MulAmt2 = MulAmt / 3;
16515   }
16516   if (MulAmt2 &&
16517       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16518     SDLoc DL(N);
16519
16520     if (isPowerOf2_64(MulAmt2) &&
16521         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16522       // If second multiplifer is pow2, issue it first. We want the multiply by
16523       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16524       // is an add.
16525       std::swap(MulAmt1, MulAmt2);
16526
16527     SDValue NewMul;
16528     if (isPowerOf2_64(MulAmt1))
16529       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16530                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16531     else
16532       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16533                            DAG.getConstant(MulAmt1, VT));
16534
16535     if (isPowerOf2_64(MulAmt2))
16536       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16537                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16538     else
16539       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16540                            DAG.getConstant(MulAmt2, VT));
16541
16542     // Do not add new nodes to DAG combiner worklist.
16543     DCI.CombineTo(N, NewMul, false);
16544   }
16545   return SDValue();
16546 }
16547
16548 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16549   SDValue N0 = N->getOperand(0);
16550   SDValue N1 = N->getOperand(1);
16551   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16552   EVT VT = N0.getValueType();
16553
16554   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16555   // since the result of setcc_c is all zero's or all ones.
16556   if (VT.isInteger() && !VT.isVector() &&
16557       N1C && N0.getOpcode() == ISD::AND &&
16558       N0.getOperand(1).getOpcode() == ISD::Constant) {
16559     SDValue N00 = N0.getOperand(0);
16560     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16561         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16562           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16563          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16564       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16565       APInt ShAmt = N1C->getAPIntValue();
16566       Mask = Mask.shl(ShAmt);
16567       if (Mask != 0)
16568         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16569                            N00, DAG.getConstant(Mask, VT));
16570     }
16571   }
16572
16573   // Hardware support for vector shifts is sparse which makes us scalarize the
16574   // vector operations in many cases. Also, on sandybridge ADD is faster than
16575   // shl.
16576   // (shl V, 1) -> add V,V
16577   if (isSplatVector(N1.getNode())) {
16578     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16579     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16580     // We shift all of the values by one. In many cases we do not have
16581     // hardware support for this operation. This is better expressed as an ADD
16582     // of two values.
16583     if (N1C && (1 == N1C->getZExtValue())) {
16584       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16585     }
16586   }
16587
16588   return SDValue();
16589 }
16590
16591 /// \brief Returns a vector of 0s if the node in input is a vector logical
16592 /// shift by a constant amount which is known to be bigger than or equal 
16593 /// to the vector element size in bits.
16594 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16595                                       const X86Subtarget *Subtarget) {
16596   EVT VT = N->getValueType(0);
16597
16598   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16599       (!Subtarget->hasInt256() ||
16600        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16601     return SDValue();
16602
16603   SDValue Amt = N->getOperand(1);
16604   SDLoc DL(N);
16605   if (isSplatVector(Amt.getNode())) {
16606     SDValue SclrAmt = Amt->getOperand(0);
16607     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16608       APInt ShiftAmt = C->getAPIntValue();
16609       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16610
16611       // SSE2/AVX2 logical shifts always return a vector of 0s
16612       // if the shift amount is bigger than or equal to 
16613       // the element size. The constant shift amount will be
16614       // encoded as a 8-bit immediate.
16615       if (ShiftAmt.trunc(8).uge(MaxAmount))
16616         return getZeroVector(VT, Subtarget, DAG, DL);
16617     }
16618   }
16619
16620   return SDValue();
16621 }
16622
16623 /// PerformShiftCombine - Combine shifts.
16624 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16625                                    TargetLowering::DAGCombinerInfo &DCI,
16626                                    const X86Subtarget *Subtarget) {
16627   if (N->getOpcode() == ISD::SHL) {
16628     SDValue V = PerformSHLCombine(N, DAG);
16629     if (V.getNode()) return V;
16630   }
16631
16632   if (N->getOpcode() != ISD::SRA) {
16633     // Try to fold this logical shift into a zero vector.
16634     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16635     if (V.getNode()) return V;
16636   }
16637
16638   return SDValue();
16639 }
16640
16641 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16642 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16643 // and friends.  Likewise for OR -> CMPNEQSS.
16644 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16645                             TargetLowering::DAGCombinerInfo &DCI,
16646                             const X86Subtarget *Subtarget) {
16647   unsigned opcode;
16648
16649   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16650   // we're requiring SSE2 for both.
16651   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16652     SDValue N0 = N->getOperand(0);
16653     SDValue N1 = N->getOperand(1);
16654     SDValue CMP0 = N0->getOperand(1);
16655     SDValue CMP1 = N1->getOperand(1);
16656     SDLoc DL(N);
16657
16658     // The SETCCs should both refer to the same CMP.
16659     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16660       return SDValue();
16661
16662     SDValue CMP00 = CMP0->getOperand(0);
16663     SDValue CMP01 = CMP0->getOperand(1);
16664     EVT     VT    = CMP00.getValueType();
16665
16666     if (VT == MVT::f32 || VT == MVT::f64) {
16667       bool ExpectingFlags = false;
16668       // Check for any users that want flags:
16669       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16670            !ExpectingFlags && UI != UE; ++UI)
16671         switch (UI->getOpcode()) {
16672         default:
16673         case ISD::BR_CC:
16674         case ISD::BRCOND:
16675         case ISD::SELECT:
16676           ExpectingFlags = true;
16677           break;
16678         case ISD::CopyToReg:
16679         case ISD::SIGN_EXTEND:
16680         case ISD::ZERO_EXTEND:
16681         case ISD::ANY_EXTEND:
16682           break;
16683         }
16684
16685       if (!ExpectingFlags) {
16686         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16687         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16688
16689         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16690           X86::CondCode tmp = cc0;
16691           cc0 = cc1;
16692           cc1 = tmp;
16693         }
16694
16695         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16696             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16697           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16698           X86ISD::NodeType NTOperator = is64BitFP ?
16699             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16700           // FIXME: need symbolic constants for these magic numbers.
16701           // See X86ATTInstPrinter.cpp:printSSECC().
16702           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16703           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16704                                               DAG.getConstant(x86cc, MVT::i8));
16705           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16706                                               OnesOrZeroesF);
16707           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16708                                       DAG.getConstant(1, MVT::i32));
16709           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16710           return OneBitOfTruth;
16711         }
16712       }
16713     }
16714   }
16715   return SDValue();
16716 }
16717
16718 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16719 /// so it can be folded inside ANDNP.
16720 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16721   EVT VT = N->getValueType(0);
16722
16723   // Match direct AllOnes for 128 and 256-bit vectors
16724   if (ISD::isBuildVectorAllOnes(N))
16725     return true;
16726
16727   // Look through a bit convert.
16728   if (N->getOpcode() == ISD::BITCAST)
16729     N = N->getOperand(0).getNode();
16730
16731   // Sometimes the operand may come from a insert_subvector building a 256-bit
16732   // allones vector
16733   if (VT.is256BitVector() &&
16734       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16735     SDValue V1 = N->getOperand(0);
16736     SDValue V2 = N->getOperand(1);
16737
16738     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16739         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16740         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16741         ISD::isBuildVectorAllOnes(V2.getNode()))
16742       return true;
16743   }
16744
16745   return false;
16746 }
16747
16748 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16749 // register. In most cases we actually compare or select YMM-sized registers
16750 // and mixing the two types creates horrible code. This method optimizes
16751 // some of the transition sequences.
16752 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16753                                  TargetLowering::DAGCombinerInfo &DCI,
16754                                  const X86Subtarget *Subtarget) {
16755   EVT VT = N->getValueType(0);
16756   if (!VT.is256BitVector())
16757     return SDValue();
16758
16759   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16760           N->getOpcode() == ISD::ZERO_EXTEND ||
16761           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16762
16763   SDValue Narrow = N->getOperand(0);
16764   EVT NarrowVT = Narrow->getValueType(0);
16765   if (!NarrowVT.is128BitVector())
16766     return SDValue();
16767
16768   if (Narrow->getOpcode() != ISD::XOR &&
16769       Narrow->getOpcode() != ISD::AND &&
16770       Narrow->getOpcode() != ISD::OR)
16771     return SDValue();
16772
16773   SDValue N0  = Narrow->getOperand(0);
16774   SDValue N1  = Narrow->getOperand(1);
16775   SDLoc DL(Narrow);
16776
16777   // The Left side has to be a trunc.
16778   if (N0.getOpcode() != ISD::TRUNCATE)
16779     return SDValue();
16780
16781   // The type of the truncated inputs.
16782   EVT WideVT = N0->getOperand(0)->getValueType(0);
16783   if (WideVT != VT)
16784     return SDValue();
16785
16786   // The right side has to be a 'trunc' or a constant vector.
16787   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16788   bool RHSConst = (isSplatVector(N1.getNode()) &&
16789                    isa<ConstantSDNode>(N1->getOperand(0)));
16790   if (!RHSTrunc && !RHSConst)
16791     return SDValue();
16792
16793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16794
16795   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16796     return SDValue();
16797
16798   // Set N0 and N1 to hold the inputs to the new wide operation.
16799   N0 = N0->getOperand(0);
16800   if (RHSConst) {
16801     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16802                      N1->getOperand(0));
16803     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16804     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16805   } else if (RHSTrunc) {
16806     N1 = N1->getOperand(0);
16807   }
16808
16809   // Generate the wide operation.
16810   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16811   unsigned Opcode = N->getOpcode();
16812   switch (Opcode) {
16813   case ISD::ANY_EXTEND:
16814     return Op;
16815   case ISD::ZERO_EXTEND: {
16816     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16817     APInt Mask = APInt::getAllOnesValue(InBits);
16818     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16819     return DAG.getNode(ISD::AND, DL, VT,
16820                        Op, DAG.getConstant(Mask, VT));
16821   }
16822   case ISD::SIGN_EXTEND:
16823     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16824                        Op, DAG.getValueType(NarrowVT));
16825   default:
16826     llvm_unreachable("Unexpected opcode");
16827   }
16828 }
16829
16830 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16831                                  TargetLowering::DAGCombinerInfo &DCI,
16832                                  const X86Subtarget *Subtarget) {
16833   EVT VT = N->getValueType(0);
16834   if (DCI.isBeforeLegalizeOps())
16835     return SDValue();
16836
16837   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16838   if (R.getNode())
16839     return R;
16840
16841   // Create BLSI, and BLSR instructions
16842   // BLSI is X & (-X)
16843   // BLSR is X & (X-1)
16844   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16845     SDValue N0 = N->getOperand(0);
16846     SDValue N1 = N->getOperand(1);
16847     SDLoc DL(N);
16848
16849     // Check LHS for neg
16850     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16851         isZero(N0.getOperand(0)))
16852       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16853
16854     // Check RHS for neg
16855     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16856         isZero(N1.getOperand(0)))
16857       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16858
16859     // Check LHS for X-1
16860     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16861         isAllOnes(N0.getOperand(1)))
16862       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16863
16864     // Check RHS for X-1
16865     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16866         isAllOnes(N1.getOperand(1)))
16867       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16868
16869     return SDValue();
16870   }
16871
16872   // Want to form ANDNP nodes:
16873   // 1) In the hopes of then easily combining them with OR and AND nodes
16874   //    to form PBLEND/PSIGN.
16875   // 2) To match ANDN packed intrinsics
16876   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16877     return SDValue();
16878
16879   SDValue N0 = N->getOperand(0);
16880   SDValue N1 = N->getOperand(1);
16881   SDLoc DL(N);
16882
16883   // Check LHS for vnot
16884   if (N0.getOpcode() == ISD::XOR &&
16885       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16886       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16887     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16888
16889   // Check RHS for vnot
16890   if (N1.getOpcode() == ISD::XOR &&
16891       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16892       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16893     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16894
16895   return SDValue();
16896 }
16897
16898 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16899                                 TargetLowering::DAGCombinerInfo &DCI,
16900                                 const X86Subtarget *Subtarget) {
16901   EVT VT = N->getValueType(0);
16902   if (DCI.isBeforeLegalizeOps())
16903     return SDValue();
16904
16905   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16906   if (R.getNode())
16907     return R;
16908
16909   SDValue N0 = N->getOperand(0);
16910   SDValue N1 = N->getOperand(1);
16911
16912   // look for psign/blend
16913   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16914     if (!Subtarget->hasSSSE3() ||
16915         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16916       return SDValue();
16917
16918     // Canonicalize pandn to RHS
16919     if (N0.getOpcode() == X86ISD::ANDNP)
16920       std::swap(N0, N1);
16921     // or (and (m, y), (pandn m, x))
16922     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16923       SDValue Mask = N1.getOperand(0);
16924       SDValue X    = N1.getOperand(1);
16925       SDValue Y;
16926       if (N0.getOperand(0) == Mask)
16927         Y = N0.getOperand(1);
16928       if (N0.getOperand(1) == Mask)
16929         Y = N0.getOperand(0);
16930
16931       // Check to see if the mask appeared in both the AND and ANDNP and
16932       if (!Y.getNode())
16933         return SDValue();
16934
16935       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16936       // Look through mask bitcast.
16937       if (Mask.getOpcode() == ISD::BITCAST)
16938         Mask = Mask.getOperand(0);
16939       if (X.getOpcode() == ISD::BITCAST)
16940         X = X.getOperand(0);
16941       if (Y.getOpcode() == ISD::BITCAST)
16942         Y = Y.getOperand(0);
16943
16944       EVT MaskVT = Mask.getValueType();
16945
16946       // Validate that the Mask operand is a vector sra node.
16947       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16948       // there is no psrai.b
16949       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16950       unsigned SraAmt = ~0;
16951       if (Mask.getOpcode() == ISD::SRA) {
16952         SDValue Amt = Mask.getOperand(1);
16953         if (isSplatVector(Amt.getNode())) {
16954           SDValue SclrAmt = Amt->getOperand(0);
16955           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16956             SraAmt = C->getZExtValue();
16957         }
16958       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16959         SDValue SraC = Mask.getOperand(1);
16960         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16961       }
16962       if ((SraAmt + 1) != EltBits)
16963         return SDValue();
16964
16965       SDLoc DL(N);
16966
16967       // Now we know we at least have a plendvb with the mask val.  See if
16968       // we can form a psignb/w/d.
16969       // psign = x.type == y.type == mask.type && y = sub(0, x);
16970       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16971           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16972           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16973         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16974                "Unsupported VT for PSIGN");
16975         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16976         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16977       }
16978       // PBLENDVB only available on SSE 4.1
16979       if (!Subtarget->hasSSE41())
16980         return SDValue();
16981
16982       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16983
16984       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16985       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16986       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16987       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16988       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16989     }
16990   }
16991
16992   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16993     return SDValue();
16994
16995   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16996   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16997     std::swap(N0, N1);
16998   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16999     return SDValue();
17000   if (!N0.hasOneUse() || !N1.hasOneUse())
17001     return SDValue();
17002
17003   SDValue ShAmt0 = N0.getOperand(1);
17004   if (ShAmt0.getValueType() != MVT::i8)
17005     return SDValue();
17006   SDValue ShAmt1 = N1.getOperand(1);
17007   if (ShAmt1.getValueType() != MVT::i8)
17008     return SDValue();
17009   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17010     ShAmt0 = ShAmt0.getOperand(0);
17011   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17012     ShAmt1 = ShAmt1.getOperand(0);
17013
17014   SDLoc DL(N);
17015   unsigned Opc = X86ISD::SHLD;
17016   SDValue Op0 = N0.getOperand(0);
17017   SDValue Op1 = N1.getOperand(0);
17018   if (ShAmt0.getOpcode() == ISD::SUB) {
17019     Opc = X86ISD::SHRD;
17020     std::swap(Op0, Op1);
17021     std::swap(ShAmt0, ShAmt1);
17022   }
17023
17024   unsigned Bits = VT.getSizeInBits();
17025   if (ShAmt1.getOpcode() == ISD::SUB) {
17026     SDValue Sum = ShAmt1.getOperand(0);
17027     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17028       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17029       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17030         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17031       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17032         return DAG.getNode(Opc, DL, VT,
17033                            Op0, Op1,
17034                            DAG.getNode(ISD::TRUNCATE, DL,
17035                                        MVT::i8, ShAmt0));
17036     }
17037   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17038     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17039     if (ShAmt0C &&
17040         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17041       return DAG.getNode(Opc, DL, VT,
17042                          N0.getOperand(0), N1.getOperand(0),
17043                          DAG.getNode(ISD::TRUNCATE, DL,
17044                                        MVT::i8, ShAmt0));
17045   }
17046
17047   return SDValue();
17048 }
17049
17050 // Generate NEG and CMOV for integer abs.
17051 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17052   EVT VT = N->getValueType(0);
17053
17054   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17055   // 8-bit integer abs to NEG and CMOV.
17056   if (VT.isInteger() && VT.getSizeInBits() == 8)
17057     return SDValue();
17058
17059   SDValue N0 = N->getOperand(0);
17060   SDValue N1 = N->getOperand(1);
17061   SDLoc DL(N);
17062
17063   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17064   // and change it to SUB and CMOV.
17065   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17066       N0.getOpcode() == ISD::ADD &&
17067       N0.getOperand(1) == N1 &&
17068       N1.getOpcode() == ISD::SRA &&
17069       N1.getOperand(0) == N0.getOperand(0))
17070     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17071       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17072         // Generate SUB & CMOV.
17073         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17074                                   DAG.getConstant(0, VT), N0.getOperand(0));
17075
17076         SDValue Ops[] = { N0.getOperand(0), Neg,
17077                           DAG.getConstant(X86::COND_GE, MVT::i8),
17078                           SDValue(Neg.getNode(), 1) };
17079         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17080                            Ops, array_lengthof(Ops));
17081       }
17082   return SDValue();
17083 }
17084
17085 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17086 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17087                                  TargetLowering::DAGCombinerInfo &DCI,
17088                                  const X86Subtarget *Subtarget) {
17089   EVT VT = N->getValueType(0);
17090   if (DCI.isBeforeLegalizeOps())
17091     return SDValue();
17092
17093   if (Subtarget->hasCMov()) {
17094     SDValue RV = performIntegerAbsCombine(N, DAG);
17095     if (RV.getNode())
17096       return RV;
17097   }
17098
17099   // Try forming BMI if it is available.
17100   if (!Subtarget->hasBMI())
17101     return SDValue();
17102
17103   if (VT != MVT::i32 && VT != MVT::i64)
17104     return SDValue();
17105
17106   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17107
17108   // Create BLSMSK instructions by finding X ^ (X-1)
17109   SDValue N0 = N->getOperand(0);
17110   SDValue N1 = N->getOperand(1);
17111   SDLoc DL(N);
17112
17113   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17114       isAllOnes(N0.getOperand(1)))
17115     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17116
17117   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17118       isAllOnes(N1.getOperand(1)))
17119     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17120
17121   return SDValue();
17122 }
17123
17124 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17125 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17126                                   TargetLowering::DAGCombinerInfo &DCI,
17127                                   const X86Subtarget *Subtarget) {
17128   LoadSDNode *Ld = cast<LoadSDNode>(N);
17129   EVT RegVT = Ld->getValueType(0);
17130   EVT MemVT = Ld->getMemoryVT();
17131   SDLoc dl(Ld);
17132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17133   unsigned RegSz = RegVT.getSizeInBits();
17134
17135   // On Sandybridge unaligned 256bit loads are inefficient.
17136   ISD::LoadExtType Ext = Ld->getExtensionType();
17137   unsigned Alignment = Ld->getAlignment();
17138   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17139   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17140       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17141     unsigned NumElems = RegVT.getVectorNumElements();
17142     if (NumElems < 2)
17143       return SDValue();
17144
17145     SDValue Ptr = Ld->getBasePtr();
17146     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17147
17148     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17149                                   NumElems/2);
17150     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17151                                 Ld->getPointerInfo(), Ld->isVolatile(),
17152                                 Ld->isNonTemporal(), Ld->isInvariant(),
17153                                 Alignment);
17154     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17155     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17156                                 Ld->getPointerInfo(), Ld->isVolatile(),
17157                                 Ld->isNonTemporal(), Ld->isInvariant(),
17158                                 std::min(16U, Alignment));
17159     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17160                              Load1.getValue(1),
17161                              Load2.getValue(1));
17162
17163     SDValue NewVec = DAG.getUNDEF(RegVT);
17164     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17165     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17166     return DCI.CombineTo(N, NewVec, TF, true);
17167   }
17168
17169   // If this is a vector EXT Load then attempt to optimize it using a
17170   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17171   // expansion is still better than scalar code.
17172   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17173   // emit a shuffle and a arithmetic shift.
17174   // TODO: It is possible to support ZExt by zeroing the undef values
17175   // during the shuffle phase or after the shuffle.
17176   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17177       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17178     assert(MemVT != RegVT && "Cannot extend to the same type");
17179     assert(MemVT.isVector() && "Must load a vector from memory");
17180
17181     unsigned NumElems = RegVT.getVectorNumElements();
17182     unsigned MemSz = MemVT.getSizeInBits();
17183     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17184
17185     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17186       return SDValue();
17187
17188     // All sizes must be a power of two.
17189     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17190       return SDValue();
17191
17192     // Attempt to load the original value using scalar loads.
17193     // Find the largest scalar type that divides the total loaded size.
17194     MVT SclrLoadTy = MVT::i8;
17195     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17196          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17197       MVT Tp = (MVT::SimpleValueType)tp;
17198       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17199         SclrLoadTy = Tp;
17200       }
17201     }
17202
17203     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17204     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17205         (64 <= MemSz))
17206       SclrLoadTy = MVT::f64;
17207
17208     // Calculate the number of scalar loads that we need to perform
17209     // in order to load our vector from memory.
17210     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17211     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17212       return SDValue();
17213
17214     unsigned loadRegZize = RegSz;
17215     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17216       loadRegZize /= 2;
17217
17218     // Represent our vector as a sequence of elements which are the
17219     // largest scalar that we can load.
17220     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17221       loadRegZize/SclrLoadTy.getSizeInBits());
17222
17223     // Represent the data using the same element type that is stored in
17224     // memory. In practice, we ''widen'' MemVT.
17225     EVT WideVecVT =
17226           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17227                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17228
17229     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17230       "Invalid vector type");
17231
17232     // We can't shuffle using an illegal type.
17233     if (!TLI.isTypeLegal(WideVecVT))
17234       return SDValue();
17235
17236     SmallVector<SDValue, 8> Chains;
17237     SDValue Ptr = Ld->getBasePtr();
17238     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17239                                         TLI.getPointerTy());
17240     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17241
17242     for (unsigned i = 0; i < NumLoads; ++i) {
17243       // Perform a single load.
17244       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17245                                        Ptr, Ld->getPointerInfo(),
17246                                        Ld->isVolatile(), Ld->isNonTemporal(),
17247                                        Ld->isInvariant(), Ld->getAlignment());
17248       Chains.push_back(ScalarLoad.getValue(1));
17249       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17250       // another round of DAGCombining.
17251       if (i == 0)
17252         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17253       else
17254         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17255                           ScalarLoad, DAG.getIntPtrConstant(i));
17256
17257       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17258     }
17259
17260     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17261                                Chains.size());
17262
17263     // Bitcast the loaded value to a vector of the original element type, in
17264     // the size of the target vector type.
17265     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17266     unsigned SizeRatio = RegSz/MemSz;
17267
17268     if (Ext == ISD::SEXTLOAD) {
17269       // If we have SSE4.1 we can directly emit a VSEXT node.
17270       if (Subtarget->hasSSE41()) {
17271         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17272         return DCI.CombineTo(N, Sext, TF, true);
17273       }
17274
17275       // Otherwise we'll shuffle the small elements in the high bits of the
17276       // larger type and perform an arithmetic shift. If the shift is not legal
17277       // it's better to scalarize.
17278       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17279         return SDValue();
17280
17281       // Redistribute the loaded elements into the different locations.
17282       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17283       for (unsigned i = 0; i != NumElems; ++i)
17284         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17285
17286       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17287                                            DAG.getUNDEF(WideVecVT),
17288                                            &ShuffleVec[0]);
17289
17290       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17291
17292       // Build the arithmetic shift.
17293       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17294                      MemVT.getVectorElementType().getSizeInBits();
17295       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17296                           DAG.getConstant(Amt, RegVT));
17297
17298       return DCI.CombineTo(N, Shuff, TF, true);
17299     }
17300
17301     // Redistribute the loaded elements into the different locations.
17302     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17303     for (unsigned i = 0; i != NumElems; ++i)
17304       ShuffleVec[i*SizeRatio] = i;
17305
17306     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17307                                          DAG.getUNDEF(WideVecVT),
17308                                          &ShuffleVec[0]);
17309
17310     // Bitcast to the requested type.
17311     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17312     // Replace the original load with the new sequence
17313     // and return the new chain.
17314     return DCI.CombineTo(N, Shuff, TF, true);
17315   }
17316
17317   return SDValue();
17318 }
17319
17320 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17321 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17322                                    const X86Subtarget *Subtarget) {
17323   StoreSDNode *St = cast<StoreSDNode>(N);
17324   EVT VT = St->getValue().getValueType();
17325   EVT StVT = St->getMemoryVT();
17326   SDLoc dl(St);
17327   SDValue StoredVal = St->getOperand(1);
17328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17329
17330   // If we are saving a concatenation of two XMM registers, perform two stores.
17331   // On Sandy Bridge, 256-bit memory operations are executed by two
17332   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17333   // memory  operation.
17334   unsigned Alignment = St->getAlignment();
17335   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17336   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17337       StVT == VT && !IsAligned) {
17338     unsigned NumElems = VT.getVectorNumElements();
17339     if (NumElems < 2)
17340       return SDValue();
17341
17342     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17343     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17344
17345     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17346     SDValue Ptr0 = St->getBasePtr();
17347     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17348
17349     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17350                                 St->getPointerInfo(), St->isVolatile(),
17351                                 St->isNonTemporal(), Alignment);
17352     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17353                                 St->getPointerInfo(), St->isVolatile(),
17354                                 St->isNonTemporal(),
17355                                 std::min(16U, Alignment));
17356     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17357   }
17358
17359   // Optimize trunc store (of multiple scalars) to shuffle and store.
17360   // First, pack all of the elements in one place. Next, store to memory
17361   // in fewer chunks.
17362   if (St->isTruncatingStore() && VT.isVector()) {
17363     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17364     unsigned NumElems = VT.getVectorNumElements();
17365     assert(StVT != VT && "Cannot truncate to the same type");
17366     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17367     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17368
17369     // From, To sizes and ElemCount must be pow of two
17370     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17371     // We are going to use the original vector elt for storing.
17372     // Accumulated smaller vector elements must be a multiple of the store size.
17373     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17374
17375     unsigned SizeRatio  = FromSz / ToSz;
17376
17377     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17378
17379     // Create a type on which we perform the shuffle
17380     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17381             StVT.getScalarType(), NumElems*SizeRatio);
17382
17383     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17384
17385     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17386     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17387     for (unsigned i = 0; i != NumElems; ++i)
17388       ShuffleVec[i] = i * SizeRatio;
17389
17390     // Can't shuffle using an illegal type.
17391     if (!TLI.isTypeLegal(WideVecVT))
17392       return SDValue();
17393
17394     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17395                                          DAG.getUNDEF(WideVecVT),
17396                                          &ShuffleVec[0]);
17397     // At this point all of the data is stored at the bottom of the
17398     // register. We now need to save it to mem.
17399
17400     // Find the largest store unit
17401     MVT StoreType = MVT::i8;
17402     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17403          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17404       MVT Tp = (MVT::SimpleValueType)tp;
17405       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17406         StoreType = Tp;
17407     }
17408
17409     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17410     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17411         (64 <= NumElems * ToSz))
17412       StoreType = MVT::f64;
17413
17414     // Bitcast the original vector into a vector of store-size units
17415     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17416             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17417     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17418     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17419     SmallVector<SDValue, 8> Chains;
17420     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17421                                         TLI.getPointerTy());
17422     SDValue Ptr = St->getBasePtr();
17423
17424     // Perform one or more big stores into memory.
17425     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17426       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17427                                    StoreType, ShuffWide,
17428                                    DAG.getIntPtrConstant(i));
17429       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17430                                 St->getPointerInfo(), St->isVolatile(),
17431                                 St->isNonTemporal(), St->getAlignment());
17432       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17433       Chains.push_back(Ch);
17434     }
17435
17436     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17437                                Chains.size());
17438   }
17439
17440   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17441   // the FP state in cases where an emms may be missing.
17442   // A preferable solution to the general problem is to figure out the right
17443   // places to insert EMMS.  This qualifies as a quick hack.
17444
17445   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17446   if (VT.getSizeInBits() != 64)
17447     return SDValue();
17448
17449   const Function *F = DAG.getMachineFunction().getFunction();
17450   bool NoImplicitFloatOps = F->getAttributes().
17451     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17452   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17453                      && Subtarget->hasSSE2();
17454   if ((VT.isVector() ||
17455        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17456       isa<LoadSDNode>(St->getValue()) &&
17457       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17458       St->getChain().hasOneUse() && !St->isVolatile()) {
17459     SDNode* LdVal = St->getValue().getNode();
17460     LoadSDNode *Ld = 0;
17461     int TokenFactorIndex = -1;
17462     SmallVector<SDValue, 8> Ops;
17463     SDNode* ChainVal = St->getChain().getNode();
17464     // Must be a store of a load.  We currently handle two cases:  the load
17465     // is a direct child, and it's under an intervening TokenFactor.  It is
17466     // possible to dig deeper under nested TokenFactors.
17467     if (ChainVal == LdVal)
17468       Ld = cast<LoadSDNode>(St->getChain());
17469     else if (St->getValue().hasOneUse() &&
17470              ChainVal->getOpcode() == ISD::TokenFactor) {
17471       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17472         if (ChainVal->getOperand(i).getNode() == LdVal) {
17473           TokenFactorIndex = i;
17474           Ld = cast<LoadSDNode>(St->getValue());
17475         } else
17476           Ops.push_back(ChainVal->getOperand(i));
17477       }
17478     }
17479
17480     if (!Ld || !ISD::isNormalLoad(Ld))
17481       return SDValue();
17482
17483     // If this is not the MMX case, i.e. we are just turning i64 load/store
17484     // into f64 load/store, avoid the transformation if there are multiple
17485     // uses of the loaded value.
17486     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17487       return SDValue();
17488
17489     SDLoc LdDL(Ld);
17490     SDLoc StDL(N);
17491     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17492     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17493     // pair instead.
17494     if (Subtarget->is64Bit() || F64IsLegal) {
17495       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17496       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17497                                   Ld->getPointerInfo(), Ld->isVolatile(),
17498                                   Ld->isNonTemporal(), Ld->isInvariant(),
17499                                   Ld->getAlignment());
17500       SDValue NewChain = NewLd.getValue(1);
17501       if (TokenFactorIndex != -1) {
17502         Ops.push_back(NewChain);
17503         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17504                                Ops.size());
17505       }
17506       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17507                           St->getPointerInfo(),
17508                           St->isVolatile(), St->isNonTemporal(),
17509                           St->getAlignment());
17510     }
17511
17512     // Otherwise, lower to two pairs of 32-bit loads / stores.
17513     SDValue LoAddr = Ld->getBasePtr();
17514     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17515                                  DAG.getConstant(4, MVT::i32));
17516
17517     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17518                                Ld->getPointerInfo(),
17519                                Ld->isVolatile(), Ld->isNonTemporal(),
17520                                Ld->isInvariant(), Ld->getAlignment());
17521     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17522                                Ld->getPointerInfo().getWithOffset(4),
17523                                Ld->isVolatile(), Ld->isNonTemporal(),
17524                                Ld->isInvariant(),
17525                                MinAlign(Ld->getAlignment(), 4));
17526
17527     SDValue NewChain = LoLd.getValue(1);
17528     if (TokenFactorIndex != -1) {
17529       Ops.push_back(LoLd);
17530       Ops.push_back(HiLd);
17531       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17532                              Ops.size());
17533     }
17534
17535     LoAddr = St->getBasePtr();
17536     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17537                          DAG.getConstant(4, MVT::i32));
17538
17539     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17540                                 St->getPointerInfo(),
17541                                 St->isVolatile(), St->isNonTemporal(),
17542                                 St->getAlignment());
17543     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17544                                 St->getPointerInfo().getWithOffset(4),
17545                                 St->isVolatile(),
17546                                 St->isNonTemporal(),
17547                                 MinAlign(St->getAlignment(), 4));
17548     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17549   }
17550   return SDValue();
17551 }
17552
17553 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17554 /// and return the operands for the horizontal operation in LHS and RHS.  A
17555 /// horizontal operation performs the binary operation on successive elements
17556 /// of its first operand, then on successive elements of its second operand,
17557 /// returning the resulting values in a vector.  For example, if
17558 ///   A = < float a0, float a1, float a2, float a3 >
17559 /// and
17560 ///   B = < float b0, float b1, float b2, float b3 >
17561 /// then the result of doing a horizontal operation on A and B is
17562 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17563 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17564 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17565 /// set to A, RHS to B, and the routine returns 'true'.
17566 /// Note that the binary operation should have the property that if one of the
17567 /// operands is UNDEF then the result is UNDEF.
17568 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17569   // Look for the following pattern: if
17570   //   A = < float a0, float a1, float a2, float a3 >
17571   //   B = < float b0, float b1, float b2, float b3 >
17572   // and
17573   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17574   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17575   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17576   // which is A horizontal-op B.
17577
17578   // At least one of the operands should be a vector shuffle.
17579   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17580       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17581     return false;
17582
17583   EVT VT = LHS.getValueType();
17584
17585   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17586          "Unsupported vector type for horizontal add/sub");
17587
17588   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17589   // operate independently on 128-bit lanes.
17590   unsigned NumElts = VT.getVectorNumElements();
17591   unsigned NumLanes = VT.getSizeInBits()/128;
17592   unsigned NumLaneElts = NumElts / NumLanes;
17593   assert((NumLaneElts % 2 == 0) &&
17594          "Vector type should have an even number of elements in each lane");
17595   unsigned HalfLaneElts = NumLaneElts/2;
17596
17597   // View LHS in the form
17598   //   LHS = VECTOR_SHUFFLE A, B, LMask
17599   // If LHS is not a shuffle then pretend it is the shuffle
17600   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17601   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17602   // type VT.
17603   SDValue A, B;
17604   SmallVector<int, 16> LMask(NumElts);
17605   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17606     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17607       A = LHS.getOperand(0);
17608     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17609       B = LHS.getOperand(1);
17610     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17611     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17612   } else {
17613     if (LHS.getOpcode() != ISD::UNDEF)
17614       A = LHS;
17615     for (unsigned i = 0; i != NumElts; ++i)
17616       LMask[i] = i;
17617   }
17618
17619   // Likewise, view RHS in the form
17620   //   RHS = VECTOR_SHUFFLE C, D, RMask
17621   SDValue C, D;
17622   SmallVector<int, 16> RMask(NumElts);
17623   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17624     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17625       C = RHS.getOperand(0);
17626     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17627       D = RHS.getOperand(1);
17628     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17629     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17630   } else {
17631     if (RHS.getOpcode() != ISD::UNDEF)
17632       C = RHS;
17633     for (unsigned i = 0; i != NumElts; ++i)
17634       RMask[i] = i;
17635   }
17636
17637   // Check that the shuffles are both shuffling the same vectors.
17638   if (!(A == C && B == D) && !(A == D && B == C))
17639     return false;
17640
17641   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17642   if (!A.getNode() && !B.getNode())
17643     return false;
17644
17645   // If A and B occur in reverse order in RHS, then "swap" them (which means
17646   // rewriting the mask).
17647   if (A != C)
17648     CommuteVectorShuffleMask(RMask, NumElts);
17649
17650   // At this point LHS and RHS are equivalent to
17651   //   LHS = VECTOR_SHUFFLE A, B, LMask
17652   //   RHS = VECTOR_SHUFFLE A, B, RMask
17653   // Check that the masks correspond to performing a horizontal operation.
17654   for (unsigned i = 0; i != NumElts; ++i) {
17655     int LIdx = LMask[i], RIdx = RMask[i];
17656
17657     // Ignore any UNDEF components.
17658     if (LIdx < 0 || RIdx < 0 ||
17659         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17660         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17661       continue;
17662
17663     // Check that successive elements are being operated on.  If not, this is
17664     // not a horizontal operation.
17665     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17666     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17667     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17668     if (!(LIdx == Index && RIdx == Index + 1) &&
17669         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17670       return false;
17671   }
17672
17673   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17674   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17675   return true;
17676 }
17677
17678 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17679 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17680                                   const X86Subtarget *Subtarget) {
17681   EVT VT = N->getValueType(0);
17682   SDValue LHS = N->getOperand(0);
17683   SDValue RHS = N->getOperand(1);
17684
17685   // Try to synthesize horizontal adds from adds of shuffles.
17686   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17687        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17688       isHorizontalBinOp(LHS, RHS, true))
17689     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17690   return SDValue();
17691 }
17692
17693 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17694 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17695                                   const X86Subtarget *Subtarget) {
17696   EVT VT = N->getValueType(0);
17697   SDValue LHS = N->getOperand(0);
17698   SDValue RHS = N->getOperand(1);
17699
17700   // Try to synthesize horizontal subs from subs of shuffles.
17701   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17702        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17703       isHorizontalBinOp(LHS, RHS, false))
17704     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17705   return SDValue();
17706 }
17707
17708 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17709 /// X86ISD::FXOR nodes.
17710 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17711   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17712   // F[X]OR(0.0, x) -> x
17713   // F[X]OR(x, 0.0) -> x
17714   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17715     if (C->getValueAPF().isPosZero())
17716       return N->getOperand(1);
17717   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17718     if (C->getValueAPF().isPosZero())
17719       return N->getOperand(0);
17720   return SDValue();
17721 }
17722
17723 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17724 /// X86ISD::FMAX nodes.
17725 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17726   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17727
17728   // Only perform optimizations if UnsafeMath is used.
17729   if (!DAG.getTarget().Options.UnsafeFPMath)
17730     return SDValue();
17731
17732   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17733   // into FMINC and FMAXC, which are Commutative operations.
17734   unsigned NewOp = 0;
17735   switch (N->getOpcode()) {
17736     default: llvm_unreachable("unknown opcode");
17737     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17738     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17739   }
17740
17741   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17742                      N->getOperand(0), N->getOperand(1));
17743 }
17744
17745 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17746 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17747   // FAND(0.0, x) -> 0.0
17748   // FAND(x, 0.0) -> 0.0
17749   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17750     if (C->getValueAPF().isPosZero())
17751       return N->getOperand(0);
17752   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17753     if (C->getValueAPF().isPosZero())
17754       return N->getOperand(1);
17755   return SDValue();
17756 }
17757
17758 static SDValue PerformBTCombine(SDNode *N,
17759                                 SelectionDAG &DAG,
17760                                 TargetLowering::DAGCombinerInfo &DCI) {
17761   // BT ignores high bits in the bit index operand.
17762   SDValue Op1 = N->getOperand(1);
17763   if (Op1.hasOneUse()) {
17764     unsigned BitWidth = Op1.getValueSizeInBits();
17765     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17766     APInt KnownZero, KnownOne;
17767     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17768                                           !DCI.isBeforeLegalizeOps());
17769     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17770     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17771         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17772       DCI.CommitTargetLoweringOpt(TLO);
17773   }
17774   return SDValue();
17775 }
17776
17777 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17778   SDValue Op = N->getOperand(0);
17779   if (Op.getOpcode() == ISD::BITCAST)
17780     Op = Op.getOperand(0);
17781   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17782   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17783       VT.getVectorElementType().getSizeInBits() ==
17784       OpVT.getVectorElementType().getSizeInBits()) {
17785     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17786   }
17787   return SDValue();
17788 }
17789
17790 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17791                                                const X86Subtarget *Subtarget) {
17792   EVT VT = N->getValueType(0);
17793   if (!VT.isVector())
17794     return SDValue();
17795
17796   SDValue N0 = N->getOperand(0);
17797   SDValue N1 = N->getOperand(1);
17798   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17799   SDLoc dl(N);
17800
17801   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17802   // both SSE and AVX2 since there is no sign-extended shift right
17803   // operation on a vector with 64-bit elements.
17804   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17805   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17806   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17807       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17808     SDValue N00 = N0.getOperand(0);
17809
17810     // EXTLOAD has a better solution on AVX2,
17811     // it may be replaced with X86ISD::VSEXT node.
17812     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17813       if (!ISD::isNormalLoad(N00.getNode()))
17814         return SDValue();
17815
17816     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17817         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17818                                   N00, N1);
17819       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17820     }
17821   }
17822   return SDValue();
17823 }
17824
17825 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17826                                   TargetLowering::DAGCombinerInfo &DCI,
17827                                   const X86Subtarget *Subtarget) {
17828   if (!DCI.isBeforeLegalizeOps())
17829     return SDValue();
17830
17831   if (!Subtarget->hasFp256())
17832     return SDValue();
17833
17834   EVT VT = N->getValueType(0);
17835   if (VT.isVector() && VT.getSizeInBits() == 256) {
17836     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17837     if (R.getNode())
17838       return R;
17839   }
17840
17841   return SDValue();
17842 }
17843
17844 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17845                                  const X86Subtarget* Subtarget) {
17846   SDLoc dl(N);
17847   EVT VT = N->getValueType(0);
17848
17849   // Let legalize expand this if it isn't a legal type yet.
17850   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17851     return SDValue();
17852
17853   EVT ScalarVT = VT.getScalarType();
17854   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17855       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17856     return SDValue();
17857
17858   SDValue A = N->getOperand(0);
17859   SDValue B = N->getOperand(1);
17860   SDValue C = N->getOperand(2);
17861
17862   bool NegA = (A.getOpcode() == ISD::FNEG);
17863   bool NegB = (B.getOpcode() == ISD::FNEG);
17864   bool NegC = (C.getOpcode() == ISD::FNEG);
17865
17866   // Negative multiplication when NegA xor NegB
17867   bool NegMul = (NegA != NegB);
17868   if (NegA)
17869     A = A.getOperand(0);
17870   if (NegB)
17871     B = B.getOperand(0);
17872   if (NegC)
17873     C = C.getOperand(0);
17874
17875   unsigned Opcode;
17876   if (!NegMul)
17877     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17878   else
17879     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17880
17881   return DAG.getNode(Opcode, dl, VT, A, B, C);
17882 }
17883
17884 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17885                                   TargetLowering::DAGCombinerInfo &DCI,
17886                                   const X86Subtarget *Subtarget) {
17887   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17888   //           (and (i32 x86isd::setcc_carry), 1)
17889   // This eliminates the zext. This transformation is necessary because
17890   // ISD::SETCC is always legalized to i8.
17891   SDLoc dl(N);
17892   SDValue N0 = N->getOperand(0);
17893   EVT VT = N->getValueType(0);
17894
17895   if (N0.getOpcode() == ISD::AND &&
17896       N0.hasOneUse() &&
17897       N0.getOperand(0).hasOneUse()) {
17898     SDValue N00 = N0.getOperand(0);
17899     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17900       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17901       if (!C || C->getZExtValue() != 1)
17902         return SDValue();
17903       return DAG.getNode(ISD::AND, dl, VT,
17904                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17905                                      N00.getOperand(0), N00.getOperand(1)),
17906                          DAG.getConstant(1, VT));
17907     }
17908   }
17909
17910   if (VT.is256BitVector()) {
17911     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17912     if (R.getNode())
17913       return R;
17914   }
17915
17916   return SDValue();
17917 }
17918
17919 // Optimize x == -y --> x+y == 0
17920 //          x != -y --> x+y != 0
17921 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17922   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17923   SDValue LHS = N->getOperand(0);
17924   SDValue RHS = N->getOperand(1);
17925
17926   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17927     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17928       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17929         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17930                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17931         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17932                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17933       }
17934   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17935     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17936       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17937         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17938                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17939         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17940                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17941       }
17942   return SDValue();
17943 }
17944
17945 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17946 // as "sbb reg,reg", since it can be extended without zext and produces
17947 // an all-ones bit which is more useful than 0/1 in some cases.
17948 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17949   return DAG.getNode(ISD::AND, DL, MVT::i8,
17950                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17951                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17952                      DAG.getConstant(1, MVT::i8));
17953 }
17954
17955 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17956 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17957                                    TargetLowering::DAGCombinerInfo &DCI,
17958                                    const X86Subtarget *Subtarget) {
17959   SDLoc DL(N);
17960   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17961   SDValue EFLAGS = N->getOperand(1);
17962
17963   if (CC == X86::COND_A) {
17964     // Try to convert COND_A into COND_B in an attempt to facilitate
17965     // materializing "setb reg".
17966     //
17967     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17968     // cannot take an immediate as its first operand.
17969     //
17970     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17971         EFLAGS.getValueType().isInteger() &&
17972         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17973       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17974                                    EFLAGS.getNode()->getVTList(),
17975                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17976       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17977       return MaterializeSETB(DL, NewEFLAGS, DAG);
17978     }
17979   }
17980
17981   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17982   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17983   // cases.
17984   if (CC == X86::COND_B)
17985     return MaterializeSETB(DL, EFLAGS, DAG);
17986
17987   SDValue Flags;
17988
17989   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17990   if (Flags.getNode()) {
17991     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17992     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17993   }
17994
17995   return SDValue();
17996 }
17997
17998 // Optimize branch condition evaluation.
17999 //
18000 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18001                                     TargetLowering::DAGCombinerInfo &DCI,
18002                                     const X86Subtarget *Subtarget) {
18003   SDLoc DL(N);
18004   SDValue Chain = N->getOperand(0);
18005   SDValue Dest = N->getOperand(1);
18006   SDValue EFLAGS = N->getOperand(3);
18007   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18008
18009   SDValue Flags;
18010
18011   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18012   if (Flags.getNode()) {
18013     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18014     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18015                        Flags);
18016   }
18017
18018   return SDValue();
18019 }
18020
18021 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18022                                         const X86TargetLowering *XTLI) {
18023   SDValue Op0 = N->getOperand(0);
18024   EVT InVT = Op0->getValueType(0);
18025
18026   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18027   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18028     SDLoc dl(N);
18029     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18030     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18031     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18032   }
18033
18034   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18035   // a 32-bit target where SSE doesn't support i64->FP operations.
18036   if (Op0.getOpcode() == ISD::LOAD) {
18037     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18038     EVT VT = Ld->getValueType(0);
18039     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18040         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18041         !XTLI->getSubtarget()->is64Bit() &&
18042         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18043       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18044                                           Ld->getChain(), Op0, DAG);
18045       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18046       return FILDChain;
18047     }
18048   }
18049   return SDValue();
18050 }
18051
18052 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18053 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18054                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18055   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18056   // the result is either zero or one (depending on the input carry bit).
18057   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18058   if (X86::isZeroNode(N->getOperand(0)) &&
18059       X86::isZeroNode(N->getOperand(1)) &&
18060       // We don't have a good way to replace an EFLAGS use, so only do this when
18061       // dead right now.
18062       SDValue(N, 1).use_empty()) {
18063     SDLoc DL(N);
18064     EVT VT = N->getValueType(0);
18065     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18066     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18067                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18068                                            DAG.getConstant(X86::COND_B,MVT::i8),
18069                                            N->getOperand(2)),
18070                                DAG.getConstant(1, VT));
18071     return DCI.CombineTo(N, Res1, CarryOut);
18072   }
18073
18074   return SDValue();
18075 }
18076
18077 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18078 //      (add Y, (setne X, 0)) -> sbb -1, Y
18079 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18080 //      (sub (setne X, 0), Y) -> adc -1, Y
18081 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18082   SDLoc DL(N);
18083
18084   // Look through ZExts.
18085   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18086   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18087     return SDValue();
18088
18089   SDValue SetCC = Ext.getOperand(0);
18090   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18091     return SDValue();
18092
18093   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18094   if (CC != X86::COND_E && CC != X86::COND_NE)
18095     return SDValue();
18096
18097   SDValue Cmp = SetCC.getOperand(1);
18098   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18099       !X86::isZeroNode(Cmp.getOperand(1)) ||
18100       !Cmp.getOperand(0).getValueType().isInteger())
18101     return SDValue();
18102
18103   SDValue CmpOp0 = Cmp.getOperand(0);
18104   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18105                                DAG.getConstant(1, CmpOp0.getValueType()));
18106
18107   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18108   if (CC == X86::COND_NE)
18109     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18110                        DL, OtherVal.getValueType(), OtherVal,
18111                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18112   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18113                      DL, OtherVal.getValueType(), OtherVal,
18114                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18115 }
18116
18117 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18118 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18119                                  const X86Subtarget *Subtarget) {
18120   EVT VT = N->getValueType(0);
18121   SDValue Op0 = N->getOperand(0);
18122   SDValue Op1 = N->getOperand(1);
18123
18124   // Try to synthesize horizontal adds from adds of shuffles.
18125   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18126        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18127       isHorizontalBinOp(Op0, Op1, true))
18128     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18129
18130   return OptimizeConditionalInDecrement(N, DAG);
18131 }
18132
18133 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18134                                  const X86Subtarget *Subtarget) {
18135   SDValue Op0 = N->getOperand(0);
18136   SDValue Op1 = N->getOperand(1);
18137
18138   // X86 can't encode an immediate LHS of a sub. See if we can push the
18139   // negation into a preceding instruction.
18140   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18141     // If the RHS of the sub is a XOR with one use and a constant, invert the
18142     // immediate. Then add one to the LHS of the sub so we can turn
18143     // X-Y -> X+~Y+1, saving one register.
18144     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18145         isa<ConstantSDNode>(Op1.getOperand(1))) {
18146       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18147       EVT VT = Op0.getValueType();
18148       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18149                                    Op1.getOperand(0),
18150                                    DAG.getConstant(~XorC, VT));
18151       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18152                          DAG.getConstant(C->getAPIntValue()+1, VT));
18153     }
18154   }
18155
18156   // Try to synthesize horizontal adds from adds of shuffles.
18157   EVT VT = N->getValueType(0);
18158   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18159        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18160       isHorizontalBinOp(Op0, Op1, true))
18161     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18162
18163   return OptimizeConditionalInDecrement(N, DAG);
18164 }
18165
18166 /// performVZEXTCombine - Performs build vector combines
18167 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18168                                         TargetLowering::DAGCombinerInfo &DCI,
18169                                         const X86Subtarget *Subtarget) {
18170   // (vzext (bitcast (vzext (x)) -> (vzext x)
18171   SDValue In = N->getOperand(0);
18172   while (In.getOpcode() == ISD::BITCAST)
18173     In = In.getOperand(0);
18174
18175   if (In.getOpcode() != X86ISD::VZEXT)
18176     return SDValue();
18177
18178   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18179                      In.getOperand(0));
18180 }
18181
18182 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18183                                              DAGCombinerInfo &DCI) const {
18184   SelectionDAG &DAG = DCI.DAG;
18185   switch (N->getOpcode()) {
18186   default: break;
18187   case ISD::EXTRACT_VECTOR_ELT:
18188     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18189   case ISD::VSELECT:
18190   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18191   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18192   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18193   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18194   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18195   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18196   case ISD::SHL:
18197   case ISD::SRA:
18198   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18199   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18200   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18201   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18202   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18203   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18204   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18205   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18206   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18207   case X86ISD::FXOR:
18208   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18209   case X86ISD::FMIN:
18210   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18211   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18212   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18213   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18214   case ISD::ANY_EXTEND:
18215   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18216   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18217   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18218   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18219   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18220   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18221   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18222   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18223   case X86ISD::SHUFP:       // Handle all target specific shuffles
18224   case X86ISD::PALIGNR:
18225   case X86ISD::UNPCKH:
18226   case X86ISD::UNPCKL:
18227   case X86ISD::MOVHLPS:
18228   case X86ISD::MOVLHPS:
18229   case X86ISD::PSHUFD:
18230   case X86ISD::PSHUFHW:
18231   case X86ISD::PSHUFLW:
18232   case X86ISD::MOVSS:
18233   case X86ISD::MOVSD:
18234   case X86ISD::VPERMILP:
18235   case X86ISD::VPERM2X128:
18236   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18237   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18238   }
18239
18240   return SDValue();
18241 }
18242
18243 /// isTypeDesirableForOp - Return true if the target has native support for
18244 /// the specified value type and it is 'desirable' to use the type for the
18245 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18246 /// instruction encodings are longer and some i16 instructions are slow.
18247 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18248   if (!isTypeLegal(VT))
18249     return false;
18250   if (VT != MVT::i16)
18251     return true;
18252
18253   switch (Opc) {
18254   default:
18255     return true;
18256   case ISD::LOAD:
18257   case ISD::SIGN_EXTEND:
18258   case ISD::ZERO_EXTEND:
18259   case ISD::ANY_EXTEND:
18260   case ISD::SHL:
18261   case ISD::SRL:
18262   case ISD::SUB:
18263   case ISD::ADD:
18264   case ISD::MUL:
18265   case ISD::AND:
18266   case ISD::OR:
18267   case ISD::XOR:
18268     return false;
18269   }
18270 }
18271
18272 /// IsDesirableToPromoteOp - This method query the target whether it is
18273 /// beneficial for dag combiner to promote the specified node. If true, it
18274 /// should return the desired promotion type by reference.
18275 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18276   EVT VT = Op.getValueType();
18277   if (VT != MVT::i16)
18278     return false;
18279
18280   bool Promote = false;
18281   bool Commute = false;
18282   switch (Op.getOpcode()) {
18283   default: break;
18284   case ISD::LOAD: {
18285     LoadSDNode *LD = cast<LoadSDNode>(Op);
18286     // If the non-extending load has a single use and it's not live out, then it
18287     // might be folded.
18288     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18289                                                      Op.hasOneUse()*/) {
18290       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18291              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18292         // The only case where we'd want to promote LOAD (rather then it being
18293         // promoted as an operand is when it's only use is liveout.
18294         if (UI->getOpcode() != ISD::CopyToReg)
18295           return false;
18296       }
18297     }
18298     Promote = true;
18299     break;
18300   }
18301   case ISD::SIGN_EXTEND:
18302   case ISD::ZERO_EXTEND:
18303   case ISD::ANY_EXTEND:
18304     Promote = true;
18305     break;
18306   case ISD::SHL:
18307   case ISD::SRL: {
18308     SDValue N0 = Op.getOperand(0);
18309     // Look out for (store (shl (load), x)).
18310     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18311       return false;
18312     Promote = true;
18313     break;
18314   }
18315   case ISD::ADD:
18316   case ISD::MUL:
18317   case ISD::AND:
18318   case ISD::OR:
18319   case ISD::XOR:
18320     Commute = true;
18321     // fallthrough
18322   case ISD::SUB: {
18323     SDValue N0 = Op.getOperand(0);
18324     SDValue N1 = Op.getOperand(1);
18325     if (!Commute && MayFoldLoad(N1))
18326       return false;
18327     // Avoid disabling potential load folding opportunities.
18328     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18329       return false;
18330     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18331       return false;
18332     Promote = true;
18333   }
18334   }
18335
18336   PVT = MVT::i32;
18337   return Promote;
18338 }
18339
18340 //===----------------------------------------------------------------------===//
18341 //                           X86 Inline Assembly Support
18342 //===----------------------------------------------------------------------===//
18343
18344 namespace {
18345   // Helper to match a string separated by whitespace.
18346   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18347     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18348
18349     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18350       StringRef piece(*args[i]);
18351       if (!s.startswith(piece)) // Check if the piece matches.
18352         return false;
18353
18354       s = s.substr(piece.size());
18355       StringRef::size_type pos = s.find_first_not_of(" \t");
18356       if (pos == 0) // We matched a prefix.
18357         return false;
18358
18359       s = s.substr(pos);
18360     }
18361
18362     return s.empty();
18363   }
18364   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18365 }
18366
18367 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18368   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18369
18370   std::string AsmStr = IA->getAsmString();
18371
18372   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18373   if (!Ty || Ty->getBitWidth() % 16 != 0)
18374     return false;
18375
18376   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18377   SmallVector<StringRef, 4> AsmPieces;
18378   SplitString(AsmStr, AsmPieces, ";\n");
18379
18380   switch (AsmPieces.size()) {
18381   default: return false;
18382   case 1:
18383     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18384     // we will turn this bswap into something that will be lowered to logical
18385     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18386     // lower so don't worry about this.
18387     // bswap $0
18388     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18389         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18390         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18391         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18392         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18393         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18394       // No need to check constraints, nothing other than the equivalent of
18395       // "=r,0" would be valid here.
18396       return IntrinsicLowering::LowerToByteSwap(CI);
18397     }
18398
18399     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18400     if (CI->getType()->isIntegerTy(16) &&
18401         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18402         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18403          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18404       AsmPieces.clear();
18405       const std::string &ConstraintsStr = IA->getConstraintString();
18406       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18407       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18408       if (AsmPieces.size() == 4 &&
18409           AsmPieces[0] == "~{cc}" &&
18410           AsmPieces[1] == "~{dirflag}" &&
18411           AsmPieces[2] == "~{flags}" &&
18412           AsmPieces[3] == "~{fpsr}")
18413       return IntrinsicLowering::LowerToByteSwap(CI);
18414     }
18415     break;
18416   case 3:
18417     if (CI->getType()->isIntegerTy(32) &&
18418         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18419         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18420         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18421         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18422       AsmPieces.clear();
18423       const std::string &ConstraintsStr = IA->getConstraintString();
18424       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18425       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18426       if (AsmPieces.size() == 4 &&
18427           AsmPieces[0] == "~{cc}" &&
18428           AsmPieces[1] == "~{dirflag}" &&
18429           AsmPieces[2] == "~{flags}" &&
18430           AsmPieces[3] == "~{fpsr}")
18431         return IntrinsicLowering::LowerToByteSwap(CI);
18432     }
18433
18434     if (CI->getType()->isIntegerTy(64)) {
18435       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18436       if (Constraints.size() >= 2 &&
18437           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18438           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18439         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18440         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18441             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18442             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18443           return IntrinsicLowering::LowerToByteSwap(CI);
18444       }
18445     }
18446     break;
18447   }
18448   return false;
18449 }
18450
18451 /// getConstraintType - Given a constraint letter, return the type of
18452 /// constraint it is for this target.
18453 X86TargetLowering::ConstraintType
18454 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18455   if (Constraint.size() == 1) {
18456     switch (Constraint[0]) {
18457     case 'R':
18458     case 'q':
18459     case 'Q':
18460     case 'f':
18461     case 't':
18462     case 'u':
18463     case 'y':
18464     case 'x':
18465     case 'Y':
18466     case 'l':
18467       return C_RegisterClass;
18468     case 'a':
18469     case 'b':
18470     case 'c':
18471     case 'd':
18472     case 'S':
18473     case 'D':
18474     case 'A':
18475       return C_Register;
18476     case 'I':
18477     case 'J':
18478     case 'K':
18479     case 'L':
18480     case 'M':
18481     case 'N':
18482     case 'G':
18483     case 'C':
18484     case 'e':
18485     case 'Z':
18486       return C_Other;
18487     default:
18488       break;
18489     }
18490   }
18491   return TargetLowering::getConstraintType(Constraint);
18492 }
18493
18494 /// Examine constraint type and operand type and determine a weight value.
18495 /// This object must already have been set up with the operand type
18496 /// and the current alternative constraint selected.
18497 TargetLowering::ConstraintWeight
18498   X86TargetLowering::getSingleConstraintMatchWeight(
18499     AsmOperandInfo &info, const char *constraint) const {
18500   ConstraintWeight weight = CW_Invalid;
18501   Value *CallOperandVal = info.CallOperandVal;
18502     // If we don't have a value, we can't do a match,
18503     // but allow it at the lowest weight.
18504   if (CallOperandVal == NULL)
18505     return CW_Default;
18506   Type *type = CallOperandVal->getType();
18507   // Look at the constraint type.
18508   switch (*constraint) {
18509   default:
18510     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18511   case 'R':
18512   case 'q':
18513   case 'Q':
18514   case 'a':
18515   case 'b':
18516   case 'c':
18517   case 'd':
18518   case 'S':
18519   case 'D':
18520   case 'A':
18521     if (CallOperandVal->getType()->isIntegerTy())
18522       weight = CW_SpecificReg;
18523     break;
18524   case 'f':
18525   case 't':
18526   case 'u':
18527     if (type->isFloatingPointTy())
18528       weight = CW_SpecificReg;
18529     break;
18530   case 'y':
18531     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18532       weight = CW_SpecificReg;
18533     break;
18534   case 'x':
18535   case 'Y':
18536     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18537         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18538       weight = CW_Register;
18539     break;
18540   case 'I':
18541     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18542       if (C->getZExtValue() <= 31)
18543         weight = CW_Constant;
18544     }
18545     break;
18546   case 'J':
18547     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18548       if (C->getZExtValue() <= 63)
18549         weight = CW_Constant;
18550     }
18551     break;
18552   case 'K':
18553     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18554       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18555         weight = CW_Constant;
18556     }
18557     break;
18558   case 'L':
18559     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18560       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18561         weight = CW_Constant;
18562     }
18563     break;
18564   case 'M':
18565     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18566       if (C->getZExtValue() <= 3)
18567         weight = CW_Constant;
18568     }
18569     break;
18570   case 'N':
18571     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18572       if (C->getZExtValue() <= 0xff)
18573         weight = CW_Constant;
18574     }
18575     break;
18576   case 'G':
18577   case 'C':
18578     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18579       weight = CW_Constant;
18580     }
18581     break;
18582   case 'e':
18583     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18584       if ((C->getSExtValue() >= -0x80000000LL) &&
18585           (C->getSExtValue() <= 0x7fffffffLL))
18586         weight = CW_Constant;
18587     }
18588     break;
18589   case 'Z':
18590     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18591       if (C->getZExtValue() <= 0xffffffff)
18592         weight = CW_Constant;
18593     }
18594     break;
18595   }
18596   return weight;
18597 }
18598
18599 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18600 /// with another that has more specific requirements based on the type of the
18601 /// corresponding operand.
18602 const char *X86TargetLowering::
18603 LowerXConstraint(EVT ConstraintVT) const {
18604   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18605   // 'f' like normal targets.
18606   if (ConstraintVT.isFloatingPoint()) {
18607     if (Subtarget->hasSSE2())
18608       return "Y";
18609     if (Subtarget->hasSSE1())
18610       return "x";
18611   }
18612
18613   return TargetLowering::LowerXConstraint(ConstraintVT);
18614 }
18615
18616 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18617 /// vector.  If it is invalid, don't add anything to Ops.
18618 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18619                                                      std::string &Constraint,
18620                                                      std::vector<SDValue>&Ops,
18621                                                      SelectionDAG &DAG) const {
18622   SDValue Result(0, 0);
18623
18624   // Only support length 1 constraints for now.
18625   if (Constraint.length() > 1) return;
18626
18627   char ConstraintLetter = Constraint[0];
18628   switch (ConstraintLetter) {
18629   default: break;
18630   case 'I':
18631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18632       if (C->getZExtValue() <= 31) {
18633         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18634         break;
18635       }
18636     }
18637     return;
18638   case 'J':
18639     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18640       if (C->getZExtValue() <= 63) {
18641         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18642         break;
18643       }
18644     }
18645     return;
18646   case 'K':
18647     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18648       if (isInt<8>(C->getSExtValue())) {
18649         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18650         break;
18651       }
18652     }
18653     return;
18654   case 'N':
18655     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18656       if (C->getZExtValue() <= 255) {
18657         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18658         break;
18659       }
18660     }
18661     return;
18662   case 'e': {
18663     // 32-bit signed value
18664     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18665       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18666                                            C->getSExtValue())) {
18667         // Widen to 64 bits here to get it sign extended.
18668         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18669         break;
18670       }
18671     // FIXME gcc accepts some relocatable values here too, but only in certain
18672     // memory models; it's complicated.
18673     }
18674     return;
18675   }
18676   case 'Z': {
18677     // 32-bit unsigned value
18678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18679       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18680                                            C->getZExtValue())) {
18681         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18682         break;
18683       }
18684     }
18685     // FIXME gcc accepts some relocatable values here too, but only in certain
18686     // memory models; it's complicated.
18687     return;
18688   }
18689   case 'i': {
18690     // Literal immediates are always ok.
18691     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18692       // Widen to 64 bits here to get it sign extended.
18693       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18694       break;
18695     }
18696
18697     // In any sort of PIC mode addresses need to be computed at runtime by
18698     // adding in a register or some sort of table lookup.  These can't
18699     // be used as immediates.
18700     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18701       return;
18702
18703     // If we are in non-pic codegen mode, we allow the address of a global (with
18704     // an optional displacement) to be used with 'i'.
18705     GlobalAddressSDNode *GA = 0;
18706     int64_t Offset = 0;
18707
18708     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18709     while (1) {
18710       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18711         Offset += GA->getOffset();
18712         break;
18713       } else if (Op.getOpcode() == ISD::ADD) {
18714         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18715           Offset += C->getZExtValue();
18716           Op = Op.getOperand(0);
18717           continue;
18718         }
18719       } else if (Op.getOpcode() == ISD::SUB) {
18720         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18721           Offset += -C->getZExtValue();
18722           Op = Op.getOperand(0);
18723           continue;
18724         }
18725       }
18726
18727       // Otherwise, this isn't something we can handle, reject it.
18728       return;
18729     }
18730
18731     const GlobalValue *GV = GA->getGlobal();
18732     // If we require an extra load to get this address, as in PIC mode, we
18733     // can't accept it.
18734     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18735                                                         getTargetMachine())))
18736       return;
18737
18738     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18739                                         GA->getValueType(0), Offset);
18740     break;
18741   }
18742   }
18743
18744   if (Result.getNode()) {
18745     Ops.push_back(Result);
18746     return;
18747   }
18748   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18749 }
18750
18751 std::pair<unsigned, const TargetRegisterClass*>
18752 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18753                                                 MVT VT) const {
18754   // First, see if this is a constraint that directly corresponds to an LLVM
18755   // register class.
18756   if (Constraint.size() == 1) {
18757     // GCC Constraint Letters
18758     switch (Constraint[0]) {
18759     default: break;
18760       // TODO: Slight differences here in allocation order and leaving
18761       // RIP in the class. Do they matter any more here than they do
18762       // in the normal allocation?
18763     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18764       if (Subtarget->is64Bit()) {
18765         if (VT == MVT::i32 || VT == MVT::f32)
18766           return std::make_pair(0U, &X86::GR32RegClass);
18767         if (VT == MVT::i16)
18768           return std::make_pair(0U, &X86::GR16RegClass);
18769         if (VT == MVT::i8 || VT == MVT::i1)
18770           return std::make_pair(0U, &X86::GR8RegClass);
18771         if (VT == MVT::i64 || VT == MVT::f64)
18772           return std::make_pair(0U, &X86::GR64RegClass);
18773         break;
18774       }
18775       // 32-bit fallthrough
18776     case 'Q':   // Q_REGS
18777       if (VT == MVT::i32 || VT == MVT::f32)
18778         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18779       if (VT == MVT::i16)
18780         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18781       if (VT == MVT::i8 || VT == MVT::i1)
18782         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18783       if (VT == MVT::i64)
18784         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18785       break;
18786     case 'r':   // GENERAL_REGS
18787     case 'l':   // INDEX_REGS
18788       if (VT == MVT::i8 || VT == MVT::i1)
18789         return std::make_pair(0U, &X86::GR8RegClass);
18790       if (VT == MVT::i16)
18791         return std::make_pair(0U, &X86::GR16RegClass);
18792       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18793         return std::make_pair(0U, &X86::GR32RegClass);
18794       return std::make_pair(0U, &X86::GR64RegClass);
18795     case 'R':   // LEGACY_REGS
18796       if (VT == MVT::i8 || VT == MVT::i1)
18797         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18798       if (VT == MVT::i16)
18799         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18800       if (VT == MVT::i32 || !Subtarget->is64Bit())
18801         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18802       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18803     case 'f':  // FP Stack registers.
18804       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18805       // value to the correct fpstack register class.
18806       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18807         return std::make_pair(0U, &X86::RFP32RegClass);
18808       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18809         return std::make_pair(0U, &X86::RFP64RegClass);
18810       return std::make_pair(0U, &X86::RFP80RegClass);
18811     case 'y':   // MMX_REGS if MMX allowed.
18812       if (!Subtarget->hasMMX()) break;
18813       return std::make_pair(0U, &X86::VR64RegClass);
18814     case 'Y':   // SSE_REGS if SSE2 allowed
18815       if (!Subtarget->hasSSE2()) break;
18816       // FALL THROUGH.
18817     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18818       if (!Subtarget->hasSSE1()) break;
18819
18820       switch (VT.SimpleTy) {
18821       default: break;
18822       // Scalar SSE types.
18823       case MVT::f32:
18824       case MVT::i32:
18825         return std::make_pair(0U, &X86::FR32RegClass);
18826       case MVT::f64:
18827       case MVT::i64:
18828         return std::make_pair(0U, &X86::FR64RegClass);
18829       // Vector types.
18830       case MVT::v16i8:
18831       case MVT::v8i16:
18832       case MVT::v4i32:
18833       case MVT::v2i64:
18834       case MVT::v4f32:
18835       case MVT::v2f64:
18836         return std::make_pair(0U, &X86::VR128RegClass);
18837       // AVX types.
18838       case MVT::v32i8:
18839       case MVT::v16i16:
18840       case MVT::v8i32:
18841       case MVT::v4i64:
18842       case MVT::v8f32:
18843       case MVT::v4f64:
18844         return std::make_pair(0U, &X86::VR256RegClass);
18845       case MVT::v8f64:
18846       case MVT::v16f32:
18847       case MVT::v16i32:
18848       case MVT::v8i64:
18849         return std::make_pair(0U, &X86::VR512RegClass);
18850       }
18851       break;
18852     }
18853   }
18854
18855   // Use the default implementation in TargetLowering to convert the register
18856   // constraint into a member of a register class.
18857   std::pair<unsigned, const TargetRegisterClass*> Res;
18858   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18859
18860   // Not found as a standard register?
18861   if (Res.second == 0) {
18862     // Map st(0) -> st(7) -> ST0
18863     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18864         tolower(Constraint[1]) == 's' &&
18865         tolower(Constraint[2]) == 't' &&
18866         Constraint[3] == '(' &&
18867         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18868         Constraint[5] == ')' &&
18869         Constraint[6] == '}') {
18870
18871       Res.first = X86::ST0+Constraint[4]-'0';
18872       Res.second = &X86::RFP80RegClass;
18873       return Res;
18874     }
18875
18876     // GCC allows "st(0)" to be called just plain "st".
18877     if (StringRef("{st}").equals_lower(Constraint)) {
18878       Res.first = X86::ST0;
18879       Res.second = &X86::RFP80RegClass;
18880       return Res;
18881     }
18882
18883     // flags -> EFLAGS
18884     if (StringRef("{flags}").equals_lower(Constraint)) {
18885       Res.first = X86::EFLAGS;
18886       Res.second = &X86::CCRRegClass;
18887       return Res;
18888     }
18889
18890     // 'A' means EAX + EDX.
18891     if (Constraint == "A") {
18892       Res.first = X86::EAX;
18893       Res.second = &X86::GR32_ADRegClass;
18894       return Res;
18895     }
18896     return Res;
18897   }
18898
18899   // Otherwise, check to see if this is a register class of the wrong value
18900   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18901   // turn into {ax},{dx}.
18902   if (Res.second->hasType(VT))
18903     return Res;   // Correct type already, nothing to do.
18904
18905   // All of the single-register GCC register classes map their values onto
18906   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18907   // really want an 8-bit or 32-bit register, map to the appropriate register
18908   // class and return the appropriate register.
18909   if (Res.second == &X86::GR16RegClass) {
18910     if (VT == MVT::i8 || VT == MVT::i1) {
18911       unsigned DestReg = 0;
18912       switch (Res.first) {
18913       default: break;
18914       case X86::AX: DestReg = X86::AL; break;
18915       case X86::DX: DestReg = X86::DL; break;
18916       case X86::CX: DestReg = X86::CL; break;
18917       case X86::BX: DestReg = X86::BL; break;
18918       }
18919       if (DestReg) {
18920         Res.first = DestReg;
18921         Res.second = &X86::GR8RegClass;
18922       }
18923     } else if (VT == MVT::i32 || VT == MVT::f32) {
18924       unsigned DestReg = 0;
18925       switch (Res.first) {
18926       default: break;
18927       case X86::AX: DestReg = X86::EAX; break;
18928       case X86::DX: DestReg = X86::EDX; break;
18929       case X86::CX: DestReg = X86::ECX; break;
18930       case X86::BX: DestReg = X86::EBX; break;
18931       case X86::SI: DestReg = X86::ESI; break;
18932       case X86::DI: DestReg = X86::EDI; break;
18933       case X86::BP: DestReg = X86::EBP; break;
18934       case X86::SP: DestReg = X86::ESP; break;
18935       }
18936       if (DestReg) {
18937         Res.first = DestReg;
18938         Res.second = &X86::GR32RegClass;
18939       }
18940     } else if (VT == MVT::i64 || VT == MVT::f64) {
18941       unsigned DestReg = 0;
18942       switch (Res.first) {
18943       default: break;
18944       case X86::AX: DestReg = X86::RAX; break;
18945       case X86::DX: DestReg = X86::RDX; break;
18946       case X86::CX: DestReg = X86::RCX; break;
18947       case X86::BX: DestReg = X86::RBX; break;
18948       case X86::SI: DestReg = X86::RSI; break;
18949       case X86::DI: DestReg = X86::RDI; break;
18950       case X86::BP: DestReg = X86::RBP; break;
18951       case X86::SP: DestReg = X86::RSP; break;
18952       }
18953       if (DestReg) {
18954         Res.first = DestReg;
18955         Res.second = &X86::GR64RegClass;
18956       }
18957     }
18958   } else if (Res.second == &X86::FR32RegClass ||
18959              Res.second == &X86::FR64RegClass ||
18960              Res.second == &X86::VR128RegClass ||
18961              Res.second == &X86::VR256RegClass ||
18962              Res.second == &X86::FR32XRegClass ||
18963              Res.second == &X86::FR64XRegClass ||
18964              Res.second == &X86::VR128XRegClass ||
18965              Res.second == &X86::VR256XRegClass ||
18966              Res.second == &X86::VR512RegClass) {
18967     // Handle references to XMM physical registers that got mapped into the
18968     // wrong class.  This can happen with constraints like {xmm0} where the
18969     // target independent register mapper will just pick the first match it can
18970     // find, ignoring the required type.
18971
18972     if (VT == MVT::f32 || VT == MVT::i32)
18973       Res.second = &X86::FR32RegClass;
18974     else if (VT == MVT::f64 || VT == MVT::i64)
18975       Res.second = &X86::FR64RegClass;
18976     else if (X86::VR128RegClass.hasType(VT))
18977       Res.second = &X86::VR128RegClass;
18978     else if (X86::VR256RegClass.hasType(VT))
18979       Res.second = &X86::VR256RegClass;
18980     else if (X86::VR512RegClass.hasType(VT))
18981       Res.second = &X86::VR512RegClass;
18982   }
18983
18984   return Res;
18985 }