Added INSERT and EXTRACT intructions from AVX-512 ISA.
[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() && "Unexpected vector size!");
105   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
106 }
107
108 /// Generate a DAG to grab 256-bits from a 512-bit vector.
109 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
110                                    SelectionDAG &DAG, SDLoc dl) {
111   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
112   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
113 }
114
115 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
116                                unsigned IdxVal, SelectionDAG &DAG,
117                                SDLoc dl, unsigned vectorWidth) {
118   assert((vectorWidth == 128 || vectorWidth == 256) &&
119          "Unsupported vector width");
120   // Inserting UNDEF is Result
121   if (Vec.getOpcode() == ISD::UNDEF)
122     return Result;
123   EVT VT = Vec.getValueType();
124   EVT ElVT = VT.getVectorElementType();
125   EVT ResultVT = Result.getValueType();
126
127   // Insert the relevant vectorWidth bits.
128   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
129
130   // This is the index of the first element of the vectorWidth-bit chunk
131   // we want.
132   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
133                                * ElemsPerChunk);
134
135   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
136   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
137                      VecIdx);
138 }
139 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
140 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
141 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
142 /// simple superregister reference.  Idx is an index in the 128 bits
143 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
144 /// lowering INSERT_VECTOR_ELT operations easier.
145 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
146                                   unsigned IdxVal, SelectionDAG &DAG,
147                                   SDLoc dl) {
148   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
149   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
150 }
151
152 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
153                                   unsigned IdxVal, SelectionDAG &DAG,
154                                   SDLoc dl) {
155   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
156   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
157 }
158
159 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
160 /// instructions. This is used because creating CONCAT_VECTOR nodes of
161 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
162 /// large BUILD_VECTORS.
163 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
164                                    unsigned NumElems, SelectionDAG &DAG,
165                                    SDLoc dl) {
166   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
167   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
168 }
169
170 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
171                                    unsigned NumElems, SelectionDAG &DAG,
172                                    SDLoc dl) {
173   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
174   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
175 }
176
177 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
178   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
179   bool is64Bit = Subtarget->is64Bit();
180
181   if (Subtarget->isTargetEnvMacho()) {
182     if (is64Bit)
183       return new X86_64MachoTargetObjectFile();
184     return new TargetLoweringObjectFileMachO();
185   }
186
187   if (Subtarget->isTargetLinux())
188     return new X86LinuxTargetObjectFile();
189   if (Subtarget->isTargetELF())
190     return new TargetLoweringObjectFileELF();
191   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
192     return new TargetLoweringObjectFileCOFF();
193   llvm_unreachable("unknown subtarget type");
194 }
195
196 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
197   : TargetLowering(TM, createTLOF(TM)) {
198   Subtarget = &TM.getSubtarget<X86Subtarget>();
199   X86ScalarSSEf64 = Subtarget->hasSSE2();
200   X86ScalarSSEf32 = Subtarget->hasSSE1();
201   TD = getDataLayout();
202
203   resetOperationActions();
204 }
205
206 void X86TargetLowering::resetOperationActions() {
207   const TargetMachine &TM = getTargetMachine();
208   static bool FirstTimeThrough = true;
209
210   // If none of the target options have changed, then we don't need to reset the
211   // operation actions.
212   if (!FirstTimeThrough && TO == TM.Options) return;
213
214   if (!FirstTimeThrough) {
215     // Reinitialize the actions.
216     initActions();
217     FirstTimeThrough = false;
218   }
219
220   TO = TM.Options;
221
222   // Set up the TargetLowering object.
223   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
224
225   // X86 is weird, it always uses i8 for shift amounts and setcc results.
226   setBooleanContents(ZeroOrOneBooleanContent);
227   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
228   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
229
230   // For 64-bit since we have so many registers use the ILP scheduler, for
231   // 32-bit code use the register pressure specific scheduling.
232   // For Atom, always use ILP scheduling.
233   if (Subtarget->isAtom())
234     setSchedulingPreference(Sched::ILP);
235   else if (Subtarget->is64Bit())
236     setSchedulingPreference(Sched::ILP);
237   else
238     setSchedulingPreference(Sched::RegPressure);
239   const X86RegisterInfo *RegInfo =
240     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
241   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
242
243   // Bypass expensive divides on Atom when compiling with O2
244   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
245     addBypassSlowDiv(32, 8);
246     if (Subtarget->is64Bit())
247       addBypassSlowDiv(64, 16);
248   }
249
250   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
251     // Setup Windows compiler runtime calls.
252     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
253     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
254     setLibcallName(RTLIB::SREM_I64, "_allrem");
255     setLibcallName(RTLIB::UREM_I64, "_aullrem");
256     setLibcallName(RTLIB::MUL_I64, "_allmul");
257     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
258     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
262
263     // The _ftol2 runtime function has an unusual calling conv, which
264     // is modeled by a special pseudo-instruction.
265     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
266     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
268     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
269   }
270
271   if (Subtarget->isTargetDarwin()) {
272     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
273     setUseUnderscoreSetJmp(false);
274     setUseUnderscoreLongJmp(false);
275   } else if (Subtarget->isTargetMingw()) {
276     // MS runtime is weird: it exports _setjmp, but longjmp!
277     setUseUnderscoreSetJmp(true);
278     setUseUnderscoreLongJmp(false);
279   } else {
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(true);
282   }
283
284   // Set up the register classes.
285   addRegisterClass(MVT::i8, &X86::GR8RegClass);
286   addRegisterClass(MVT::i16, &X86::GR16RegClass);
287   addRegisterClass(MVT::i32, &X86::GR32RegClass);
288   if (Subtarget->is64Bit())
289     addRegisterClass(MVT::i64, &X86::GR64RegClass);
290
291   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
292
293   // We don't accept any truncstore of integer registers.
294   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
295   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
297   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
298   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
299   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
300
301   // SETOEQ and SETUNE require checking two conditions.
302   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
303   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
305   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
308
309   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
310   // operation.
311   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
314
315   if (Subtarget->is64Bit()) {
316     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
318   } else if (!TM.Options.UseSoftFloat) {
319     // We have an algorithm for SSE2->double, and we turn this into a
320     // 64-bit FILD followed by conditional FADD for other targets.
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322     // We have an algorithm for SSE2, and we turn this into a 64-bit
323     // FILD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
325   }
326
327   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
331
332   if (!TM.Options.UseSoftFloat) {
333     // SSE has no i16 to fp conversion, only i32
334     if (X86ScalarSSEf32) {
335       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
336       // f32 and f64 cases are Legal, f80 case is not
337       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
338     } else {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     }
342   } else {
343     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
345   }
346
347   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
348   // are Legal, f80 is custom lowered.
349   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
350   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
351
352   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
353   // this operation.
354   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
356
357   if (X86ScalarSSEf32) {
358     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
359     // f32 and f64 cases are Legal, f80 case is not
360     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
361   } else {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   }
365
366   // Handle FP_TO_UINT by promoting the destination to a larger signed
367   // conversion.
368   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
371
372   if (Subtarget->is64Bit()) {
373     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
375   } else if (!TM.Options.UseSoftFloat) {
376     // Since AVX is a superset of SSE3, only check for SSE here.
377     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
378       // Expand FP_TO_UINT into a select.
379       // FIXME: We would like to use a Custom expander here eventually to do
380       // the optimal thing for SSE vs. the default expansion in the legalizer.
381       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
382     else
383       // With SSE3 we can use fisttpll to convert to a signed i64; without
384       // SSE, we're stuck with a fistpll.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
386   }
387
388   if (isTargetFTOL()) {
389     // Use the _ftol2 runtime function, which has a pseudo-instruction
390     // to handle its weird calling convention.
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
392   }
393
394   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
395   if (!X86ScalarSSEf64) {
396     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
397     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
398     if (Subtarget->is64Bit()) {
399       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
400       // Without SSE, i64->f64 goes through memory.
401       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
402     }
403   }
404
405   // Scalar integer divide and remainder are lowered to use operations that
406   // produce two results, to match the available instructions. This exposes
407   // the two-result form to trivial CSE, which is able to combine x/y and x%y
408   // into a single instruction.
409   //
410   // Scalar integer multiply-high is also lowered to use two-result
411   // operations, to match the available instructions. However, plain multiply
412   // (low) operations are left as Legal, as there are single-result
413   // instructions for this in x86. Using the two-result multiply instructions
414   // when both high and low results are needed must be arranged by dagcombine.
415   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
416     MVT VT = IntVTs[i];
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::MULHU, VT, Expand);
419     setOperationAction(ISD::SDIV, VT, Expand);
420     setOperationAction(ISD::UDIV, VT, Expand);
421     setOperationAction(ISD::SREM, VT, Expand);
422     setOperationAction(ISD::UREM, VT, Expand);
423
424     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
425     setOperationAction(ISD::ADDC, VT, Custom);
426     setOperationAction(ISD::ADDE, VT, Custom);
427     setOperationAction(ISD::SUBC, VT, Custom);
428     setOperationAction(ISD::SUBE, VT, Custom);
429   }
430
431   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
432   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
433   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
434   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
440   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
441   if (Subtarget->is64Bit())
442     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
443   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
446   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
447   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
450   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
451
452   // Promote the i8 variants and force them on up to i32 which has a shorter
453   // encoding.
454   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
455   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
456   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
457   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
458   if (Subtarget->hasBMI()) {
459     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
461     if (Subtarget->is64Bit())
462       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
463   } else {
464     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
465     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
466     if (Subtarget->is64Bit())
467       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
468   }
469
470   if (Subtarget->hasLZCNT()) {
471     // When promoting the i8 variants, force them to i32 for a shorter
472     // encoding.
473     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
474     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
476     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
477     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
479     if (Subtarget->is64Bit())
480       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
481   } else {
482     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
483     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
485     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
488     if (Subtarget->is64Bit()) {
489       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
490       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
491     }
492   }
493
494   if (Subtarget->hasPOPCNT()) {
495     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
496   } else {
497     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
498     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
500     if (Subtarget->is64Bit())
501       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
502   }
503
504   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
505   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
506
507   // These should be promoted to a larger select which is supported.
508   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
509   // X86 wants to expand cmov itself.
510   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
511   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
516   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
522   if (Subtarget->is64Bit()) {
523     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
524     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
525   }
526   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
527   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
528   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
529   // support continuation, user-level threading, and etc.. As a result, no
530   // other SjLj exception interfaces are implemented and please don't build
531   // your own exception handling based on them.
532   // LLVM/Clang supports zero-cost DWARF exception handling.
533   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
534   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
535
536   // Darwin ABI issue.
537   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
538   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
539   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
541   if (Subtarget->is64Bit())
542     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
543   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
544   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
545   if (Subtarget->is64Bit()) {
546     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
547     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
548     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
549     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
550     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
551   }
552   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
553   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
554   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
558     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
560   }
561
562   if (Subtarget->hasSSE1())
563     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
564
565   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
566
567   // Expand certain atomics
568   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
569     MVT VT = IntVTs[i];
570     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
571     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
572     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
573   }
574
575   if (!Subtarget->is64Bit()) {
576     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
588   }
589
590   if (Subtarget->hasCmpxchg16b()) {
591     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
592   }
593
594   // FIXME - use subtarget debug flags
595   if (!Subtarget->isTargetDarwin() &&
596       !Subtarget->isTargetELF() &&
597       !Subtarget->isTargetCygMing()) {
598     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
599   }
600
601   if (Subtarget->is64Bit()) {
602     setExceptionPointerRegister(X86::RAX);
603     setExceptionSelectorRegister(X86::RDX);
604   } else {
605     setExceptionPointerRegister(X86::EAX);
606     setExceptionSelectorRegister(X86::EDX);
607   }
608   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
610
611   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
612   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
613
614   setOperationAction(ISD::TRAP, MVT::Other, Legal);
615   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
616
617   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
618   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
619   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
620   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
621     // TargetInfo::X86_64ABIBuiltinVaList
622     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
623     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
624   } else {
625     // TargetInfo::CharPtrBuiltinVaList
626     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
627     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
628   }
629
630   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
631   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
632
633   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
634     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
635                        MVT::i64 : MVT::i32, Custom);
636   else if (TM.Options.EnableSegmentedStacks)
637     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
638                        MVT::i64 : MVT::i32, Custom);
639   else
640     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641                        MVT::i64 : MVT::i32, Expand);
642
643   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
644     // f32 and f64 use SSE.
645     // Set up the FP register classes.
646     addRegisterClass(MVT::f32, &X86::FR32RegClass);
647     addRegisterClass(MVT::f64, &X86::FR64RegClass);
648
649     // Use ANDPD to simulate FABS.
650     setOperationAction(ISD::FABS , MVT::f64, Custom);
651     setOperationAction(ISD::FABS , MVT::f32, Custom);
652
653     // Use XORP to simulate FNEG.
654     setOperationAction(ISD::FNEG , MVT::f64, Custom);
655     setOperationAction(ISD::FNEG , MVT::f32, Custom);
656
657     // Use ANDPD and ORPD to simulate FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660
661     // Lower this to FGETSIGNx86 plus an AND.
662     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
663     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664
665     // We don't support sin/cos/fmod
666     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
667     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
668     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
669     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
670     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
671     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672
673     // Expand FP immediates into loads from the stack, except for the special
674     // cases we handle.
675     addLegalFPImmediate(APFloat(+0.0)); // xorpd
676     addLegalFPImmediate(APFloat(+0.0f)); // xorps
677   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
678     // Use SSE for f32, x87 for f64.
679     // Set up the FP register classes.
680     addRegisterClass(MVT::f32, &X86::FR32RegClass);
681     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682
683     // Use ANDPS to simulate FABS.
684     setOperationAction(ISD::FABS , MVT::f32, Custom);
685
686     // Use XORP to simulate FNEG.
687     setOperationAction(ISD::FNEG , MVT::f32, Custom);
688
689     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
690
691     // Use ANDPS and ORPS to simulate FCOPYSIGN.
692     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
693     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694
695     // We don't support sin/cos/fmod
696     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
697     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
698     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699
700     // Special cases we handle for FP constants.
701     addLegalFPImmediate(APFloat(+0.0f)); // xorps
702     addLegalFPImmediate(APFloat(+0.0)); // FLD0
703     addLegalFPImmediate(APFloat(+1.0)); // FLD1
704     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
705     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706
707     if (!TM.Options.UnsafeFPMath) {
708       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
709       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
710       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711     }
712   } else if (!TM.Options.UseSoftFloat) {
713     // f32 and f64 in x87.
714     // Set up the FP register classes.
715     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
716     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717
718     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
719     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722
723     if (!TM.Options.UnsafeFPMath) {
724       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
725       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730     }
731     addLegalFPImmediate(APFloat(+0.0)); // FLD0
732     addLegalFPImmediate(APFloat(+1.0)); // FLD1
733     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
734     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
735     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
736     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
737     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
738     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
739   }
740
741   // We don't support FMA.
742   setOperationAction(ISD::FMA, MVT::f64, Expand);
743   setOperationAction(ISD::FMA, MVT::f32, Expand);
744
745   // Long double always uses X87.
746   if (!TM.Options.UseSoftFloat) {
747     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
748     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
749     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750     {
751       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
752       addLegalFPImmediate(TmpFlt);  // FLD0
753       TmpFlt.changeSign();
754       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
755
756       bool ignored;
757       APFloat TmpFlt2(+1.0);
758       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759                       &ignored);
760       addLegalFPImmediate(TmpFlt2);  // FLD1
761       TmpFlt2.changeSign();
762       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
763     }
764
765     if (!TM.Options.UnsafeFPMath) {
766       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
767       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
768       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
769     }
770
771     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
772     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
773     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
774     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
775     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
776     setOperationAction(ISD::FMA, MVT::f80, Expand);
777   }
778
779   // Always use a library call for pow.
780   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
783
784   setOperationAction(ISD::FLOG, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789
790   // First set operation action for all vector types to either promote
791   // (for widening) or expand (for scalarization). Then we will selectively
792   // turn on ones that can be effectively codegen'd.
793   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
794            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
795     MVT VT = (MVT::SimpleValueType)i;
796     setOperationAction(ISD::ADD , VT, Expand);
797     setOperationAction(ISD::SUB , VT, Expand);
798     setOperationAction(ISD::FADD, VT, Expand);
799     setOperationAction(ISD::FNEG, VT, Expand);
800     setOperationAction(ISD::FSUB, VT, Expand);
801     setOperationAction(ISD::MUL , VT, Expand);
802     setOperationAction(ISD::FMUL, VT, Expand);
803     setOperationAction(ISD::SDIV, VT, Expand);
804     setOperationAction(ISD::UDIV, VT, Expand);
805     setOperationAction(ISD::FDIV, VT, Expand);
806     setOperationAction(ISD::SREM, VT, Expand);
807     setOperationAction(ISD::UREM, VT, Expand);
808     setOperationAction(ISD::LOAD, VT, Expand);
809     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
810     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
811     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
812     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::FABS, VT, Expand);
815     setOperationAction(ISD::FSIN, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FCOS, VT, Expand);
818     setOperationAction(ISD::FSINCOS, VT, Expand);
819     setOperationAction(ISD::FREM, VT, Expand);
820     setOperationAction(ISD::FMA,  VT, Expand);
821     setOperationAction(ISD::FPOWI, VT, Expand);
822     setOperationAction(ISD::FSQRT, VT, Expand);
823     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
824     setOperationAction(ISD::FFLOOR, VT, Expand);
825     setOperationAction(ISD::FCEIL, VT, Expand);
826     setOperationAction(ISD::FTRUNC, VT, Expand);
827     setOperationAction(ISD::FRINT, VT, Expand);
828     setOperationAction(ISD::FNEARBYINT, VT, Expand);
829     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::SDIVREM, VT, Expand);
832     setOperationAction(ISD::UDIVREM, VT, Expand);
833     setOperationAction(ISD::FPOW, VT, Expand);
834     setOperationAction(ISD::CTPOP, VT, Expand);
835     setOperationAction(ISD::CTTZ, VT, Expand);
836     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::CTLZ, VT, Expand);
838     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::SHL, VT, Expand);
840     setOperationAction(ISD::SRA, VT, Expand);
841     setOperationAction(ISD::SRL, VT, Expand);
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844     setOperationAction(ISD::BSWAP, VT, Expand);
845     setOperationAction(ISD::SETCC, VT, Expand);
846     setOperationAction(ISD::FLOG, VT, Expand);
847     setOperationAction(ISD::FLOG2, VT, Expand);
848     setOperationAction(ISD::FLOG10, VT, Expand);
849     setOperationAction(ISD::FEXP, VT, Expand);
850     setOperationAction(ISD::FEXP2, VT, Expand);
851     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856     setOperationAction(ISD::TRUNCATE, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860     setOperationAction(ISD::VSELECT, VT, Expand);
861     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863       setTruncStoreAction(VT,
864                           (MVT::SimpleValueType)InnerVT, Expand);
865     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
868   }
869
870   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871   // with -msoft-float, disable use of MMX as well.
872   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874     // No operations on x86mmx supported, everything uses intrinsics.
875   }
876
877   // MMX-sized vectors (other than x86mmx) are expected to be expanded
878   // into smaller operations.
879   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
880   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
883   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
884   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
885   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
886   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
887   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
888   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
889   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
890   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
891   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
892   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
893   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
894   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
899   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
900   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
901   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
908
909   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911
912     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
917     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
918     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
919     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
921     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
924   }
925
926   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928
929     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930     // registers cannot be used even for integer operations.
931     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935
936     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
937     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
938     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
939     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
940     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
941     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
942     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
943     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
944     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
945     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
946     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
947     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
952     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
953     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
954
955     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
959
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
965
966     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
967     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
968       MVT VT = (MVT::SimpleValueType)i;
969       // Do not attempt to custom lower non-power-of-2 vectors
970       if (!isPowerOf2_32(VT.getVectorNumElements()))
971         continue;
972       // Do not attempt to custom lower non-128-bit vectors
973       if (!VT.is128BitVector())
974         continue;
975       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
976       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
977       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
978     }
979
980     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
982     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
985     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
986
987     if (Subtarget->is64Bit()) {
988       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
989       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
990     }
991
992     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
993     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
994       MVT VT = (MVT::SimpleValueType)i;
995
996       // Do not attempt to promote non-128-bit vectors
997       if (!VT.is128BitVector())
998         continue;
999
1000       setOperationAction(ISD::AND,    VT, Promote);
1001       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1002       setOperationAction(ISD::OR,     VT, Promote);
1003       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1004       setOperationAction(ISD::XOR,    VT, Promote);
1005       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1006       setOperationAction(ISD::LOAD,   VT, Promote);
1007       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1008       setOperationAction(ISD::SELECT, VT, Promote);
1009       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1010     }
1011
1012     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1013
1014     // Custom lower v2i64 and v2f64 selects.
1015     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1016     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1017     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1018     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1019
1020     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1021     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1022
1023     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1025     // As there is no 64-bit GPR available, we need build a special custom
1026     // sequence to convert from v2i32 to v2f32.
1027     if (!Subtarget->is64Bit())
1028       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1029
1030     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1031     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1032
1033     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1034   }
1035
1036   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1037     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1038     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1039     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1040     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1041     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1042     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1043     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1044     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1045     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1046     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1047
1048     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1053     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1056     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1058
1059     // FIXME: Do we need to handle scalar-to-vector here?
1060     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1061
1062     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1063     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1067
1068     // i8 and i16 vectors are custom , because the source register and source
1069     // source memory operand types are not the same width.  f32 vectors are
1070     // custom since the immediate controlling the insert encodes additional
1071     // information.
1072     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1076
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1081
1082     // FIXME: these should be Legal but thats only for the case where
1083     // the index is constant.  For now custom expand to deal with that.
1084     if (Subtarget->is64Bit()) {
1085       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1086       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1087     }
1088   }
1089
1090   if (Subtarget->hasSSE2()) {
1091     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1092     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1093
1094     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1095     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1096
1097     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1098     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1099
1100     // In the customized shift lowering, the legal cases in AVX2 will be
1101     // recognized.
1102     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1111     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1112   }
1113
1114   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1115     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1116     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1117     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1121
1122     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1123     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1125
1126     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1127     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1131     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1132     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1134     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1135     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1137     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1138
1139     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1144     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1145     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1147     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1148     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1150     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1151
1152     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1153     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1154
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1156
1157     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1160     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1161
1162     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1163     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1165
1166     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1167
1168     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1169     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1170
1171     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1172     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1173
1174     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1175     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1176
1177     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1178
1179     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1183
1184     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1187
1188     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1192
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199
1200     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1201       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1202       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1205       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1207     }
1208
1209     if (Subtarget->hasInt256()) {
1210       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1211       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1214
1215       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1216       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1219
1220       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1221       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1223       // Don't lower v32i8 because there is no 128-bit byte mul
1224
1225       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1226
1227       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1228     } else {
1229       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1230       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1233
1234       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1235       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1238
1239       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1240       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1242       // Don't lower v32i8 because there is no 128-bit byte mul
1243     }
1244
1245     // In the customized shift lowering, the legal cases in AVX2 will be
1246     // recognized.
1247     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1248     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1249
1250     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1251     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1252
1253     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1254
1255     // Custom lower several nodes for 256-bit types.
1256     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1257              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1258       MVT VT = (MVT::SimpleValueType)i;
1259
1260       // Extract subvector is special because the value type
1261       // (result) is 128-bit but the source is 256-bit wide.
1262       if (VT.is128BitVector())
1263         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1264
1265       // Do not attempt to custom lower other non-256-bit vectors
1266       if (!VT.is256BitVector())
1267         continue;
1268
1269       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1270       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1271       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1272       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1273       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1274       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1275       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1276     }
1277
1278     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1279     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1280       MVT VT = (MVT::SimpleValueType)i;
1281
1282       // Do not attempt to promote non-256-bit vectors
1283       if (!VT.is256BitVector())
1284         continue;
1285
1286       setOperationAction(ISD::AND,    VT, Promote);
1287       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1288       setOperationAction(ISD::OR,     VT, Promote);
1289       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1290       setOperationAction(ISD::XOR,    VT, Promote);
1291       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1292       setOperationAction(ISD::LOAD,   VT, Promote);
1293       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1294       setOperationAction(ISD::SELECT, VT, Promote);
1295       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1296     }
1297   }
1298
1299   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1300     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1301     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1304
1305     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1306     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1307
1308     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1309     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1314
1315     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1321
1322     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1323     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1327     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1328     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1329     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1330     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1331
1332
1333     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1334     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1336     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1337     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1339     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1340     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1341
1342     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1343     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1347     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1349     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1354
1355     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1360
1361     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1362     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1363
1364     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1365
1366     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1368     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1371
1372     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1373     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1374
1375     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1376     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1377
1378     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1379
1380     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1381     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1382
1383     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1384     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1385
1386     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1387     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1388
1389     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1390     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1391     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1392
1393     // Custom lower several nodes.
1394     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1395              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1396       MVT VT = (MVT::SimpleValueType)i;
1397
1398       // Extract subvector is special because the value type
1399       // (result) is 256/128-bit but the source is 512-bit wide.
1400       if (VT.is128BitVector() || VT.is256BitVector())
1401         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1402
1403       if (VT.getVectorElementType() == MVT::i1)
1404         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1405
1406       // Do not attempt to custom lower other non-512-bit vectors
1407       if (!VT.is512BitVector())
1408         continue;
1409
1410       if (VT != MVT::v8i64) {
1411         setOperationAction(ISD::XOR,   VT, Promote);
1412         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1413         setOperationAction(ISD::OR,    VT, Promote);
1414         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1415         setOperationAction(ISD::AND,   VT, Promote);
1416         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1417       }
1418       setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1419       setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1420       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1421       setOperationAction(ISD::VSELECT,             VT, Legal);
1422       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1423       setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1424       setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1425     }
1426     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1427       MVT VT = (MVT::SimpleValueType)i;
1428
1429       // Do not attempt to promote non-256-bit vectors
1430       if (!VT.is512BitVector())
1431         continue;
1432
1433       setOperationAction(ISD::LOAD,   VT, Promote);
1434       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1435       setOperationAction(ISD::SELECT, VT, Promote);
1436       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1437     }
1438   }// has  AVX-512
1439
1440   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1441   // of this type with custom code.
1442   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1443            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1444     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1445                        Custom);
1446   }
1447
1448   // We want to custom lower some of our intrinsics.
1449   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1450   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1451
1452   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1453   // handle type legalization for these operations here.
1454   //
1455   // FIXME: We really should do custom legalization for addition and
1456   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1457   // than generic legalization for 64-bit multiplication-with-overflow, though.
1458   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1459     // Add/Sub/Mul with overflow operations are custom lowered.
1460     MVT VT = IntVTs[i];
1461     setOperationAction(ISD::SADDO, VT, Custom);
1462     setOperationAction(ISD::UADDO, VT, Custom);
1463     setOperationAction(ISD::SSUBO, VT, Custom);
1464     setOperationAction(ISD::USUBO, VT, Custom);
1465     setOperationAction(ISD::SMULO, VT, Custom);
1466     setOperationAction(ISD::UMULO, VT, Custom);
1467   }
1468
1469   // There are no 8-bit 3-address imul/mul instructions
1470   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1471   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1472
1473   if (!Subtarget->is64Bit()) {
1474     // These libcalls are not available in 32-bit.
1475     setLibcallName(RTLIB::SHL_I128, 0);
1476     setLibcallName(RTLIB::SRL_I128, 0);
1477     setLibcallName(RTLIB::SRA_I128, 0);
1478   }
1479
1480   // Combine sin / cos into one node or libcall if possible.
1481   if (Subtarget->hasSinCos()) {
1482     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1483     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1484     if (Subtarget->isTargetDarwin()) {
1485       // For MacOSX, we don't want to the normal expansion of a libcall to
1486       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1487       // traffic.
1488       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1489       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1490     }
1491   }
1492
1493   // We have target-specific dag combine patterns for the following nodes:
1494   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1495   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1496   setTargetDAGCombine(ISD::VSELECT);
1497   setTargetDAGCombine(ISD::SELECT);
1498   setTargetDAGCombine(ISD::SHL);
1499   setTargetDAGCombine(ISD::SRA);
1500   setTargetDAGCombine(ISD::SRL);
1501   setTargetDAGCombine(ISD::OR);
1502   setTargetDAGCombine(ISD::AND);
1503   setTargetDAGCombine(ISD::ADD);
1504   setTargetDAGCombine(ISD::FADD);
1505   setTargetDAGCombine(ISD::FSUB);
1506   setTargetDAGCombine(ISD::FMA);
1507   setTargetDAGCombine(ISD::SUB);
1508   setTargetDAGCombine(ISD::LOAD);
1509   setTargetDAGCombine(ISD::STORE);
1510   setTargetDAGCombine(ISD::ZERO_EXTEND);
1511   setTargetDAGCombine(ISD::ANY_EXTEND);
1512   setTargetDAGCombine(ISD::SIGN_EXTEND);
1513   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1514   setTargetDAGCombine(ISD::TRUNCATE);
1515   setTargetDAGCombine(ISD::SINT_TO_FP);
1516   setTargetDAGCombine(ISD::SETCC);
1517   if (Subtarget->is64Bit())
1518     setTargetDAGCombine(ISD::MUL);
1519   setTargetDAGCombine(ISD::XOR);
1520
1521   computeRegisterProperties();
1522
1523   // On Darwin, -Os means optimize for size without hurting performance,
1524   // do not reduce the limit.
1525   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1526   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1527   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1528   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1529   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1530   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1531   setPrefLoopAlignment(4); // 2^4 bytes.
1532
1533   // Predictable cmov don't hurt on atom because it's in-order.
1534   PredictableSelectIsExpensive = !Subtarget->isAtom();
1535
1536   setPrefFunctionAlignment(4); // 2^4 bytes.
1537 }
1538
1539 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1540   if (!VT.isVector()) return MVT::i8;
1541   return VT.changeVectorElementTypeToInteger();
1542 }
1543
1544 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1545 /// the desired ByVal argument alignment.
1546 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1547   if (MaxAlign == 16)
1548     return;
1549   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1550     if (VTy->getBitWidth() == 128)
1551       MaxAlign = 16;
1552   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1553     unsigned EltAlign = 0;
1554     getMaxByValAlign(ATy->getElementType(), EltAlign);
1555     if (EltAlign > MaxAlign)
1556       MaxAlign = EltAlign;
1557   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1558     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1559       unsigned EltAlign = 0;
1560       getMaxByValAlign(STy->getElementType(i), EltAlign);
1561       if (EltAlign > MaxAlign)
1562         MaxAlign = EltAlign;
1563       if (MaxAlign == 16)
1564         break;
1565     }
1566   }
1567 }
1568
1569 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1570 /// function arguments in the caller parameter area. For X86, aggregates
1571 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1572 /// are at 4-byte boundaries.
1573 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1574   if (Subtarget->is64Bit()) {
1575     // Max of 8 and alignment of type.
1576     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1577     if (TyAlign > 8)
1578       return TyAlign;
1579     return 8;
1580   }
1581
1582   unsigned Align = 4;
1583   if (Subtarget->hasSSE1())
1584     getMaxByValAlign(Ty, Align);
1585   return Align;
1586 }
1587
1588 /// getOptimalMemOpType - Returns the target specific optimal type for load
1589 /// and store operations as a result of memset, memcpy, and memmove
1590 /// lowering. If DstAlign is zero that means it's safe to destination
1591 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1592 /// means there isn't a need to check it against alignment requirement,
1593 /// probably because the source does not need to be loaded. If 'IsMemset' is
1594 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1595 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1596 /// source is constant so it does not need to be loaded.
1597 /// It returns EVT::Other if the type should be determined using generic
1598 /// target-independent logic.
1599 EVT
1600 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1601                                        unsigned DstAlign, unsigned SrcAlign,
1602                                        bool IsMemset, bool ZeroMemset,
1603                                        bool MemcpyStrSrc,
1604                                        MachineFunction &MF) const {
1605   const Function *F = MF.getFunction();
1606   if ((!IsMemset || ZeroMemset) &&
1607       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1608                                        Attribute::NoImplicitFloat)) {
1609     if (Size >= 16 &&
1610         (Subtarget->isUnalignedMemAccessFast() ||
1611          ((DstAlign == 0 || DstAlign >= 16) &&
1612           (SrcAlign == 0 || SrcAlign >= 16)))) {
1613       if (Size >= 32) {
1614         if (Subtarget->hasInt256())
1615           return MVT::v8i32;
1616         if (Subtarget->hasFp256())
1617           return MVT::v8f32;
1618       }
1619       if (Subtarget->hasSSE2())
1620         return MVT::v4i32;
1621       if (Subtarget->hasSSE1())
1622         return MVT::v4f32;
1623     } else if (!MemcpyStrSrc && Size >= 8 &&
1624                !Subtarget->is64Bit() &&
1625                Subtarget->hasSSE2()) {
1626       // Do not use f64 to lower memcpy if source is string constant. It's
1627       // better to use i32 to avoid the loads.
1628       return MVT::f64;
1629     }
1630   }
1631   if (Subtarget->is64Bit() && Size >= 8)
1632     return MVT::i64;
1633   return MVT::i32;
1634 }
1635
1636 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1637   if (VT == MVT::f32)
1638     return X86ScalarSSEf32;
1639   else if (VT == MVT::f64)
1640     return X86ScalarSSEf64;
1641   return true;
1642 }
1643
1644 bool
1645 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1646   if (Fast)
1647     *Fast = Subtarget->isUnalignedMemAccessFast();
1648   return true;
1649 }
1650
1651 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1652 /// current function.  The returned value is a member of the
1653 /// MachineJumpTableInfo::JTEntryKind enum.
1654 unsigned X86TargetLowering::getJumpTableEncoding() const {
1655   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1656   // symbol.
1657   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1658       Subtarget->isPICStyleGOT())
1659     return MachineJumpTableInfo::EK_Custom32;
1660
1661   // Otherwise, use the normal jump table encoding heuristics.
1662   return TargetLowering::getJumpTableEncoding();
1663 }
1664
1665 const MCExpr *
1666 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1667                                              const MachineBasicBlock *MBB,
1668                                              unsigned uid,MCContext &Ctx) const{
1669   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1670          Subtarget->isPICStyleGOT());
1671   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1672   // entries.
1673   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1674                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1675 }
1676
1677 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1678 /// jumptable.
1679 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1680                                                     SelectionDAG &DAG) const {
1681   if (!Subtarget->is64Bit())
1682     // This doesn't have SDLoc associated with it, but is not really the
1683     // same as a Register.
1684     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1685   return Table;
1686 }
1687
1688 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1689 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1690 /// MCExpr.
1691 const MCExpr *X86TargetLowering::
1692 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1693                              MCContext &Ctx) const {
1694   // X86-64 uses RIP relative addressing based on the jump table label.
1695   if (Subtarget->isPICStyleRIPRel())
1696     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1697
1698   // Otherwise, the reference is relative to the PIC base.
1699   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1700 }
1701
1702 // FIXME: Why this routine is here? Move to RegInfo!
1703 std::pair<const TargetRegisterClass*, uint8_t>
1704 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1705   const TargetRegisterClass *RRC = 0;
1706   uint8_t Cost = 1;
1707   switch (VT.SimpleTy) {
1708   default:
1709     return TargetLowering::findRepresentativeClass(VT);
1710   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1711     RRC = Subtarget->is64Bit() ?
1712       (const TargetRegisterClass*)&X86::GR64RegClass :
1713       (const TargetRegisterClass*)&X86::GR32RegClass;
1714     break;
1715   case MVT::x86mmx:
1716     RRC = &X86::VR64RegClass;
1717     break;
1718   case MVT::f32: case MVT::f64:
1719   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1720   case MVT::v4f32: case MVT::v2f64:
1721   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1722   case MVT::v4f64:
1723     RRC = &X86::VR128RegClass;
1724     break;
1725   }
1726   return std::make_pair(RRC, Cost);
1727 }
1728
1729 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1730                                                unsigned &Offset) const {
1731   if (!Subtarget->isTargetLinux())
1732     return false;
1733
1734   if (Subtarget->is64Bit()) {
1735     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1736     Offset = 0x28;
1737     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1738       AddressSpace = 256;
1739     else
1740       AddressSpace = 257;
1741   } else {
1742     // %gs:0x14 on i386
1743     Offset = 0x14;
1744     AddressSpace = 256;
1745   }
1746   return true;
1747 }
1748
1749 //===----------------------------------------------------------------------===//
1750 //               Return Value Calling Convention Implementation
1751 //===----------------------------------------------------------------------===//
1752
1753 #include "X86GenCallingConv.inc"
1754
1755 bool
1756 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1757                                   MachineFunction &MF, bool isVarArg,
1758                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1759                         LLVMContext &Context) const {
1760   SmallVector<CCValAssign, 16> RVLocs;
1761   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1762                  RVLocs, Context);
1763   return CCInfo.CheckReturn(Outs, RetCC_X86);
1764 }
1765
1766 SDValue
1767 X86TargetLowering::LowerReturn(SDValue Chain,
1768                                CallingConv::ID CallConv, bool isVarArg,
1769                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1770                                const SmallVectorImpl<SDValue> &OutVals,
1771                                SDLoc dl, SelectionDAG &DAG) const {
1772   MachineFunction &MF = DAG.getMachineFunction();
1773   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1774
1775   SmallVector<CCValAssign, 16> RVLocs;
1776   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1777                  RVLocs, *DAG.getContext());
1778   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1779
1780   SDValue Flag;
1781   SmallVector<SDValue, 6> RetOps;
1782   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1783   // Operand #1 = Bytes To Pop
1784   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1785                    MVT::i16));
1786
1787   // Copy the result values into the output registers.
1788   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1789     CCValAssign &VA = RVLocs[i];
1790     assert(VA.isRegLoc() && "Can only return in registers!");
1791     SDValue ValToCopy = OutVals[i];
1792     EVT ValVT = ValToCopy.getValueType();
1793
1794     // Promote values to the appropriate types
1795     if (VA.getLocInfo() == CCValAssign::SExt)
1796       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1797     else if (VA.getLocInfo() == CCValAssign::ZExt)
1798       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1799     else if (VA.getLocInfo() == CCValAssign::AExt)
1800       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::BCvt)
1802       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1803
1804     // If this is x86-64, and we disabled SSE, we can't return FP values,
1805     // or SSE or MMX vectors.
1806     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1807          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1808           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1809       report_fatal_error("SSE register return with SSE disabled");
1810     }
1811     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1812     // llvm-gcc has never done it right and no one has noticed, so this
1813     // should be OK for now.
1814     if (ValVT == MVT::f64 &&
1815         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1816       report_fatal_error("SSE2 register return with SSE2 disabled");
1817
1818     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1819     // the RET instruction and handled by the FP Stackifier.
1820     if (VA.getLocReg() == X86::ST0 ||
1821         VA.getLocReg() == X86::ST1) {
1822       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1823       // change the value to the FP stack register class.
1824       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1825         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1826       RetOps.push_back(ValToCopy);
1827       // Don't emit a copytoreg.
1828       continue;
1829     }
1830
1831     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1832     // which is returned in RAX / RDX.
1833     if (Subtarget->is64Bit()) {
1834       if (ValVT == MVT::x86mmx) {
1835         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1836           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1837           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1838                                   ValToCopy);
1839           // If we don't have SSE2 available, convert to v4f32 so the generated
1840           // register is legal.
1841           if (!Subtarget->hasSSE2())
1842             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1843         }
1844       }
1845     }
1846
1847     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1848     Flag = Chain.getValue(1);
1849     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1850   }
1851
1852   // The x86-64 ABIs require that for returning structs by value we copy
1853   // the sret argument into %rax/%eax (depending on ABI) for the return.
1854   // Win32 requires us to put the sret argument to %eax as well.
1855   // We saved the argument into a virtual register in the entry block,
1856   // so now we copy the value out and into %rax/%eax.
1857   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1858       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1859     MachineFunction &MF = DAG.getMachineFunction();
1860     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1861     unsigned Reg = FuncInfo->getSRetReturnReg();
1862     assert(Reg &&
1863            "SRetReturnReg should have been set in LowerFormalArguments().");
1864     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1865
1866     unsigned RetValReg
1867         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1868           X86::RAX : X86::EAX;
1869     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1870     Flag = Chain.getValue(1);
1871
1872     // RAX/EAX now acts like a return value.
1873     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1874   }
1875
1876   RetOps[0] = Chain;  // Update chain.
1877
1878   // Add the flag if we have it.
1879   if (Flag.getNode())
1880     RetOps.push_back(Flag);
1881
1882   return DAG.getNode(X86ISD::RET_FLAG, dl,
1883                      MVT::Other, &RetOps[0], RetOps.size());
1884 }
1885
1886 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1887   if (N->getNumValues() != 1)
1888     return false;
1889   if (!N->hasNUsesOfValue(1, 0))
1890     return false;
1891
1892   SDValue TCChain = Chain;
1893   SDNode *Copy = *N->use_begin();
1894   if (Copy->getOpcode() == ISD::CopyToReg) {
1895     // If the copy has a glue operand, we conservatively assume it isn't safe to
1896     // perform a tail call.
1897     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1898       return false;
1899     TCChain = Copy->getOperand(0);
1900   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1901     return false;
1902
1903   bool HasRet = false;
1904   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1905        UI != UE; ++UI) {
1906     if (UI->getOpcode() != X86ISD::RET_FLAG)
1907       return false;
1908     HasRet = true;
1909   }
1910
1911   if (!HasRet)
1912     return false;
1913
1914   Chain = TCChain;
1915   return true;
1916 }
1917
1918 MVT
1919 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1920                                             ISD::NodeType ExtendKind) const {
1921   MVT ReturnMVT;
1922   // TODO: Is this also valid on 32-bit?
1923   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1924     ReturnMVT = MVT::i8;
1925   else
1926     ReturnMVT = MVT::i32;
1927
1928   MVT MinVT = getRegisterType(ReturnMVT);
1929   return VT.bitsLT(MinVT) ? MinVT : VT;
1930 }
1931
1932 /// LowerCallResult - Lower the result values of a call into the
1933 /// appropriate copies out of appropriate physical registers.
1934 ///
1935 SDValue
1936 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1937                                    CallingConv::ID CallConv, bool isVarArg,
1938                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1939                                    SDLoc dl, SelectionDAG &DAG,
1940                                    SmallVectorImpl<SDValue> &InVals) const {
1941
1942   // Assign locations to each value returned by this call.
1943   SmallVector<CCValAssign, 16> RVLocs;
1944   bool Is64Bit = Subtarget->is64Bit();
1945   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1946                  getTargetMachine(), RVLocs, *DAG.getContext());
1947   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1948
1949   // Copy all of the result registers out of their specified physreg.
1950   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1951     CCValAssign &VA = RVLocs[i];
1952     EVT CopyVT = VA.getValVT();
1953
1954     // If this is x86-64, and we disabled SSE, we can't return FP values
1955     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1956         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1957       report_fatal_error("SSE register return with SSE disabled");
1958     }
1959
1960     SDValue Val;
1961
1962     // If this is a call to a function that returns an fp value on the floating
1963     // point stack, we must guarantee the value is popped from the stack, so
1964     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1965     // if the return value is not used. We use the FpPOP_RETVAL instruction
1966     // instead.
1967     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1968       // If we prefer to use the value in xmm registers, copy it out as f80 and
1969       // use a truncate to move it from fp stack reg to xmm reg.
1970       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1971       SDValue Ops[] = { Chain, InFlag };
1972       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1973                                          MVT::Other, MVT::Glue, Ops), 1);
1974       Val = Chain.getValue(0);
1975
1976       // Round the f80 to the right size, which also moves it to the appropriate
1977       // xmm register.
1978       if (CopyVT != VA.getValVT())
1979         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1980                           // This truncation won't change the value.
1981                           DAG.getIntPtrConstant(1));
1982     } else {
1983       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1984                                  CopyVT, InFlag).getValue(1);
1985       Val = Chain.getValue(0);
1986     }
1987     InFlag = Chain.getValue(2);
1988     InVals.push_back(Val);
1989   }
1990
1991   return Chain;
1992 }
1993
1994 //===----------------------------------------------------------------------===//
1995 //                C & StdCall & Fast Calling Convention implementation
1996 //===----------------------------------------------------------------------===//
1997 //  StdCall calling convention seems to be standard for many Windows' API
1998 //  routines and around. It differs from C calling convention just a little:
1999 //  callee should clean up the stack, not caller. Symbols should be also
2000 //  decorated in some fancy way :) It doesn't support any vector arguments.
2001 //  For info on fast calling convention see Fast Calling Convention (tail call)
2002 //  implementation LowerX86_32FastCCCallTo.
2003
2004 /// CallIsStructReturn - Determines whether a call uses struct return
2005 /// semantics.
2006 enum StructReturnType {
2007   NotStructReturn,
2008   RegStructReturn,
2009   StackStructReturn
2010 };
2011 static StructReturnType
2012 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2013   if (Outs.empty())
2014     return NotStructReturn;
2015
2016   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2017   if (!Flags.isSRet())
2018     return NotStructReturn;
2019   if (Flags.isInReg())
2020     return RegStructReturn;
2021   return StackStructReturn;
2022 }
2023
2024 /// ArgsAreStructReturn - Determines whether a function uses struct
2025 /// return semantics.
2026 static StructReturnType
2027 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2028   if (Ins.empty())
2029     return NotStructReturn;
2030
2031   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2032   if (!Flags.isSRet())
2033     return NotStructReturn;
2034   if (Flags.isInReg())
2035     return RegStructReturn;
2036   return StackStructReturn;
2037 }
2038
2039 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2040 /// by "Src" to address "Dst" with size and alignment information specified by
2041 /// the specific parameter attribute. The copy will be passed as a byval
2042 /// function parameter.
2043 static SDValue
2044 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2045                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2046                           SDLoc dl) {
2047   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2048
2049   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2050                        /*isVolatile*/false, /*AlwaysInline=*/true,
2051                        MachinePointerInfo(), MachinePointerInfo());
2052 }
2053
2054 /// IsTailCallConvention - Return true if the calling convention is one that
2055 /// supports tail call optimization.
2056 static bool IsTailCallConvention(CallingConv::ID CC) {
2057   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2058           CC == CallingConv::HiPE);
2059 }
2060
2061 /// \brief Return true if the calling convention is a C calling convention.
2062 static bool IsCCallConvention(CallingConv::ID CC) {
2063   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2064           CC == CallingConv::X86_64_SysV);
2065 }
2066
2067 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2068   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2069     return false;
2070
2071   CallSite CS(CI);
2072   CallingConv::ID CalleeCC = CS.getCallingConv();
2073   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2074     return false;
2075
2076   return true;
2077 }
2078
2079 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2080 /// a tailcall target by changing its ABI.
2081 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2082                                    bool GuaranteedTailCallOpt) {
2083   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2084 }
2085
2086 SDValue
2087 X86TargetLowering::LowerMemArgument(SDValue Chain,
2088                                     CallingConv::ID CallConv,
2089                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2090                                     SDLoc dl, SelectionDAG &DAG,
2091                                     const CCValAssign &VA,
2092                                     MachineFrameInfo *MFI,
2093                                     unsigned i) const {
2094   // Create the nodes corresponding to a load from this parameter slot.
2095   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2096   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2097                               getTargetMachine().Options.GuaranteedTailCallOpt);
2098   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2099   EVT ValVT;
2100
2101   // If value is passed by pointer we have address passed instead of the value
2102   // itself.
2103   if (VA.getLocInfo() == CCValAssign::Indirect)
2104     ValVT = VA.getLocVT();
2105   else
2106     ValVT = VA.getValVT();
2107
2108   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2109   // changed with more analysis.
2110   // In case of tail call optimization mark all arguments mutable. Since they
2111   // could be overwritten by lowering of arguments in case of a tail call.
2112   if (Flags.isByVal()) {
2113     unsigned Bytes = Flags.getByValSize();
2114     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2115     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2116     return DAG.getFrameIndex(FI, getPointerTy());
2117   } else {
2118     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2119                                     VA.getLocMemOffset(), isImmutable);
2120     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2121     return DAG.getLoad(ValVT, dl, Chain, FIN,
2122                        MachinePointerInfo::getFixedStack(FI),
2123                        false, false, false, 0);
2124   }
2125 }
2126
2127 SDValue
2128 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2129                                         CallingConv::ID CallConv,
2130                                         bool isVarArg,
2131                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2132                                         SDLoc dl,
2133                                         SelectionDAG &DAG,
2134                                         SmallVectorImpl<SDValue> &InVals)
2135                                           const {
2136   MachineFunction &MF = DAG.getMachineFunction();
2137   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2138
2139   const Function* Fn = MF.getFunction();
2140   if (Fn->hasExternalLinkage() &&
2141       Subtarget->isTargetCygMing() &&
2142       Fn->getName() == "main")
2143     FuncInfo->setForceFramePointer(true);
2144
2145   MachineFrameInfo *MFI = MF.getFrameInfo();
2146   bool Is64Bit = Subtarget->is64Bit();
2147   bool IsWindows = Subtarget->isTargetWindows();
2148   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2149
2150   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2151          "Var args not supported with calling convention fastcc, ghc or hipe");
2152
2153   // Assign locations to all of the incoming arguments.
2154   SmallVector<CCValAssign, 16> ArgLocs;
2155   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2156                  ArgLocs, *DAG.getContext());
2157
2158   // Allocate shadow area for Win64
2159   if (IsWin64)
2160     CCInfo.AllocateStack(32, 8);
2161
2162   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2163
2164   unsigned LastVal = ~0U;
2165   SDValue ArgValue;
2166   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2167     CCValAssign &VA = ArgLocs[i];
2168     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2169     // places.
2170     assert(VA.getValNo() != LastVal &&
2171            "Don't support value assigned to multiple locs yet");
2172     (void)LastVal;
2173     LastVal = VA.getValNo();
2174
2175     if (VA.isRegLoc()) {
2176       EVT RegVT = VA.getLocVT();
2177       const TargetRegisterClass *RC;
2178       if (RegVT == MVT::i32)
2179         RC = &X86::GR32RegClass;
2180       else if (Is64Bit && RegVT == MVT::i64)
2181         RC = &X86::GR64RegClass;
2182       else if (RegVT == MVT::f32)
2183         RC = &X86::FR32RegClass;
2184       else if (RegVT == MVT::f64)
2185         RC = &X86::FR64RegClass;
2186       else if (RegVT.is512BitVector())
2187         RC = &X86::VR512RegClass;
2188       else if (RegVT.is256BitVector())
2189         RC = &X86::VR256RegClass;
2190       else if (RegVT.is128BitVector())
2191         RC = &X86::VR128RegClass;
2192       else if (RegVT == MVT::x86mmx)
2193         RC = &X86::VR64RegClass;
2194       else if (RegVT == MVT::v8i1)
2195         RC = &X86::VK8RegClass;
2196       else if (RegVT == MVT::v16i1)
2197         RC = &X86::VK16RegClass;
2198       else
2199         llvm_unreachable("Unknown argument type!");
2200
2201       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2202       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2203
2204       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2205       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2206       // right size.
2207       if (VA.getLocInfo() == CCValAssign::SExt)
2208         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2209                                DAG.getValueType(VA.getValVT()));
2210       else if (VA.getLocInfo() == CCValAssign::ZExt)
2211         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2212                                DAG.getValueType(VA.getValVT()));
2213       else if (VA.getLocInfo() == CCValAssign::BCvt)
2214         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2215
2216       if (VA.isExtInLoc()) {
2217         // Handle MMX values passed in XMM regs.
2218         if (RegVT.isVector())
2219           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2220         else
2221           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2222       }
2223     } else {
2224       assert(VA.isMemLoc());
2225       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2226     }
2227
2228     // If value is passed via pointer - do a load.
2229     if (VA.getLocInfo() == CCValAssign::Indirect)
2230       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2231                              MachinePointerInfo(), false, false, false, 0);
2232
2233     InVals.push_back(ArgValue);
2234   }
2235
2236   // The x86-64 ABIs require that for returning structs by value we copy
2237   // the sret argument into %rax/%eax (depending on ABI) for the return.
2238   // Win32 requires us to put the sret argument to %eax as well.
2239   // Save the argument into a virtual register so that we can access it
2240   // from the return points.
2241   if (MF.getFunction()->hasStructRetAttr() &&
2242       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2243     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2244     unsigned Reg = FuncInfo->getSRetReturnReg();
2245     if (!Reg) {
2246       MVT PtrTy = getPointerTy();
2247       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2248       FuncInfo->setSRetReturnReg(Reg);
2249     }
2250     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2251     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2252   }
2253
2254   unsigned StackSize = CCInfo.getNextStackOffset();
2255   // Align stack specially for tail calls.
2256   if (FuncIsMadeTailCallSafe(CallConv,
2257                              MF.getTarget().Options.GuaranteedTailCallOpt))
2258     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2259
2260   // If the function takes variable number of arguments, make a frame index for
2261   // the start of the first vararg value... for expansion of llvm.va_start.
2262   if (isVarArg) {
2263     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2264                     CallConv != CallingConv::X86_ThisCall)) {
2265       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2266     }
2267     if (Is64Bit) {
2268       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2269
2270       // FIXME: We should really autogenerate these arrays
2271       static const uint16_t GPR64ArgRegsWin64[] = {
2272         X86::RCX, X86::RDX, X86::R8,  X86::R9
2273       };
2274       static const uint16_t GPR64ArgRegs64Bit[] = {
2275         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2276       };
2277       static const uint16_t XMMArgRegs64Bit[] = {
2278         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2279         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2280       };
2281       const uint16_t *GPR64ArgRegs;
2282       unsigned NumXMMRegs = 0;
2283
2284       if (IsWin64) {
2285         // The XMM registers which might contain var arg parameters are shadowed
2286         // in their paired GPR.  So we only need to save the GPR to their home
2287         // slots.
2288         TotalNumIntRegs = 4;
2289         GPR64ArgRegs = GPR64ArgRegsWin64;
2290       } else {
2291         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2292         GPR64ArgRegs = GPR64ArgRegs64Bit;
2293
2294         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2295                                                 TotalNumXMMRegs);
2296       }
2297       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2298                                                        TotalNumIntRegs);
2299
2300       bool NoImplicitFloatOps = Fn->getAttributes().
2301         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2302       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2303              "SSE register cannot be used when SSE is disabled!");
2304       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2305                NoImplicitFloatOps) &&
2306              "SSE register cannot be used when SSE is disabled!");
2307       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2308           !Subtarget->hasSSE1())
2309         // Kernel mode asks for SSE to be disabled, so don't push them
2310         // on the stack.
2311         TotalNumXMMRegs = 0;
2312
2313       if (IsWin64) {
2314         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2315         // Get to the caller-allocated home save location.  Add 8 to account
2316         // for the return address.
2317         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2318         FuncInfo->setRegSaveFrameIndex(
2319           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2320         // Fixup to set vararg frame on shadow area (4 x i64).
2321         if (NumIntRegs < 4)
2322           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2323       } else {
2324         // For X86-64, if there are vararg parameters that are passed via
2325         // registers, then we must store them to their spots on the stack so
2326         // they may be loaded by deferencing the result of va_next.
2327         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2328         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2329         FuncInfo->setRegSaveFrameIndex(
2330           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2331                                false));
2332       }
2333
2334       // Store the integer parameter registers.
2335       SmallVector<SDValue, 8> MemOps;
2336       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2337                                         getPointerTy());
2338       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2339       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2340         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2341                                   DAG.getIntPtrConstant(Offset));
2342         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2343                                      &X86::GR64RegClass);
2344         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2345         SDValue Store =
2346           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2347                        MachinePointerInfo::getFixedStack(
2348                          FuncInfo->getRegSaveFrameIndex(), Offset),
2349                        false, false, 0);
2350         MemOps.push_back(Store);
2351         Offset += 8;
2352       }
2353
2354       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2355         // Now store the XMM (fp + vector) parameter registers.
2356         SmallVector<SDValue, 11> SaveXMMOps;
2357         SaveXMMOps.push_back(Chain);
2358
2359         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2360         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2361         SaveXMMOps.push_back(ALVal);
2362
2363         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2364                                FuncInfo->getRegSaveFrameIndex()));
2365         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2366                                FuncInfo->getVarArgsFPOffset()));
2367
2368         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2369           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2370                                        &X86::VR128RegClass);
2371           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2372           SaveXMMOps.push_back(Val);
2373         }
2374         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2375                                      MVT::Other,
2376                                      &SaveXMMOps[0], SaveXMMOps.size()));
2377       }
2378
2379       if (!MemOps.empty())
2380         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2381                             &MemOps[0], MemOps.size());
2382     }
2383   }
2384
2385   // Some CCs need callee pop.
2386   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2387                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2388     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2389   } else {
2390     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2391     // If this is an sret function, the return should pop the hidden pointer.
2392     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2393         argsAreStructReturn(Ins) == StackStructReturn)
2394       FuncInfo->setBytesToPopOnReturn(4);
2395   }
2396
2397   if (!Is64Bit) {
2398     // RegSaveFrameIndex is X86-64 only.
2399     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2400     if (CallConv == CallingConv::X86_FastCall ||
2401         CallConv == CallingConv::X86_ThisCall)
2402       // fastcc functions can't have varargs.
2403       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2404   }
2405
2406   FuncInfo->setArgumentStackSize(StackSize);
2407
2408   return Chain;
2409 }
2410
2411 SDValue
2412 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2413                                     SDValue StackPtr, SDValue Arg,
2414                                     SDLoc dl, SelectionDAG &DAG,
2415                                     const CCValAssign &VA,
2416                                     ISD::ArgFlagsTy Flags) const {
2417   unsigned LocMemOffset = VA.getLocMemOffset();
2418   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2419   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2420   if (Flags.isByVal())
2421     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2422
2423   return DAG.getStore(Chain, dl, Arg, PtrOff,
2424                       MachinePointerInfo::getStack(LocMemOffset),
2425                       false, false, 0);
2426 }
2427
2428 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2429 /// optimization is performed and it is required.
2430 SDValue
2431 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2432                                            SDValue &OutRetAddr, SDValue Chain,
2433                                            bool IsTailCall, bool Is64Bit,
2434                                            int FPDiff, SDLoc dl) const {
2435   // Adjust the Return address stack slot.
2436   EVT VT = getPointerTy();
2437   OutRetAddr = getReturnAddressFrameIndex(DAG);
2438
2439   // Load the "old" Return address.
2440   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2441                            false, false, false, 0);
2442   return SDValue(OutRetAddr.getNode(), 1);
2443 }
2444
2445 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2446 /// optimization is performed and it is required (FPDiff!=0).
2447 static SDValue
2448 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2449                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2450                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2451   // Store the return address to the appropriate stack slot.
2452   if (!FPDiff) return Chain;
2453   // Calculate the new stack slot for the return address.
2454   int NewReturnAddrFI =
2455     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2456   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2457   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2458                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2459                        false, false, 0);
2460   return Chain;
2461 }
2462
2463 SDValue
2464 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2465                              SmallVectorImpl<SDValue> &InVals) const {
2466   SelectionDAG &DAG                     = CLI.DAG;
2467   SDLoc &dl                             = CLI.DL;
2468   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2469   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2470   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2471   SDValue Chain                         = CLI.Chain;
2472   SDValue Callee                        = CLI.Callee;
2473   CallingConv::ID CallConv              = CLI.CallConv;
2474   bool &isTailCall                      = CLI.IsTailCall;
2475   bool isVarArg                         = CLI.IsVarArg;
2476
2477   MachineFunction &MF = DAG.getMachineFunction();
2478   bool Is64Bit        = Subtarget->is64Bit();
2479   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2480   bool IsWindows      = Subtarget->isTargetWindows();
2481   StructReturnType SR = callIsStructReturn(Outs);
2482   bool IsSibcall      = false;
2483
2484   if (MF.getTarget().Options.DisableTailCalls)
2485     isTailCall = false;
2486
2487   if (isTailCall) {
2488     // Check if it's really possible to do a tail call.
2489     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2490                     isVarArg, SR != NotStructReturn,
2491                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2492                     Outs, OutVals, Ins, DAG);
2493
2494     // Sibcalls are automatically detected tailcalls which do not require
2495     // ABI changes.
2496     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2497       IsSibcall = true;
2498
2499     if (isTailCall)
2500       ++NumTailCalls;
2501   }
2502
2503   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2504          "Var args not supported with calling convention fastcc, ghc or hipe");
2505
2506   // Analyze operands of the call, assigning locations to each operand.
2507   SmallVector<CCValAssign, 16> ArgLocs;
2508   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2509                  ArgLocs, *DAG.getContext());
2510
2511   // Allocate shadow area for Win64
2512   if (IsWin64)
2513     CCInfo.AllocateStack(32, 8);
2514
2515   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2516
2517   // Get a count of how many bytes are to be pushed on the stack.
2518   unsigned NumBytes = CCInfo.getNextStackOffset();
2519   if (IsSibcall)
2520     // This is a sibcall. The memory operands are available in caller's
2521     // own caller's stack.
2522     NumBytes = 0;
2523   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2524            IsTailCallConvention(CallConv))
2525     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2526
2527   int FPDiff = 0;
2528   if (isTailCall && !IsSibcall) {
2529     // Lower arguments at fp - stackoffset + fpdiff.
2530     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2531     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2532
2533     FPDiff = NumBytesCallerPushed - NumBytes;
2534
2535     // Set the delta of movement of the returnaddr stackslot.
2536     // But only set if delta is greater than previous delta.
2537     if (FPDiff < X86Info->getTCReturnAddrDelta())
2538       X86Info->setTCReturnAddrDelta(FPDiff);
2539   }
2540
2541   if (!IsSibcall)
2542     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2543                                  dl);
2544
2545   SDValue RetAddrFrIdx;
2546   // Load return address for tail calls.
2547   if (isTailCall && FPDiff)
2548     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2549                                     Is64Bit, FPDiff, dl);
2550
2551   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2552   SmallVector<SDValue, 8> MemOpChains;
2553   SDValue StackPtr;
2554
2555   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2556   // of tail call optimization arguments are handle later.
2557   const X86RegisterInfo *RegInfo =
2558     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2559   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2560     CCValAssign &VA = ArgLocs[i];
2561     EVT RegVT = VA.getLocVT();
2562     SDValue Arg = OutVals[i];
2563     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2564     bool isByVal = Flags.isByVal();
2565
2566     // Promote the value if needed.
2567     switch (VA.getLocInfo()) {
2568     default: llvm_unreachable("Unknown loc info!");
2569     case CCValAssign::Full: break;
2570     case CCValAssign::SExt:
2571       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2572       break;
2573     case CCValAssign::ZExt:
2574       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2575       break;
2576     case CCValAssign::AExt:
2577       if (RegVT.is128BitVector()) {
2578         // Special case: passing MMX values in XMM registers.
2579         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2580         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2581         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2582       } else
2583         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2584       break;
2585     case CCValAssign::BCvt:
2586       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2587       break;
2588     case CCValAssign::Indirect: {
2589       // Store the argument.
2590       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2591       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2592       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2593                            MachinePointerInfo::getFixedStack(FI),
2594                            false, false, 0);
2595       Arg = SpillSlot;
2596       break;
2597     }
2598     }
2599
2600     if (VA.isRegLoc()) {
2601       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2602       if (isVarArg && IsWin64) {
2603         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2604         // shadow reg if callee is a varargs function.
2605         unsigned ShadowReg = 0;
2606         switch (VA.getLocReg()) {
2607         case X86::XMM0: ShadowReg = X86::RCX; break;
2608         case X86::XMM1: ShadowReg = X86::RDX; break;
2609         case X86::XMM2: ShadowReg = X86::R8; break;
2610         case X86::XMM3: ShadowReg = X86::R9; break;
2611         }
2612         if (ShadowReg)
2613           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2614       }
2615     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2616       assert(VA.isMemLoc());
2617       if (StackPtr.getNode() == 0)
2618         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2619                                       getPointerTy());
2620       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2621                                              dl, DAG, VA, Flags));
2622     }
2623   }
2624
2625   if (!MemOpChains.empty())
2626     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2627                         &MemOpChains[0], MemOpChains.size());
2628
2629   if (Subtarget->isPICStyleGOT()) {
2630     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2631     // GOT pointer.
2632     if (!isTailCall) {
2633       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2634                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2635     } else {
2636       // If we are tail calling and generating PIC/GOT style code load the
2637       // address of the callee into ECX. The value in ecx is used as target of
2638       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2639       // for tail calls on PIC/GOT architectures. Normally we would just put the
2640       // address of GOT into ebx and then call target@PLT. But for tail calls
2641       // ebx would be restored (since ebx is callee saved) before jumping to the
2642       // target@PLT.
2643
2644       // Note: The actual moving to ECX is done further down.
2645       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2646       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2647           !G->getGlobal()->hasProtectedVisibility())
2648         Callee = LowerGlobalAddress(Callee, DAG);
2649       else if (isa<ExternalSymbolSDNode>(Callee))
2650         Callee = LowerExternalSymbol(Callee, DAG);
2651     }
2652   }
2653
2654   if (Is64Bit && isVarArg && !IsWin64) {
2655     // From AMD64 ABI document:
2656     // For calls that may call functions that use varargs or stdargs
2657     // (prototype-less calls or calls to functions containing ellipsis (...) in
2658     // the declaration) %al is used as hidden argument to specify the number
2659     // of SSE registers used. The contents of %al do not need to match exactly
2660     // the number of registers, but must be an ubound on the number of SSE
2661     // registers used and is in the range 0 - 8 inclusive.
2662
2663     // Count the number of XMM registers allocated.
2664     static const uint16_t XMMArgRegs[] = {
2665       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2666       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2667     };
2668     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2669     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2670            && "SSE registers cannot be used when SSE is disabled");
2671
2672     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2673                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2674   }
2675
2676   // For tail calls lower the arguments to the 'real' stack slot.
2677   if (isTailCall) {
2678     // Force all the incoming stack arguments to be loaded from the stack
2679     // before any new outgoing arguments are stored to the stack, because the
2680     // outgoing stack slots may alias the incoming argument stack slots, and
2681     // the alias isn't otherwise explicit. This is slightly more conservative
2682     // than necessary, because it means that each store effectively depends
2683     // on every argument instead of just those arguments it would clobber.
2684     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2685
2686     SmallVector<SDValue, 8> MemOpChains2;
2687     SDValue FIN;
2688     int FI = 0;
2689     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2690       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2691         CCValAssign &VA = ArgLocs[i];
2692         if (VA.isRegLoc())
2693           continue;
2694         assert(VA.isMemLoc());
2695         SDValue Arg = OutVals[i];
2696         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2697         // Create frame index.
2698         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2699         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2700         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2701         FIN = DAG.getFrameIndex(FI, getPointerTy());
2702
2703         if (Flags.isByVal()) {
2704           // Copy relative to framepointer.
2705           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2706           if (StackPtr.getNode() == 0)
2707             StackPtr = DAG.getCopyFromReg(Chain, dl,
2708                                           RegInfo->getStackRegister(),
2709                                           getPointerTy());
2710           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2711
2712           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2713                                                            ArgChain,
2714                                                            Flags, DAG, dl));
2715         } else {
2716           // Store relative to framepointer.
2717           MemOpChains2.push_back(
2718             DAG.getStore(ArgChain, dl, Arg, FIN,
2719                          MachinePointerInfo::getFixedStack(FI),
2720                          false, false, 0));
2721         }
2722       }
2723     }
2724
2725     if (!MemOpChains2.empty())
2726       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2727                           &MemOpChains2[0], MemOpChains2.size());
2728
2729     // Store the return address to the appropriate stack slot.
2730     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2731                                      getPointerTy(), RegInfo->getSlotSize(),
2732                                      FPDiff, dl);
2733   }
2734
2735   // Build a sequence of copy-to-reg nodes chained together with token chain
2736   // and flag operands which copy the outgoing args into registers.
2737   SDValue InFlag;
2738   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2739     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2740                              RegsToPass[i].second, InFlag);
2741     InFlag = Chain.getValue(1);
2742   }
2743
2744   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2745     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2746     // In the 64-bit large code model, we have to make all calls
2747     // through a register, since the call instruction's 32-bit
2748     // pc-relative offset may not be large enough to hold the whole
2749     // address.
2750   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2751     // If the callee is a GlobalAddress node (quite common, every direct call
2752     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2753     // it.
2754
2755     // We should use extra load for direct calls to dllimported functions in
2756     // non-JIT mode.
2757     const GlobalValue *GV = G->getGlobal();
2758     if (!GV->hasDLLImportLinkage()) {
2759       unsigned char OpFlags = 0;
2760       bool ExtraLoad = false;
2761       unsigned WrapperKind = ISD::DELETED_NODE;
2762
2763       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2764       // external symbols most go through the PLT in PIC mode.  If the symbol
2765       // has hidden or protected visibility, or if it is static or local, then
2766       // we don't need to use the PLT - we can directly call it.
2767       if (Subtarget->isTargetELF() &&
2768           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2769           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2770         OpFlags = X86II::MO_PLT;
2771       } else if (Subtarget->isPICStyleStubAny() &&
2772                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2773                  (!Subtarget->getTargetTriple().isMacOSX() ||
2774                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2775         // PC-relative references to external symbols should go through $stub,
2776         // unless we're building with the leopard linker or later, which
2777         // automatically synthesizes these stubs.
2778         OpFlags = X86II::MO_DARWIN_STUB;
2779       } else if (Subtarget->isPICStyleRIPRel() &&
2780                  isa<Function>(GV) &&
2781                  cast<Function>(GV)->getAttributes().
2782                    hasAttribute(AttributeSet::FunctionIndex,
2783                                 Attribute::NonLazyBind)) {
2784         // If the function is marked as non-lazy, generate an indirect call
2785         // which loads from the GOT directly. This avoids runtime overhead
2786         // at the cost of eager binding (and one extra byte of encoding).
2787         OpFlags = X86II::MO_GOTPCREL;
2788         WrapperKind = X86ISD::WrapperRIP;
2789         ExtraLoad = true;
2790       }
2791
2792       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2793                                           G->getOffset(), OpFlags);
2794
2795       // Add a wrapper if needed.
2796       if (WrapperKind != ISD::DELETED_NODE)
2797         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2798       // Add extra indirection if needed.
2799       if (ExtraLoad)
2800         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2801                              MachinePointerInfo::getGOT(),
2802                              false, false, false, 0);
2803     }
2804   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2805     unsigned char OpFlags = 0;
2806
2807     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2808     // external symbols should go through the PLT.
2809     if (Subtarget->isTargetELF() &&
2810         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2811       OpFlags = X86II::MO_PLT;
2812     } else if (Subtarget->isPICStyleStubAny() &&
2813                (!Subtarget->getTargetTriple().isMacOSX() ||
2814                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2815       // PC-relative references to external symbols should go through $stub,
2816       // unless we're building with the leopard linker or later, which
2817       // automatically synthesizes these stubs.
2818       OpFlags = X86II::MO_DARWIN_STUB;
2819     }
2820
2821     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2822                                          OpFlags);
2823   }
2824
2825   // Returns a chain & a flag for retval copy to use.
2826   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2827   SmallVector<SDValue, 8> Ops;
2828
2829   if (!IsSibcall && isTailCall) {
2830     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2831                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2832     InFlag = Chain.getValue(1);
2833   }
2834
2835   Ops.push_back(Chain);
2836   Ops.push_back(Callee);
2837
2838   if (isTailCall)
2839     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2840
2841   // Add argument registers to the end of the list so that they are known live
2842   // into the call.
2843   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2844     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2845                                   RegsToPass[i].second.getValueType()));
2846
2847   // Add a register mask operand representing the call-preserved registers.
2848   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2849   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2850   assert(Mask && "Missing call preserved mask for calling convention");
2851   Ops.push_back(DAG.getRegisterMask(Mask));
2852
2853   if (InFlag.getNode())
2854     Ops.push_back(InFlag);
2855
2856   if (isTailCall) {
2857     // We used to do:
2858     //// If this is the first return lowered for this function, add the regs
2859     //// to the liveout set for the function.
2860     // This isn't right, although it's probably harmless on x86; liveouts
2861     // should be computed from returns not tail calls.  Consider a void
2862     // function making a tail call to a function returning int.
2863     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2864   }
2865
2866   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2867   InFlag = Chain.getValue(1);
2868
2869   // Create the CALLSEQ_END node.
2870   unsigned NumBytesForCalleeToPush;
2871   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2872                        getTargetMachine().Options.GuaranteedTailCallOpt))
2873     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2874   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2875            SR == StackStructReturn)
2876     // If this is a call to a struct-return function, the callee
2877     // pops the hidden struct pointer, so we have to push it back.
2878     // This is common for Darwin/X86, Linux & Mingw32 targets.
2879     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2880     NumBytesForCalleeToPush = 4;
2881   else
2882     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2883
2884   // Returns a flag for retval copy to use.
2885   if (!IsSibcall) {
2886     Chain = DAG.getCALLSEQ_END(Chain,
2887                                DAG.getIntPtrConstant(NumBytes, true),
2888                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2889                                                      true),
2890                                InFlag, dl);
2891     InFlag = Chain.getValue(1);
2892   }
2893
2894   // Handle result values, copying them out of physregs into vregs that we
2895   // return.
2896   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2897                          Ins, dl, DAG, InVals);
2898 }
2899
2900 //===----------------------------------------------------------------------===//
2901 //                Fast Calling Convention (tail call) implementation
2902 //===----------------------------------------------------------------------===//
2903
2904 //  Like std call, callee cleans arguments, convention except that ECX is
2905 //  reserved for storing the tail called function address. Only 2 registers are
2906 //  free for argument passing (inreg). Tail call optimization is performed
2907 //  provided:
2908 //                * tailcallopt is enabled
2909 //                * caller/callee are fastcc
2910 //  On X86_64 architecture with GOT-style position independent code only local
2911 //  (within module) calls are supported at the moment.
2912 //  To keep the stack aligned according to platform abi the function
2913 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2914 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2915 //  If a tail called function callee has more arguments than the caller the
2916 //  caller needs to make sure that there is room to move the RETADDR to. This is
2917 //  achieved by reserving an area the size of the argument delta right after the
2918 //  original REtADDR, but before the saved framepointer or the spilled registers
2919 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2920 //  stack layout:
2921 //    arg1
2922 //    arg2
2923 //    RETADDR
2924 //    [ new RETADDR
2925 //      move area ]
2926 //    (possible EBP)
2927 //    ESI
2928 //    EDI
2929 //    local1 ..
2930
2931 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2932 /// for a 16 byte align requirement.
2933 unsigned
2934 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2935                                                SelectionDAG& DAG) const {
2936   MachineFunction &MF = DAG.getMachineFunction();
2937   const TargetMachine &TM = MF.getTarget();
2938   const X86RegisterInfo *RegInfo =
2939     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2940   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2941   unsigned StackAlignment = TFI.getStackAlignment();
2942   uint64_t AlignMask = StackAlignment - 1;
2943   int64_t Offset = StackSize;
2944   unsigned SlotSize = RegInfo->getSlotSize();
2945   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2946     // Number smaller than 12 so just add the difference.
2947     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2948   } else {
2949     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2950     Offset = ((~AlignMask) & Offset) + StackAlignment +
2951       (StackAlignment-SlotSize);
2952   }
2953   return Offset;
2954 }
2955
2956 /// MatchingStackOffset - Return true if the given stack call argument is
2957 /// already available in the same position (relatively) of the caller's
2958 /// incoming argument stack.
2959 static
2960 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2961                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2962                          const X86InstrInfo *TII) {
2963   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2964   int FI = INT_MAX;
2965   if (Arg.getOpcode() == ISD::CopyFromReg) {
2966     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2967     if (!TargetRegisterInfo::isVirtualRegister(VR))
2968       return false;
2969     MachineInstr *Def = MRI->getVRegDef(VR);
2970     if (!Def)
2971       return false;
2972     if (!Flags.isByVal()) {
2973       if (!TII->isLoadFromStackSlot(Def, FI))
2974         return false;
2975     } else {
2976       unsigned Opcode = Def->getOpcode();
2977       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2978           Def->getOperand(1).isFI()) {
2979         FI = Def->getOperand(1).getIndex();
2980         Bytes = Flags.getByValSize();
2981       } else
2982         return false;
2983     }
2984   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2985     if (Flags.isByVal())
2986       // ByVal argument is passed in as a pointer but it's now being
2987       // dereferenced. e.g.
2988       // define @foo(%struct.X* %A) {
2989       //   tail call @bar(%struct.X* byval %A)
2990       // }
2991       return false;
2992     SDValue Ptr = Ld->getBasePtr();
2993     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2994     if (!FINode)
2995       return false;
2996     FI = FINode->getIndex();
2997   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2998     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2999     FI = FINode->getIndex();
3000     Bytes = Flags.getByValSize();
3001   } else
3002     return false;
3003
3004   assert(FI != INT_MAX);
3005   if (!MFI->isFixedObjectIndex(FI))
3006     return false;
3007   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3008 }
3009
3010 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3011 /// for tail call optimization. Targets which want to do tail call
3012 /// optimization should implement this function.
3013 bool
3014 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3015                                                      CallingConv::ID CalleeCC,
3016                                                      bool isVarArg,
3017                                                      bool isCalleeStructRet,
3018                                                      bool isCallerStructRet,
3019                                                      Type *RetTy,
3020                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3021                                     const SmallVectorImpl<SDValue> &OutVals,
3022                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3023                                                      SelectionDAG &DAG) const {
3024   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3025     return false;
3026
3027   // If -tailcallopt is specified, make fastcc functions tail-callable.
3028   const MachineFunction &MF = DAG.getMachineFunction();
3029   const Function *CallerF = MF.getFunction();
3030
3031   // If the function return type is x86_fp80 and the callee return type is not,
3032   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3033   // perform a tailcall optimization here.
3034   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3035     return false;
3036
3037   CallingConv::ID CallerCC = CallerF->getCallingConv();
3038   bool CCMatch = CallerCC == CalleeCC;
3039   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3040   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3041
3042   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3043     if (IsTailCallConvention(CalleeCC) && CCMatch)
3044       return true;
3045     return false;
3046   }
3047
3048   // Look for obvious safe cases to perform tail call optimization that do not
3049   // require ABI changes. This is what gcc calls sibcall.
3050
3051   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3052   // emit a special epilogue.
3053   const X86RegisterInfo *RegInfo =
3054     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3055   if (RegInfo->needsStackRealignment(MF))
3056     return false;
3057
3058   // Also avoid sibcall optimization if either caller or callee uses struct
3059   // return semantics.
3060   if (isCalleeStructRet || isCallerStructRet)
3061     return false;
3062
3063   // An stdcall caller is expected to clean up its arguments; the callee
3064   // isn't going to do that.
3065   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3066     return false;
3067
3068   // Do not sibcall optimize vararg calls unless all arguments are passed via
3069   // registers.
3070   if (isVarArg && !Outs.empty()) {
3071
3072     // Optimizing for varargs on Win64 is unlikely to be safe without
3073     // additional testing.
3074     if (IsCalleeWin64 || IsCallerWin64)
3075       return false;
3076
3077     SmallVector<CCValAssign, 16> ArgLocs;
3078     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3079                    getTargetMachine(), ArgLocs, *DAG.getContext());
3080
3081     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3082     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3083       if (!ArgLocs[i].isRegLoc())
3084         return false;
3085   }
3086
3087   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3088   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3089   // this into a sibcall.
3090   bool Unused = false;
3091   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3092     if (!Ins[i].Used) {
3093       Unused = true;
3094       break;
3095     }
3096   }
3097   if (Unused) {
3098     SmallVector<CCValAssign, 16> RVLocs;
3099     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3100                    getTargetMachine(), RVLocs, *DAG.getContext());
3101     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3102     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3103       CCValAssign &VA = RVLocs[i];
3104       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3105         return false;
3106     }
3107   }
3108
3109   // If the calling conventions do not match, then we'd better make sure the
3110   // results are returned in the same way as what the caller expects.
3111   if (!CCMatch) {
3112     SmallVector<CCValAssign, 16> RVLocs1;
3113     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3114                     getTargetMachine(), RVLocs1, *DAG.getContext());
3115     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3116
3117     SmallVector<CCValAssign, 16> RVLocs2;
3118     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs2, *DAG.getContext());
3120     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     if (RVLocs1.size() != RVLocs2.size())
3123       return false;
3124     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3125       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3126         return false;
3127       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3128         return false;
3129       if (RVLocs1[i].isRegLoc()) {
3130         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3131           return false;
3132       } else {
3133         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3134           return false;
3135       }
3136     }
3137   }
3138
3139   // If the callee takes no arguments then go on to check the results of the
3140   // call.
3141   if (!Outs.empty()) {
3142     // Check if stack adjustment is needed. For now, do not do this if any
3143     // argument is passed on the stack.
3144     SmallVector<CCValAssign, 16> ArgLocs;
3145     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3146                    getTargetMachine(), ArgLocs, *DAG.getContext());
3147
3148     // Allocate shadow area for Win64
3149     if (IsCalleeWin64)
3150       CCInfo.AllocateStack(32, 8);
3151
3152     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3153     if (CCInfo.getNextStackOffset()) {
3154       MachineFunction &MF = DAG.getMachineFunction();
3155       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3156         return false;
3157
3158       // Check if the arguments are already laid out in the right way as
3159       // the caller's fixed stack objects.
3160       MachineFrameInfo *MFI = MF.getFrameInfo();
3161       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3162       const X86InstrInfo *TII =
3163         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3164       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3165         CCValAssign &VA = ArgLocs[i];
3166         SDValue Arg = OutVals[i];
3167         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3168         if (VA.getLocInfo() == CCValAssign::Indirect)
3169           return false;
3170         if (!VA.isRegLoc()) {
3171           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3172                                    MFI, MRI, TII))
3173             return false;
3174         }
3175       }
3176     }
3177
3178     // If the tailcall address may be in a register, then make sure it's
3179     // possible to register allocate for it. In 32-bit, the call address can
3180     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3181     // callee-saved registers are restored. These happen to be the same
3182     // registers used to pass 'inreg' arguments so watch out for those.
3183     if (!Subtarget->is64Bit() &&
3184         ((!isa<GlobalAddressSDNode>(Callee) &&
3185           !isa<ExternalSymbolSDNode>(Callee)) ||
3186          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3187       unsigned NumInRegs = 0;
3188       // In PIC we need an extra register to formulate the address computation
3189       // for the callee.
3190       unsigned MaxInRegs =
3191           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3192
3193       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3194         CCValAssign &VA = ArgLocs[i];
3195         if (!VA.isRegLoc())
3196           continue;
3197         unsigned Reg = VA.getLocReg();
3198         switch (Reg) {
3199         default: break;
3200         case X86::EAX: case X86::EDX: case X86::ECX:
3201           if (++NumInRegs == MaxInRegs)
3202             return false;
3203           break;
3204         }
3205       }
3206     }
3207   }
3208
3209   return true;
3210 }
3211
3212 FastISel *
3213 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3214                                   const TargetLibraryInfo *libInfo) const {
3215   return X86::createFastISel(funcInfo, libInfo);
3216 }
3217
3218 //===----------------------------------------------------------------------===//
3219 //                           Other Lowering Hooks
3220 //===----------------------------------------------------------------------===//
3221
3222 static bool MayFoldLoad(SDValue Op) {
3223   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3224 }
3225
3226 static bool MayFoldIntoStore(SDValue Op) {
3227   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3228 }
3229
3230 static bool isTargetShuffle(unsigned Opcode) {
3231   switch(Opcode) {
3232   default: return false;
3233   case X86ISD::PSHUFD:
3234   case X86ISD::PSHUFHW:
3235   case X86ISD::PSHUFLW:
3236   case X86ISD::SHUFP:
3237   case X86ISD::PALIGNR:
3238   case X86ISD::MOVLHPS:
3239   case X86ISD::MOVLHPD:
3240   case X86ISD::MOVHLPS:
3241   case X86ISD::MOVLPS:
3242   case X86ISD::MOVLPD:
3243   case X86ISD::MOVSHDUP:
3244   case X86ISD::MOVSLDUP:
3245   case X86ISD::MOVDDUP:
3246   case X86ISD::MOVSS:
3247   case X86ISD::MOVSD:
3248   case X86ISD::UNPCKL:
3249   case X86ISD::UNPCKH:
3250   case X86ISD::VPERMILP:
3251   case X86ISD::VPERM2X128:
3252   case X86ISD::VPERMI:
3253     return true;
3254   }
3255 }
3256
3257 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3258                                     SDValue V1, SelectionDAG &DAG) {
3259   switch(Opc) {
3260   default: llvm_unreachable("Unknown x86 shuffle node");
3261   case X86ISD::MOVSHDUP:
3262   case X86ISD::MOVSLDUP:
3263   case X86ISD::MOVDDUP:
3264     return DAG.getNode(Opc, dl, VT, V1);
3265   }
3266 }
3267
3268 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3269                                     SDValue V1, unsigned TargetMask,
3270                                     SelectionDAG &DAG) {
3271   switch(Opc) {
3272   default: llvm_unreachable("Unknown x86 shuffle node");
3273   case X86ISD::PSHUFD:
3274   case X86ISD::PSHUFHW:
3275   case X86ISD::PSHUFLW:
3276   case X86ISD::VPERMILP:
3277   case X86ISD::VPERMI:
3278     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3279   }
3280 }
3281
3282 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3283                                     SDValue V1, SDValue V2, unsigned TargetMask,
3284                                     SelectionDAG &DAG) {
3285   switch(Opc) {
3286   default: llvm_unreachable("Unknown x86 shuffle node");
3287   case X86ISD::PALIGNR:
3288   case X86ISD::SHUFP:
3289   case X86ISD::VPERM2X128:
3290     return DAG.getNode(Opc, dl, VT, V1, V2,
3291                        DAG.getConstant(TargetMask, MVT::i8));
3292   }
3293 }
3294
3295 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3296                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3297   switch(Opc) {
3298   default: llvm_unreachable("Unknown x86 shuffle node");
3299   case X86ISD::MOVLHPS:
3300   case X86ISD::MOVLHPD:
3301   case X86ISD::MOVHLPS:
3302   case X86ISD::MOVLPS:
3303   case X86ISD::MOVLPD:
3304   case X86ISD::MOVSS:
3305   case X86ISD::MOVSD:
3306   case X86ISD::UNPCKL:
3307   case X86ISD::UNPCKH:
3308     return DAG.getNode(Opc, dl, VT, V1, V2);
3309   }
3310 }
3311
3312 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3313   MachineFunction &MF = DAG.getMachineFunction();
3314   const X86RegisterInfo *RegInfo =
3315     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3316   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3317   int ReturnAddrIndex = FuncInfo->getRAIndex();
3318
3319   if (ReturnAddrIndex == 0) {
3320     // Set up a frame object for the return address.
3321     unsigned SlotSize = RegInfo->getSlotSize();
3322     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3323                                                            false);
3324     FuncInfo->setRAIndex(ReturnAddrIndex);
3325   }
3326
3327   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3328 }
3329
3330 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3331                                        bool hasSymbolicDisplacement) {
3332   // Offset should fit into 32 bit immediate field.
3333   if (!isInt<32>(Offset))
3334     return false;
3335
3336   // If we don't have a symbolic displacement - we don't have any extra
3337   // restrictions.
3338   if (!hasSymbolicDisplacement)
3339     return true;
3340
3341   // FIXME: Some tweaks might be needed for medium code model.
3342   if (M != CodeModel::Small && M != CodeModel::Kernel)
3343     return false;
3344
3345   // For small code model we assume that latest object is 16MB before end of 31
3346   // bits boundary. We may also accept pretty large negative constants knowing
3347   // that all objects are in the positive half of address space.
3348   if (M == CodeModel::Small && Offset < 16*1024*1024)
3349     return true;
3350
3351   // For kernel code model we know that all object resist in the negative half
3352   // of 32bits address space. We may not accept negative offsets, since they may
3353   // be just off and we may accept pretty large positive ones.
3354   if (M == CodeModel::Kernel && Offset > 0)
3355     return true;
3356
3357   return false;
3358 }
3359
3360 /// isCalleePop - Determines whether the callee is required to pop its
3361 /// own arguments. Callee pop is necessary to support tail calls.
3362 bool X86::isCalleePop(CallingConv::ID CallingConv,
3363                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3364   if (IsVarArg)
3365     return false;
3366
3367   switch (CallingConv) {
3368   default:
3369     return false;
3370   case CallingConv::X86_StdCall:
3371     return !is64Bit;
3372   case CallingConv::X86_FastCall:
3373     return !is64Bit;
3374   case CallingConv::X86_ThisCall:
3375     return !is64Bit;
3376   case CallingConv::Fast:
3377     return TailCallOpt;
3378   case CallingConv::GHC:
3379     return TailCallOpt;
3380   case CallingConv::HiPE:
3381     return TailCallOpt;
3382   }
3383 }
3384
3385 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3386 /// specific condition code, returning the condition code and the LHS/RHS of the
3387 /// comparison to make.
3388 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3389                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3390   if (!isFP) {
3391     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3392       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3393         // X > -1   -> X == 0, jump !sign.
3394         RHS = DAG.getConstant(0, RHS.getValueType());
3395         return X86::COND_NS;
3396       }
3397       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3398         // X < 0   -> X == 0, jump on sign.
3399         return X86::COND_S;
3400       }
3401       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3402         // X < 1   -> X <= 0
3403         RHS = DAG.getConstant(0, RHS.getValueType());
3404         return X86::COND_LE;
3405       }
3406     }
3407
3408     switch (SetCCOpcode) {
3409     default: llvm_unreachable("Invalid integer condition!");
3410     case ISD::SETEQ:  return X86::COND_E;
3411     case ISD::SETGT:  return X86::COND_G;
3412     case ISD::SETGE:  return X86::COND_GE;
3413     case ISD::SETLT:  return X86::COND_L;
3414     case ISD::SETLE:  return X86::COND_LE;
3415     case ISD::SETNE:  return X86::COND_NE;
3416     case ISD::SETULT: return X86::COND_B;
3417     case ISD::SETUGT: return X86::COND_A;
3418     case ISD::SETULE: return X86::COND_BE;
3419     case ISD::SETUGE: return X86::COND_AE;
3420     }
3421   }
3422
3423   // First determine if it is required or is profitable to flip the operands.
3424
3425   // If LHS is a foldable load, but RHS is not, flip the condition.
3426   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3427       !ISD::isNON_EXTLoad(RHS.getNode())) {
3428     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3429     std::swap(LHS, RHS);
3430   }
3431
3432   switch (SetCCOpcode) {
3433   default: break;
3434   case ISD::SETOLT:
3435   case ISD::SETOLE:
3436   case ISD::SETUGT:
3437   case ISD::SETUGE:
3438     std::swap(LHS, RHS);
3439     break;
3440   }
3441
3442   // On a floating point condition, the flags are set as follows:
3443   // ZF  PF  CF   op
3444   //  0 | 0 | 0 | X > Y
3445   //  0 | 0 | 1 | X < Y
3446   //  1 | 0 | 0 | X == Y
3447   //  1 | 1 | 1 | unordered
3448   switch (SetCCOpcode) {
3449   default: llvm_unreachable("Condcode should be pre-legalized away");
3450   case ISD::SETUEQ:
3451   case ISD::SETEQ:   return X86::COND_E;
3452   case ISD::SETOLT:              // flipped
3453   case ISD::SETOGT:
3454   case ISD::SETGT:   return X86::COND_A;
3455   case ISD::SETOLE:              // flipped
3456   case ISD::SETOGE:
3457   case ISD::SETGE:   return X86::COND_AE;
3458   case ISD::SETUGT:              // flipped
3459   case ISD::SETULT:
3460   case ISD::SETLT:   return X86::COND_B;
3461   case ISD::SETUGE:              // flipped
3462   case ISD::SETULE:
3463   case ISD::SETLE:   return X86::COND_BE;
3464   case ISD::SETONE:
3465   case ISD::SETNE:   return X86::COND_NE;
3466   case ISD::SETUO:   return X86::COND_P;
3467   case ISD::SETO:    return X86::COND_NP;
3468   case ISD::SETOEQ:
3469   case ISD::SETUNE:  return X86::COND_INVALID;
3470   }
3471 }
3472
3473 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3474 /// code. Current x86 isa includes the following FP cmov instructions:
3475 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3476 static bool hasFPCMov(unsigned X86CC) {
3477   switch (X86CC) {
3478   default:
3479     return false;
3480   case X86::COND_B:
3481   case X86::COND_BE:
3482   case X86::COND_E:
3483   case X86::COND_P:
3484   case X86::COND_A:
3485   case X86::COND_AE:
3486   case X86::COND_NE:
3487   case X86::COND_NP:
3488     return true;
3489   }
3490 }
3491
3492 /// isFPImmLegal - Returns true if the target can instruction select the
3493 /// specified FP immediate natively. If false, the legalizer will
3494 /// materialize the FP immediate as a load from a constant pool.
3495 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3496   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3497     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3498       return true;
3499   }
3500   return false;
3501 }
3502
3503 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3504 /// the specified range (L, H].
3505 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3506   return (Val < 0) || (Val >= Low && Val < Hi);
3507 }
3508
3509 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3510 /// specified value.
3511 static bool isUndefOrEqual(int Val, int CmpVal) {
3512   return (Val < 0 || Val == CmpVal);
3513 }
3514
3515 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3516 /// from position Pos and ending in Pos+Size, falls within the specified
3517 /// sequential range (L, L+Pos]. or is undef.
3518 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3519                                        unsigned Pos, unsigned Size, int Low) {
3520   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3521     if (!isUndefOrEqual(Mask[i], Low))
3522       return false;
3523   return true;
3524 }
3525
3526 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3527 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3528 /// the second operand.
3529 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3530   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3531     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3532   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3533     return (Mask[0] < 2 && Mask[1] < 2);
3534   return false;
3535 }
3536
3537 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3538 /// is suitable for input to PSHUFHW.
3539 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3540   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3541     return false;
3542
3543   // Lower quadword copied in order or undef.
3544   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3545     return false;
3546
3547   // Upper quadword shuffled.
3548   for (unsigned i = 4; i != 8; ++i)
3549     if (!isUndefOrInRange(Mask[i], 4, 8))
3550       return false;
3551
3552   if (VT == MVT::v16i16) {
3553     // Lower quadword copied in order or undef.
3554     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3555       return false;
3556
3557     // Upper quadword shuffled.
3558     for (unsigned i = 12; i != 16; ++i)
3559       if (!isUndefOrInRange(Mask[i], 12, 16))
3560         return false;
3561   }
3562
3563   return true;
3564 }
3565
3566 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3567 /// is suitable for input to PSHUFLW.
3568 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3569   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3570     return false;
3571
3572   // Upper quadword copied in order.
3573   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3574     return false;
3575
3576   // Lower quadword shuffled.
3577   for (unsigned i = 0; i != 4; ++i)
3578     if (!isUndefOrInRange(Mask[i], 0, 4))
3579       return false;
3580
3581   if (VT == MVT::v16i16) {
3582     // Upper quadword copied in order.
3583     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3584       return false;
3585
3586     // Lower quadword shuffled.
3587     for (unsigned i = 8; i != 12; ++i)
3588       if (!isUndefOrInRange(Mask[i], 8, 12))
3589         return false;
3590   }
3591
3592   return true;
3593 }
3594
3595 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3596 /// is suitable for input to PALIGNR.
3597 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3598                           const X86Subtarget *Subtarget) {
3599   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3600       (VT.is256BitVector() && !Subtarget->hasInt256()))
3601     return false;
3602
3603   unsigned NumElts = VT.getVectorNumElements();
3604   unsigned NumLanes = VT.getSizeInBits()/128;
3605   unsigned NumLaneElts = NumElts/NumLanes;
3606
3607   // Do not handle 64-bit element shuffles with palignr.
3608   if (NumLaneElts == 2)
3609     return false;
3610
3611   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3612     unsigned i;
3613     for (i = 0; i != NumLaneElts; ++i) {
3614       if (Mask[i+l] >= 0)
3615         break;
3616     }
3617
3618     // Lane is all undef, go to next lane
3619     if (i == NumLaneElts)
3620       continue;
3621
3622     int Start = Mask[i+l];
3623
3624     // Make sure its in this lane in one of the sources
3625     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3626         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3627       return false;
3628
3629     // If not lane 0, then we must match lane 0
3630     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3631       return false;
3632
3633     // Correct second source to be contiguous with first source
3634     if (Start >= (int)NumElts)
3635       Start -= NumElts - NumLaneElts;
3636
3637     // Make sure we're shifting in the right direction.
3638     if (Start <= (int)(i+l))
3639       return false;
3640
3641     Start -= i;
3642
3643     // Check the rest of the elements to see if they are consecutive.
3644     for (++i; i != NumLaneElts; ++i) {
3645       int Idx = Mask[i+l];
3646
3647       // Make sure its in this lane
3648       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3649           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3650         return false;
3651
3652       // If not lane 0, then we must match lane 0
3653       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3654         return false;
3655
3656       if (Idx >= (int)NumElts)
3657         Idx -= NumElts - NumLaneElts;
3658
3659       if (!isUndefOrEqual(Idx, Start+i))
3660         return false;
3661
3662     }
3663   }
3664
3665   return true;
3666 }
3667
3668 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3669 /// the two vector operands have swapped position.
3670 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3671                                      unsigned NumElems) {
3672   for (unsigned i = 0; i != NumElems; ++i) {
3673     int idx = Mask[i];
3674     if (idx < 0)
3675       continue;
3676     else if (idx < (int)NumElems)
3677       Mask[i] = idx + NumElems;
3678     else
3679       Mask[i] = idx - NumElems;
3680   }
3681 }
3682
3683 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3684 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3685 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3686 /// reverse of what x86 shuffles want.
3687 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3688                         bool Commuted = false) {
3689   if (!HasFp256 && VT.is256BitVector())
3690     return false;
3691
3692   unsigned NumElems = VT.getVectorNumElements();
3693   unsigned NumLanes = VT.getSizeInBits()/128;
3694   unsigned NumLaneElems = NumElems/NumLanes;
3695
3696   if (NumLaneElems != 2 && NumLaneElems != 4)
3697     return false;
3698
3699   // VSHUFPSY divides the resulting vector into 4 chunks.
3700   // The sources are also splitted into 4 chunks, and each destination
3701   // chunk must come from a different source chunk.
3702   //
3703   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3704   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3705   //
3706   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3707   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3708   //
3709   // VSHUFPDY divides the resulting vector into 4 chunks.
3710   // The sources are also splitted into 4 chunks, and each destination
3711   // chunk must come from a different source chunk.
3712   //
3713   //  SRC1 =>      X3       X2       X1       X0
3714   //  SRC2 =>      Y3       Y2       Y1       Y0
3715   //
3716   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3717   //
3718   unsigned HalfLaneElems = NumLaneElems/2;
3719   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3720     for (unsigned i = 0; i != NumLaneElems; ++i) {
3721       int Idx = Mask[i+l];
3722       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3723       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3724         return false;
3725       // For VSHUFPSY, the mask of the second half must be the same as the
3726       // first but with the appropriate offsets. This works in the same way as
3727       // VPERMILPS works with masks.
3728       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3729         continue;
3730       if (!isUndefOrEqual(Idx, Mask[i]+l))
3731         return false;
3732     }
3733   }
3734
3735   return true;
3736 }
3737
3738 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3739 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3740 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3741   if (!VT.is128BitVector())
3742     return false;
3743
3744   unsigned NumElems = VT.getVectorNumElements();
3745
3746   if (NumElems != 4)
3747     return false;
3748
3749   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3750   return isUndefOrEqual(Mask[0], 6) &&
3751          isUndefOrEqual(Mask[1], 7) &&
3752          isUndefOrEqual(Mask[2], 2) &&
3753          isUndefOrEqual(Mask[3], 3);
3754 }
3755
3756 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3757 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3758 /// <2, 3, 2, 3>
3759 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3760   if (!VT.is128BitVector())
3761     return false;
3762
3763   unsigned NumElems = VT.getVectorNumElements();
3764
3765   if (NumElems != 4)
3766     return false;
3767
3768   return isUndefOrEqual(Mask[0], 2) &&
3769          isUndefOrEqual(Mask[1], 3) &&
3770          isUndefOrEqual(Mask[2], 2) &&
3771          isUndefOrEqual(Mask[3], 3);
3772 }
3773
3774 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3775 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3776 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3777   if (!VT.is128BitVector())
3778     return false;
3779
3780   unsigned NumElems = VT.getVectorNumElements();
3781
3782   if (NumElems != 2 && NumElems != 4)
3783     return false;
3784
3785   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3786     if (!isUndefOrEqual(Mask[i], i + NumElems))
3787       return false;
3788
3789   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3790     if (!isUndefOrEqual(Mask[i], i))
3791       return false;
3792
3793   return true;
3794 }
3795
3796 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3798 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3799   if (!VT.is128BitVector())
3800     return false;
3801
3802   unsigned NumElems = VT.getVectorNumElements();
3803
3804   if (NumElems != 2 && NumElems != 4)
3805     return false;
3806
3807   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3808     if (!isUndefOrEqual(Mask[i], i))
3809       return false;
3810
3811   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3812     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3813       return false;
3814
3815   return true;
3816 }
3817
3818 //
3819 // Some special combinations that can be optimized.
3820 //
3821 static
3822 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3823                                SelectionDAG &DAG) {
3824   MVT VT = SVOp->getValueType(0).getSimpleVT();
3825   SDLoc dl(SVOp);
3826
3827   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3828     return SDValue();
3829
3830   ArrayRef<int> Mask = SVOp->getMask();
3831
3832   // These are the special masks that may be optimized.
3833   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3834   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3835   bool MatchEvenMask = true;
3836   bool MatchOddMask  = true;
3837   for (int i=0; i<8; ++i) {
3838     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3839       MatchEvenMask = false;
3840     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3841       MatchOddMask = false;
3842   }
3843
3844   if (!MatchEvenMask && !MatchOddMask)
3845     return SDValue();
3846
3847   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3848
3849   SDValue Op0 = SVOp->getOperand(0);
3850   SDValue Op1 = SVOp->getOperand(1);
3851
3852   if (MatchEvenMask) {
3853     // Shift the second operand right to 32 bits.
3854     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3855     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3856   } else {
3857     // Shift the first operand left to 32 bits.
3858     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3859     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3860   }
3861   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3862   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3863 }
3864
3865 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3866 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3867 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3868                          bool HasInt256, bool V2IsSplat = false) {
3869   unsigned NumElts = VT.getVectorNumElements();
3870
3871   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3872          "Unsupported vector type for unpckh");
3873
3874   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3875       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3876     return false;
3877
3878   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3879   // independently on 128-bit lanes.
3880   unsigned NumLanes = VT.getSizeInBits()/128;
3881   unsigned NumLaneElts = NumElts/NumLanes;
3882
3883   for (unsigned l = 0; l != NumLanes; ++l) {
3884     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3885          i != (l+1)*NumLaneElts;
3886          i += 2, ++j) {
3887       int BitI  = Mask[i];
3888       int BitI1 = Mask[i+1];
3889       if (!isUndefOrEqual(BitI, j))
3890         return false;
3891       if (V2IsSplat) {
3892         if (!isUndefOrEqual(BitI1, NumElts))
3893           return false;
3894       } else {
3895         if (!isUndefOrEqual(BitI1, j + NumElts))
3896           return false;
3897       }
3898     }
3899   }
3900
3901   return true;
3902 }
3903
3904 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3906 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3907                          bool HasInt256, bool V2IsSplat = false) {
3908   unsigned NumElts = VT.getVectorNumElements();
3909
3910   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3911          "Unsupported vector type for unpckh");
3912
3913   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3914       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3915     return false;
3916
3917   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3918   // independently on 128-bit lanes.
3919   unsigned NumLanes = VT.getSizeInBits()/128;
3920   unsigned NumLaneElts = NumElts/NumLanes;
3921
3922   for (unsigned l = 0; l != NumLanes; ++l) {
3923     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3924          i != (l+1)*NumLaneElts; i += 2, ++j) {
3925       int BitI  = Mask[i];
3926       int BitI1 = Mask[i+1];
3927       if (!isUndefOrEqual(BitI, j))
3928         return false;
3929       if (V2IsSplat) {
3930         if (isUndefOrEqual(BitI1, NumElts))
3931           return false;
3932       } else {
3933         if (!isUndefOrEqual(BitI1, j+NumElts))
3934           return false;
3935       }
3936     }
3937   }
3938   return true;
3939 }
3940
3941 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3942 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3943 /// <0, 0, 1, 1>
3944 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3945   unsigned NumElts = VT.getVectorNumElements();
3946   bool Is256BitVec = VT.is256BitVector();
3947
3948   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3949          "Unsupported vector type for unpckh");
3950
3951   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3952       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3953     return false;
3954
3955   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3956   // FIXME: Need a better way to get rid of this, there's no latency difference
3957   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3958   // the former later. We should also remove the "_undef" special mask.
3959   if (NumElts == 4 && Is256BitVec)
3960     return false;
3961
3962   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3963   // independently on 128-bit lanes.
3964   unsigned NumLanes = VT.getSizeInBits()/128;
3965   unsigned NumLaneElts = NumElts/NumLanes;
3966
3967   for (unsigned l = 0; l != NumLanes; ++l) {
3968     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3969          i != (l+1)*NumLaneElts;
3970          i += 2, ++j) {
3971       int BitI  = Mask[i];
3972       int BitI1 = Mask[i+1];
3973
3974       if (!isUndefOrEqual(BitI, j))
3975         return false;
3976       if (!isUndefOrEqual(BitI1, j))
3977         return false;
3978     }
3979   }
3980
3981   return true;
3982 }
3983
3984 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3985 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3986 /// <2, 2, 3, 3>
3987 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3988   unsigned NumElts = VT.getVectorNumElements();
3989
3990   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3991          "Unsupported vector type for unpckh");
3992
3993   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3994       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3995     return false;
3996
3997   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3998   // independently on 128-bit lanes.
3999   unsigned NumLanes = VT.getSizeInBits()/128;
4000   unsigned NumLaneElts = NumElts/NumLanes;
4001
4002   for (unsigned l = 0; l != NumLanes; ++l) {
4003     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4004          i != (l+1)*NumLaneElts; i += 2, ++j) {
4005       int BitI  = Mask[i];
4006       int BitI1 = Mask[i+1];
4007       if (!isUndefOrEqual(BitI, j))
4008         return false;
4009       if (!isUndefOrEqual(BitI1, j))
4010         return false;
4011     }
4012   }
4013   return true;
4014 }
4015
4016 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4017 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4018 /// MOVSD, and MOVD, i.e. setting the lowest element.
4019 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4020   if (VT.getVectorElementType().getSizeInBits() < 32)
4021     return false;
4022   if (!VT.is128BitVector())
4023     return false;
4024
4025   unsigned NumElts = VT.getVectorNumElements();
4026
4027   if (!isUndefOrEqual(Mask[0], NumElts))
4028     return false;
4029
4030   for (unsigned i = 1; i != NumElts; ++i)
4031     if (!isUndefOrEqual(Mask[i], i))
4032       return false;
4033
4034   return true;
4035 }
4036
4037 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4038 /// as permutations between 128-bit chunks or halves. As an example: this
4039 /// shuffle bellow:
4040 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4041 /// The first half comes from the second half of V1 and the second half from the
4042 /// the second half of V2.
4043 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4044   if (!HasFp256 || !VT.is256BitVector())
4045     return false;
4046
4047   // The shuffle result is divided into half A and half B. In total the two
4048   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4049   // B must come from C, D, E or F.
4050   unsigned HalfSize = VT.getVectorNumElements()/2;
4051   bool MatchA = false, MatchB = false;
4052
4053   // Check if A comes from one of C, D, E, F.
4054   for (unsigned Half = 0; Half != 4; ++Half) {
4055     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4056       MatchA = true;
4057       break;
4058     }
4059   }
4060
4061   // Check if B comes from one of C, D, E, F.
4062   for (unsigned Half = 0; Half != 4; ++Half) {
4063     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4064       MatchB = true;
4065       break;
4066     }
4067   }
4068
4069   return MatchA && MatchB;
4070 }
4071
4072 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4073 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4074 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4075   MVT VT = SVOp->getValueType(0).getSimpleVT();
4076
4077   unsigned HalfSize = VT.getVectorNumElements()/2;
4078
4079   unsigned FstHalf = 0, SndHalf = 0;
4080   for (unsigned i = 0; i < HalfSize; ++i) {
4081     if (SVOp->getMaskElt(i) > 0) {
4082       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4083       break;
4084     }
4085   }
4086   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4087     if (SVOp->getMaskElt(i) > 0) {
4088       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4089       break;
4090     }
4091   }
4092
4093   return (FstHalf | (SndHalf << 4));
4094 }
4095
4096 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4098 /// Note that VPERMIL mask matching is different depending whether theunderlying
4099 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4100 /// to the same elements of the low, but to the higher half of the source.
4101 /// In VPERMILPD the two lanes could be shuffled independently of each other
4102 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4103 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4104   if (!HasFp256)
4105     return false;
4106
4107   unsigned NumElts = VT.getVectorNumElements();
4108   // Only match 256-bit with 32/64-bit types
4109   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4110     return false;
4111
4112   unsigned NumLanes = VT.getSizeInBits()/128;
4113   unsigned LaneSize = NumElts/NumLanes;
4114   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4115     for (unsigned i = 0; i != LaneSize; ++i) {
4116       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4117         return false;
4118       if (NumElts != 8 || l == 0)
4119         continue;
4120       // VPERMILPS handling
4121       if (Mask[i] < 0)
4122         continue;
4123       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4124         return false;
4125     }
4126   }
4127
4128   return true;
4129 }
4130
4131 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4132 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4133 /// element of vector 2 and the other elements to come from vector 1 in order.
4134 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4135                                bool V2IsSplat = false, bool V2IsUndef = false) {
4136   if (!VT.is128BitVector())
4137     return false;
4138
4139   unsigned NumOps = VT.getVectorNumElements();
4140   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4141     return false;
4142
4143   if (!isUndefOrEqual(Mask[0], 0))
4144     return false;
4145
4146   for (unsigned i = 1; i != NumOps; ++i)
4147     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4148           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4149           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4150       return false;
4151
4152   return true;
4153 }
4154
4155 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4156 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4157 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4158 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4159                            const X86Subtarget *Subtarget) {
4160   if (!Subtarget->hasSSE3())
4161     return false;
4162
4163   unsigned NumElems = VT.getVectorNumElements();
4164
4165   if ((VT.is128BitVector() && NumElems != 4) ||
4166       (VT.is256BitVector() && NumElems != 8))
4167     return false;
4168
4169   // "i+1" is the value the indexed mask element must have
4170   for (unsigned i = 0; i != NumElems; i += 2)
4171     if (!isUndefOrEqual(Mask[i], i+1) ||
4172         !isUndefOrEqual(Mask[i+1], i+1))
4173       return false;
4174
4175   return true;
4176 }
4177
4178 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4179 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4180 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4181 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4182                            const X86Subtarget *Subtarget) {
4183   if (!Subtarget->hasSSE3())
4184     return false;
4185
4186   unsigned NumElems = VT.getVectorNumElements();
4187
4188   if ((VT.is128BitVector() && NumElems != 4) ||
4189       (VT.is256BitVector() && NumElems != 8))
4190     return false;
4191
4192   // "i" is the value the indexed mask element must have
4193   for (unsigned i = 0; i != NumElems; i += 2)
4194     if (!isUndefOrEqual(Mask[i], i) ||
4195         !isUndefOrEqual(Mask[i+1], i))
4196       return false;
4197
4198   return true;
4199 }
4200
4201 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4202 /// specifies a shuffle of elements that is suitable for input to 256-bit
4203 /// version of MOVDDUP.
4204 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4205   if (!HasFp256 || !VT.is256BitVector())
4206     return false;
4207
4208   unsigned NumElts = VT.getVectorNumElements();
4209   if (NumElts != 4)
4210     return false;
4211
4212   for (unsigned i = 0; i != NumElts/2; ++i)
4213     if (!isUndefOrEqual(Mask[i], 0))
4214       return false;
4215   for (unsigned i = NumElts/2; i != NumElts; ++i)
4216     if (!isUndefOrEqual(Mask[i], NumElts/2))
4217       return false;
4218   return true;
4219 }
4220
4221 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to 128-bit
4223 /// version of MOVDDUP.
4224 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4225   if (!VT.is128BitVector())
4226     return false;
4227
4228   unsigned e = VT.getVectorNumElements() / 2;
4229   for (unsigned i = 0; i != e; ++i)
4230     if (!isUndefOrEqual(Mask[i], i))
4231       return false;
4232   for (unsigned i = 0; i != e; ++i)
4233     if (!isUndefOrEqual(Mask[e+i], i))
4234       return false;
4235   return true;
4236 }
4237
4238 /// isVEXTRACTIndex - Return true if the specified
4239 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4240 /// suitable for instruction that extract 128 or 256 bit vectors
4241 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4242   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4243   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4244     return false;
4245
4246   // The index should be aligned on a vecWidth-bit boundary.
4247   uint64_t Index =
4248     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4249
4250   MVT VT = N->getValueType(0).getSimpleVT();
4251   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4252   bool Result = (Index * ElSize) % vecWidth == 0;
4253
4254   return Result;
4255 }
4256
4257 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4258 /// operand specifies a subvector insert that is suitable for input to
4259 /// insertion of 128 or 256-bit subvectors
4260 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4261   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4262   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4263     return false;
4264   // The index should be aligned on a vecWidth-bit boundary.
4265   uint64_t Index =
4266     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4267
4268   MVT VT = N->getValueType(0).getSimpleVT();
4269   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4270   bool Result = (Index * ElSize) % vecWidth == 0;
4271
4272   return Result;
4273 }
4274
4275 bool X86::isVINSERT128Index(SDNode *N) {
4276   return isVINSERTIndex(N, 128);
4277 }
4278
4279 bool X86::isVINSERT256Index(SDNode *N) {
4280   return isVINSERTIndex(N, 256);
4281 }
4282
4283 bool X86::isVEXTRACT128Index(SDNode *N) {
4284   return isVEXTRACTIndex(N, 128);
4285 }
4286
4287 bool X86::isVEXTRACT256Index(SDNode *N) {
4288   return isVEXTRACTIndex(N, 256);
4289 }
4290
4291 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4292 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4293 /// Handles 128-bit and 256-bit.
4294 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4295   MVT VT = N->getValueType(0).getSimpleVT();
4296
4297   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4298          "Unsupported vector type for PSHUF/SHUFP");
4299
4300   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4301   // independently on 128-bit lanes.
4302   unsigned NumElts = VT.getVectorNumElements();
4303   unsigned NumLanes = VT.getSizeInBits()/128;
4304   unsigned NumLaneElts = NumElts/NumLanes;
4305
4306   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4307          "Only supports 2 or 4 elements per lane");
4308
4309   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4310   unsigned Mask = 0;
4311   for (unsigned i = 0; i != NumElts; ++i) {
4312     int Elt = N->getMaskElt(i);
4313     if (Elt < 0) continue;
4314     Elt &= NumLaneElts - 1;
4315     unsigned ShAmt = (i << Shift) % 8;
4316     Mask |= Elt << ShAmt;
4317   }
4318
4319   return Mask;
4320 }
4321
4322 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4323 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4324 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4325   MVT VT = N->getValueType(0).getSimpleVT();
4326
4327   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4328          "Unsupported vector type for PSHUFHW");
4329
4330   unsigned NumElts = VT.getVectorNumElements();
4331
4332   unsigned Mask = 0;
4333   for (unsigned l = 0; l != NumElts; l += 8) {
4334     // 8 nodes per lane, but we only care about the last 4.
4335     for (unsigned i = 0; i < 4; ++i) {
4336       int Elt = N->getMaskElt(l+i+4);
4337       if (Elt < 0) continue;
4338       Elt &= 0x3; // only 2-bits.
4339       Mask |= Elt << (i * 2);
4340     }
4341   }
4342
4343   return Mask;
4344 }
4345
4346 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4347 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4348 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4349   MVT VT = N->getValueType(0).getSimpleVT();
4350
4351   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4352          "Unsupported vector type for PSHUFHW");
4353
4354   unsigned NumElts = VT.getVectorNumElements();
4355
4356   unsigned Mask = 0;
4357   for (unsigned l = 0; l != NumElts; l += 8) {
4358     // 8 nodes per lane, but we only care about the first 4.
4359     for (unsigned i = 0; i < 4; ++i) {
4360       int Elt = N->getMaskElt(l+i);
4361       if (Elt < 0) continue;
4362       Elt &= 0x3; // only 2-bits
4363       Mask |= Elt << (i * 2);
4364     }
4365   }
4366
4367   return Mask;
4368 }
4369
4370 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4371 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4372 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4373   MVT VT = SVOp->getValueType(0).getSimpleVT();
4374   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4375
4376   unsigned NumElts = VT.getVectorNumElements();
4377   unsigned NumLanes = VT.getSizeInBits()/128;
4378   unsigned NumLaneElts = NumElts/NumLanes;
4379
4380   int Val = 0;
4381   unsigned i;
4382   for (i = 0; i != NumElts; ++i) {
4383     Val = SVOp->getMaskElt(i);
4384     if (Val >= 0)
4385       break;
4386   }
4387   if (Val >= (int)NumElts)
4388     Val -= NumElts - NumLaneElts;
4389
4390   assert(Val - i > 0 && "PALIGNR imm should be positive");
4391   return (Val - i) * EltSize;
4392 }
4393
4394 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4395   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4396   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4397     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4398
4399   uint64_t Index =
4400     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4401
4402   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4403   MVT ElVT = VecVT.getVectorElementType();
4404
4405   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4406   return Index / NumElemsPerChunk;
4407 }
4408
4409 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4410   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4411   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4412     llvm_unreachable("Illegal insert subvector for VINSERT");
4413
4414   uint64_t Index =
4415     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4416
4417   MVT VecVT = N->getValueType(0).getSimpleVT();
4418   MVT ElVT = VecVT.getVectorElementType();
4419
4420   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4421   return Index / NumElemsPerChunk;
4422 }
4423
4424 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4425 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4426 /// and VINSERTI128 instructions.
4427 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4428   return getExtractVEXTRACTImmediate(N, 128);
4429 }
4430
4431 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4432 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4433 /// and VINSERTI64x4 instructions.
4434 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4435   return getExtractVEXTRACTImmediate(N, 256);
4436 }
4437
4438 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4439 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4440 /// and VINSERTI128 instructions.
4441 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4442   return getInsertVINSERTImmediate(N, 128);
4443 }
4444
4445 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4446 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4447 /// and VINSERTI64x4 instructions.
4448 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4449   return getInsertVINSERTImmediate(N, 256);
4450 }
4451
4452 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4453 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4454 /// Handles 256-bit.
4455 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4456   MVT VT = N->getValueType(0).getSimpleVT();
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459
4460   assert((VT.is256BitVector() && NumElts == 4) &&
4461          "Unsupported vector type for VPERMQ/VPERMPD");
4462
4463   unsigned Mask = 0;
4464   for (unsigned i = 0; i != NumElts; ++i) {
4465     int Elt = N->getMaskElt(i);
4466     if (Elt < 0)
4467       continue;
4468     Mask |= Elt << (i*2);
4469   }
4470
4471   return Mask;
4472 }
4473 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4474 /// constant +0.0.
4475 bool X86::isZeroNode(SDValue Elt) {
4476   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4477     return CN->isNullValue();
4478   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4479     return CFP->getValueAPF().isPosZero();
4480   return false;
4481 }
4482
4483 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4484 /// their permute mask.
4485 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4486                                     SelectionDAG &DAG) {
4487   MVT VT = SVOp->getValueType(0).getSimpleVT();
4488   unsigned NumElems = VT.getVectorNumElements();
4489   SmallVector<int, 8> MaskVec;
4490
4491   for (unsigned i = 0; i != NumElems; ++i) {
4492     int Idx = SVOp->getMaskElt(i);
4493     if (Idx >= 0) {
4494       if (Idx < (int)NumElems)
4495         Idx += NumElems;
4496       else
4497         Idx -= NumElems;
4498     }
4499     MaskVec.push_back(Idx);
4500   }
4501   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4502                               SVOp->getOperand(0), &MaskVec[0]);
4503 }
4504
4505 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4506 /// match movhlps. The lower half elements should come from upper half of
4507 /// V1 (and in order), and the upper half elements should come from the upper
4508 /// half of V2 (and in order).
4509 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4510   if (!VT.is128BitVector())
4511     return false;
4512   if (VT.getVectorNumElements() != 4)
4513     return false;
4514   for (unsigned i = 0, e = 2; i != e; ++i)
4515     if (!isUndefOrEqual(Mask[i], i+2))
4516       return false;
4517   for (unsigned i = 2; i != 4; ++i)
4518     if (!isUndefOrEqual(Mask[i], i+4))
4519       return false;
4520   return true;
4521 }
4522
4523 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4524 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4525 /// required.
4526 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4527   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4528     return false;
4529   N = N->getOperand(0).getNode();
4530   if (!ISD::isNON_EXTLoad(N))
4531     return false;
4532   if (LD)
4533     *LD = cast<LoadSDNode>(N);
4534   return true;
4535 }
4536
4537 // Test whether the given value is a vector value which will be legalized
4538 // into a load.
4539 static bool WillBeConstantPoolLoad(SDNode *N) {
4540   if (N->getOpcode() != ISD::BUILD_VECTOR)
4541     return false;
4542
4543   // Check for any non-constant elements.
4544   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4545     switch (N->getOperand(i).getNode()->getOpcode()) {
4546     case ISD::UNDEF:
4547     case ISD::ConstantFP:
4548     case ISD::Constant:
4549       break;
4550     default:
4551       return false;
4552     }
4553
4554   // Vectors of all-zeros and all-ones are materialized with special
4555   // instructions rather than being loaded.
4556   return !ISD::isBuildVectorAllZeros(N) &&
4557          !ISD::isBuildVectorAllOnes(N);
4558 }
4559
4560 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4561 /// match movlp{s|d}. The lower half elements should come from lower half of
4562 /// V1 (and in order), and the upper half elements should come from the upper
4563 /// half of V2 (and in order). And since V1 will become the source of the
4564 /// MOVLP, it must be either a vector load or a scalar load to vector.
4565 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4566                                ArrayRef<int> Mask, EVT VT) {
4567   if (!VT.is128BitVector())
4568     return false;
4569
4570   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4571     return false;
4572   // Is V2 is a vector load, don't do this transformation. We will try to use
4573   // load folding shufps op.
4574   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4575     return false;
4576
4577   unsigned NumElems = VT.getVectorNumElements();
4578
4579   if (NumElems != 2 && NumElems != 4)
4580     return false;
4581   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4582     if (!isUndefOrEqual(Mask[i], i))
4583       return false;
4584   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4585     if (!isUndefOrEqual(Mask[i], i+NumElems))
4586       return false;
4587   return true;
4588 }
4589
4590 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4591 /// all the same.
4592 static bool isSplatVector(SDNode *N) {
4593   if (N->getOpcode() != ISD::BUILD_VECTOR)
4594     return false;
4595
4596   SDValue SplatValue = N->getOperand(0);
4597   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4598     if (N->getOperand(i) != SplatValue)
4599       return false;
4600   return true;
4601 }
4602
4603 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4604 /// to an zero vector.
4605 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4606 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4607   SDValue V1 = N->getOperand(0);
4608   SDValue V2 = N->getOperand(1);
4609   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4610   for (unsigned i = 0; i != NumElems; ++i) {
4611     int Idx = N->getMaskElt(i);
4612     if (Idx >= (int)NumElems) {
4613       unsigned Opc = V2.getOpcode();
4614       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4615         continue;
4616       if (Opc != ISD::BUILD_VECTOR ||
4617           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4618         return false;
4619     } else if (Idx >= 0) {
4620       unsigned Opc = V1.getOpcode();
4621       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4622         continue;
4623       if (Opc != ISD::BUILD_VECTOR ||
4624           !X86::isZeroNode(V1.getOperand(Idx)))
4625         return false;
4626     }
4627   }
4628   return true;
4629 }
4630
4631 /// getZeroVector - Returns a vector of specified type with all zero elements.
4632 ///
4633 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4634                              SelectionDAG &DAG, SDLoc dl) {
4635   assert(VT.isVector() && "Expected a vector type");
4636
4637   // Always build SSE zero vectors as <4 x i32> bitcasted
4638   // to their dest type. This ensures they get CSE'd.
4639   SDValue Vec;
4640   if (VT.is128BitVector()) {  // SSE
4641     if (Subtarget->hasSSE2()) {  // SSE2
4642       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4643       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4644     } else { // SSE1
4645       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4646       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4647     }
4648   } else if (VT.is256BitVector()) { // AVX
4649     if (Subtarget->hasInt256()) { // AVX2
4650       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4651       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4652       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4653                         array_lengthof(Ops));
4654     } else {
4655       // 256-bit logic and arithmetic instructions in AVX are all
4656       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4657       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4658       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4659       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4660                         array_lengthof(Ops));
4661     }
4662   } else
4663     llvm_unreachable("Unexpected vector type");
4664
4665   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4666 }
4667
4668 /// getOnesVector - Returns a vector of specified type with all bits set.
4669 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4670 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4671 /// Then bitcast to their original type, ensuring they get CSE'd.
4672 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4673                              SDLoc dl) {
4674   assert(VT.isVector() && "Expected a vector type");
4675
4676   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4677   SDValue Vec;
4678   if (VT.is256BitVector()) {
4679     if (HasInt256) { // AVX2
4680       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4681       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4682                         array_lengthof(Ops));
4683     } else { // AVX
4684       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4685       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4686     }
4687   } else if (VT.is128BitVector()) {
4688     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4689   } else
4690     llvm_unreachable("Unexpected vector type");
4691
4692   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4693 }
4694
4695 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4696 /// that point to V2 points to its first element.
4697 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4698   for (unsigned i = 0; i != NumElems; ++i) {
4699     if (Mask[i] > (int)NumElems) {
4700       Mask[i] = NumElems;
4701     }
4702   }
4703 }
4704
4705 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4706 /// operation of specified width.
4707 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4708                        SDValue V2) {
4709   unsigned NumElems = VT.getVectorNumElements();
4710   SmallVector<int, 8> Mask;
4711   Mask.push_back(NumElems);
4712   for (unsigned i = 1; i != NumElems; ++i)
4713     Mask.push_back(i);
4714   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4715 }
4716
4717 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4718 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4719                           SDValue V2) {
4720   unsigned NumElems = VT.getVectorNumElements();
4721   SmallVector<int, 8> Mask;
4722   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4723     Mask.push_back(i);
4724     Mask.push_back(i + NumElems);
4725   }
4726   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4727 }
4728
4729 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4730 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4731                           SDValue V2) {
4732   unsigned NumElems = VT.getVectorNumElements();
4733   SmallVector<int, 8> Mask;
4734   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4735     Mask.push_back(i + Half);
4736     Mask.push_back(i + NumElems + Half);
4737   }
4738   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4739 }
4740
4741 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4742 // a generic shuffle instruction because the target has no such instructions.
4743 // Generate shuffles which repeat i16 and i8 several times until they can be
4744 // represented by v4f32 and then be manipulated by target suported shuffles.
4745 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4746   EVT VT = V.getValueType();
4747   int NumElems = VT.getVectorNumElements();
4748   SDLoc dl(V);
4749
4750   while (NumElems > 4) {
4751     if (EltNo < NumElems/2) {
4752       V = getUnpackl(DAG, dl, VT, V, V);
4753     } else {
4754       V = getUnpackh(DAG, dl, VT, V, V);
4755       EltNo -= NumElems/2;
4756     }
4757     NumElems >>= 1;
4758   }
4759   return V;
4760 }
4761
4762 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4763 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4764   EVT VT = V.getValueType();
4765   SDLoc dl(V);
4766
4767   if (VT.is128BitVector()) {
4768     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4769     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4770     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4771                              &SplatMask[0]);
4772   } else if (VT.is256BitVector()) {
4773     // To use VPERMILPS to splat scalars, the second half of indicies must
4774     // refer to the higher part, which is a duplication of the lower one,
4775     // because VPERMILPS can only handle in-lane permutations.
4776     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4777                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4778
4779     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4780     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4781                              &SplatMask[0]);
4782   } else
4783     llvm_unreachable("Vector size not supported");
4784
4785   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4786 }
4787
4788 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4789 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4790   EVT SrcVT = SV->getValueType(0);
4791   SDValue V1 = SV->getOperand(0);
4792   SDLoc dl(SV);
4793
4794   int EltNo = SV->getSplatIndex();
4795   int NumElems = SrcVT.getVectorNumElements();
4796   bool Is256BitVec = SrcVT.is256BitVector();
4797
4798   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4799          "Unknown how to promote splat for type");
4800
4801   // Extract the 128-bit part containing the splat element and update
4802   // the splat element index when it refers to the higher register.
4803   if (Is256BitVec) {
4804     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4805     if (EltNo >= NumElems/2)
4806       EltNo -= NumElems/2;
4807   }
4808
4809   // All i16 and i8 vector types can't be used directly by a generic shuffle
4810   // instruction because the target has no such instruction. Generate shuffles
4811   // which repeat i16 and i8 several times until they fit in i32, and then can
4812   // be manipulated by target suported shuffles.
4813   EVT EltVT = SrcVT.getVectorElementType();
4814   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4815     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4816
4817   // Recreate the 256-bit vector and place the same 128-bit vector
4818   // into the low and high part. This is necessary because we want
4819   // to use VPERM* to shuffle the vectors
4820   if (Is256BitVec) {
4821     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4822   }
4823
4824   return getLegalSplat(DAG, V1, EltNo);
4825 }
4826
4827 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4828 /// vector of zero or undef vector.  This produces a shuffle where the low
4829 /// element of V2 is swizzled into the zero/undef vector, landing at element
4830 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4831 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4832                                            bool IsZero,
4833                                            const X86Subtarget *Subtarget,
4834                                            SelectionDAG &DAG) {
4835   EVT VT = V2.getValueType();
4836   SDValue V1 = IsZero
4837     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4838   unsigned NumElems = VT.getVectorNumElements();
4839   SmallVector<int, 16> MaskVec;
4840   for (unsigned i = 0; i != NumElems; ++i)
4841     // If this is the insertion idx, put the low elt of V2 here.
4842     MaskVec.push_back(i == Idx ? NumElems : i);
4843   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4844 }
4845
4846 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4847 /// target specific opcode. Returns true if the Mask could be calculated.
4848 /// Sets IsUnary to true if only uses one source.
4849 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4850                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4851   unsigned NumElems = VT.getVectorNumElements();
4852   SDValue ImmN;
4853
4854   IsUnary = false;
4855   switch(N->getOpcode()) {
4856   case X86ISD::SHUFP:
4857     ImmN = N->getOperand(N->getNumOperands()-1);
4858     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4859     break;
4860   case X86ISD::UNPCKH:
4861     DecodeUNPCKHMask(VT, Mask);
4862     break;
4863   case X86ISD::UNPCKL:
4864     DecodeUNPCKLMask(VT, Mask);
4865     break;
4866   case X86ISD::MOVHLPS:
4867     DecodeMOVHLPSMask(NumElems, Mask);
4868     break;
4869   case X86ISD::MOVLHPS:
4870     DecodeMOVLHPSMask(NumElems, Mask);
4871     break;
4872   case X86ISD::PALIGNR:
4873     ImmN = N->getOperand(N->getNumOperands()-1);
4874     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4875     break;
4876   case X86ISD::PSHUFD:
4877   case X86ISD::VPERMILP:
4878     ImmN = N->getOperand(N->getNumOperands()-1);
4879     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4880     IsUnary = true;
4881     break;
4882   case X86ISD::PSHUFHW:
4883     ImmN = N->getOperand(N->getNumOperands()-1);
4884     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4885     IsUnary = true;
4886     break;
4887   case X86ISD::PSHUFLW:
4888     ImmN = N->getOperand(N->getNumOperands()-1);
4889     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4890     IsUnary = true;
4891     break;
4892   case X86ISD::VPERMI:
4893     ImmN = N->getOperand(N->getNumOperands()-1);
4894     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4895     IsUnary = true;
4896     break;
4897   case X86ISD::MOVSS:
4898   case X86ISD::MOVSD: {
4899     // The index 0 always comes from the first element of the second source,
4900     // this is why MOVSS and MOVSD are used in the first place. The other
4901     // elements come from the other positions of the first source vector
4902     Mask.push_back(NumElems);
4903     for (unsigned i = 1; i != NumElems; ++i) {
4904       Mask.push_back(i);
4905     }
4906     break;
4907   }
4908   case X86ISD::VPERM2X128:
4909     ImmN = N->getOperand(N->getNumOperands()-1);
4910     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4911     if (Mask.empty()) return false;
4912     break;
4913   case X86ISD::MOVDDUP:
4914   case X86ISD::MOVLHPD:
4915   case X86ISD::MOVLPD:
4916   case X86ISD::MOVLPS:
4917   case X86ISD::MOVSHDUP:
4918   case X86ISD::MOVSLDUP:
4919     // Not yet implemented
4920     return false;
4921   default: llvm_unreachable("unknown target shuffle node");
4922   }
4923
4924   return true;
4925 }
4926
4927 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4928 /// element of the result of the vector shuffle.
4929 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4930                                    unsigned Depth) {
4931   if (Depth == 6)
4932     return SDValue();  // Limit search depth.
4933
4934   SDValue V = SDValue(N, 0);
4935   EVT VT = V.getValueType();
4936   unsigned Opcode = V.getOpcode();
4937
4938   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4939   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4940     int Elt = SV->getMaskElt(Index);
4941
4942     if (Elt < 0)
4943       return DAG.getUNDEF(VT.getVectorElementType());
4944
4945     unsigned NumElems = VT.getVectorNumElements();
4946     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4947                                          : SV->getOperand(1);
4948     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4949   }
4950
4951   // Recurse into target specific vector shuffles to find scalars.
4952   if (isTargetShuffle(Opcode)) {
4953     MVT ShufVT = V.getValueType().getSimpleVT();
4954     unsigned NumElems = ShufVT.getVectorNumElements();
4955     SmallVector<int, 16> ShuffleMask;
4956     bool IsUnary;
4957
4958     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4959       return SDValue();
4960
4961     int Elt = ShuffleMask[Index];
4962     if (Elt < 0)
4963       return DAG.getUNDEF(ShufVT.getVectorElementType());
4964
4965     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4966                                          : N->getOperand(1);
4967     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4968                                Depth+1);
4969   }
4970
4971   // Actual nodes that may contain scalar elements
4972   if (Opcode == ISD::BITCAST) {
4973     V = V.getOperand(0);
4974     EVT SrcVT = V.getValueType();
4975     unsigned NumElems = VT.getVectorNumElements();
4976
4977     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4978       return SDValue();
4979   }
4980
4981   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4982     return (Index == 0) ? V.getOperand(0)
4983                         : DAG.getUNDEF(VT.getVectorElementType());
4984
4985   if (V.getOpcode() == ISD::BUILD_VECTOR)
4986     return V.getOperand(Index);
4987
4988   return SDValue();
4989 }
4990
4991 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4992 /// shuffle operation which come from a consecutively from a zero. The
4993 /// search can start in two different directions, from left or right.
4994 /// We count undefs as zeros until PreferredNum is reached.
4995 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4996                                          unsigned NumElems, bool ZerosFromLeft,
4997                                          SelectionDAG &DAG,
4998                                          unsigned PreferredNum = -1U) {
4999   unsigned NumZeros = 0;
5000   for (unsigned i = 0; i != NumElems; ++i) {
5001     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5002     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5003     if (!Elt.getNode())
5004       break;
5005
5006     if (X86::isZeroNode(Elt))
5007       ++NumZeros;
5008     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5009       NumZeros = std::min(NumZeros + 1, PreferredNum);
5010     else
5011       break;
5012   }
5013
5014   return NumZeros;
5015 }
5016
5017 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5018 /// correspond consecutively to elements from one of the vector operands,
5019 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5020 static
5021 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5022                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5023                               unsigned NumElems, unsigned &OpNum) {
5024   bool SeenV1 = false;
5025   bool SeenV2 = false;
5026
5027   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5028     int Idx = SVOp->getMaskElt(i);
5029     // Ignore undef indicies
5030     if (Idx < 0)
5031       continue;
5032
5033     if (Idx < (int)NumElems)
5034       SeenV1 = true;
5035     else
5036       SeenV2 = true;
5037
5038     // Only accept consecutive elements from the same vector
5039     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5040       return false;
5041   }
5042
5043   OpNum = SeenV1 ? 0 : 1;
5044   return true;
5045 }
5046
5047 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5048 /// logical left shift of a vector.
5049 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5050                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5051   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5052   unsigned NumZeros = getNumOfConsecutiveZeros(
5053       SVOp, NumElems, false /* check zeros from right */, DAG,
5054       SVOp->getMaskElt(0));
5055   unsigned OpSrc;
5056
5057   if (!NumZeros)
5058     return false;
5059
5060   // Considering the elements in the mask that are not consecutive zeros,
5061   // check if they consecutively come from only one of the source vectors.
5062   //
5063   //               V1 = {X, A, B, C}     0
5064   //                         \  \  \    /
5065   //   vector_shuffle V1, V2 <1, 2, 3, X>
5066   //
5067   if (!isShuffleMaskConsecutive(SVOp,
5068             0,                   // Mask Start Index
5069             NumElems-NumZeros,   // Mask End Index(exclusive)
5070             NumZeros,            // Where to start looking in the src vector
5071             NumElems,            // Number of elements in vector
5072             OpSrc))              // Which source operand ?
5073     return false;
5074
5075   isLeft = false;
5076   ShAmt = NumZeros;
5077   ShVal = SVOp->getOperand(OpSrc);
5078   return true;
5079 }
5080
5081 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5082 /// logical left shift of a vector.
5083 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5084                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5085   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5086   unsigned NumZeros = getNumOfConsecutiveZeros(
5087       SVOp, NumElems, true /* check zeros from left */, DAG,
5088       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5089   unsigned OpSrc;
5090
5091   if (!NumZeros)
5092     return false;
5093
5094   // Considering the elements in the mask that are not consecutive zeros,
5095   // check if they consecutively come from only one of the source vectors.
5096   //
5097   //                           0    { A, B, X, X } = V2
5098   //                          / \    /  /
5099   //   vector_shuffle V1, V2 <X, X, 4, 5>
5100   //
5101   if (!isShuffleMaskConsecutive(SVOp,
5102             NumZeros,     // Mask Start Index
5103             NumElems,     // Mask End Index(exclusive)
5104             0,            // Where to start looking in the src vector
5105             NumElems,     // Number of elements in vector
5106             OpSrc))       // Which source operand ?
5107     return false;
5108
5109   isLeft = true;
5110   ShAmt = NumZeros;
5111   ShVal = SVOp->getOperand(OpSrc);
5112   return true;
5113 }
5114
5115 /// isVectorShift - Returns true if the shuffle can be implemented as a
5116 /// logical left or right shift of a vector.
5117 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5118                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5119   // Although the logic below support any bitwidth size, there are no
5120   // shift instructions which handle more than 128-bit vectors.
5121   if (!SVOp->getValueType(0).is128BitVector())
5122     return false;
5123
5124   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5125       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5126     return true;
5127
5128   return false;
5129 }
5130
5131 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5132 ///
5133 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5134                                        unsigned NumNonZero, unsigned NumZero,
5135                                        SelectionDAG &DAG,
5136                                        const X86Subtarget* Subtarget,
5137                                        const TargetLowering &TLI) {
5138   if (NumNonZero > 8)
5139     return SDValue();
5140
5141   SDLoc dl(Op);
5142   SDValue V(0, 0);
5143   bool First = true;
5144   for (unsigned i = 0; i < 16; ++i) {
5145     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5146     if (ThisIsNonZero && First) {
5147       if (NumZero)
5148         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5149       else
5150         V = DAG.getUNDEF(MVT::v8i16);
5151       First = false;
5152     }
5153
5154     if ((i & 1) != 0) {
5155       SDValue ThisElt(0, 0), LastElt(0, 0);
5156       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5157       if (LastIsNonZero) {
5158         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5159                               MVT::i16, Op.getOperand(i-1));
5160       }
5161       if (ThisIsNonZero) {
5162         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5163         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5164                               ThisElt, DAG.getConstant(8, MVT::i8));
5165         if (LastIsNonZero)
5166           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5167       } else
5168         ThisElt = LastElt;
5169
5170       if (ThisElt.getNode())
5171         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5172                         DAG.getIntPtrConstant(i/2));
5173     }
5174   }
5175
5176   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5177 }
5178
5179 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5180 ///
5181 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5182                                      unsigned NumNonZero, unsigned NumZero,
5183                                      SelectionDAG &DAG,
5184                                      const X86Subtarget* Subtarget,
5185                                      const TargetLowering &TLI) {
5186   if (NumNonZero > 4)
5187     return SDValue();
5188
5189   SDLoc dl(Op);
5190   SDValue V(0, 0);
5191   bool First = true;
5192   for (unsigned i = 0; i < 8; ++i) {
5193     bool isNonZero = (NonZeros & (1 << i)) != 0;
5194     if (isNonZero) {
5195       if (First) {
5196         if (NumZero)
5197           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5198         else
5199           V = DAG.getUNDEF(MVT::v8i16);
5200         First = false;
5201       }
5202       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5203                       MVT::v8i16, V, Op.getOperand(i),
5204                       DAG.getIntPtrConstant(i));
5205     }
5206   }
5207
5208   return V;
5209 }
5210
5211 /// getVShift - Return a vector logical shift node.
5212 ///
5213 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5214                          unsigned NumBits, SelectionDAG &DAG,
5215                          const TargetLowering &TLI, SDLoc dl) {
5216   assert(VT.is128BitVector() && "Unknown type for VShift");
5217   EVT ShVT = MVT::v2i64;
5218   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5219   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5220   return DAG.getNode(ISD::BITCAST, dl, VT,
5221                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5222                              DAG.getConstant(NumBits,
5223                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5224 }
5225
5226 SDValue
5227 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5228                                           SelectionDAG &DAG) const {
5229
5230   // Check if the scalar load can be widened into a vector load. And if
5231   // the address is "base + cst" see if the cst can be "absorbed" into
5232   // the shuffle mask.
5233   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5234     SDValue Ptr = LD->getBasePtr();
5235     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5236       return SDValue();
5237     EVT PVT = LD->getValueType(0);
5238     if (PVT != MVT::i32 && PVT != MVT::f32)
5239       return SDValue();
5240
5241     int FI = -1;
5242     int64_t Offset = 0;
5243     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5244       FI = FINode->getIndex();
5245       Offset = 0;
5246     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5247                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5248       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5249       Offset = Ptr.getConstantOperandVal(1);
5250       Ptr = Ptr.getOperand(0);
5251     } else {
5252       return SDValue();
5253     }
5254
5255     // FIXME: 256-bit vector instructions don't require a strict alignment,
5256     // improve this code to support it better.
5257     unsigned RequiredAlign = VT.getSizeInBits()/8;
5258     SDValue Chain = LD->getChain();
5259     // Make sure the stack object alignment is at least 16 or 32.
5260     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5261     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5262       if (MFI->isFixedObjectIndex(FI)) {
5263         // Can't change the alignment. FIXME: It's possible to compute
5264         // the exact stack offset and reference FI + adjust offset instead.
5265         // If someone *really* cares about this. That's the way to implement it.
5266         return SDValue();
5267       } else {
5268         MFI->setObjectAlignment(FI, RequiredAlign);
5269       }
5270     }
5271
5272     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5273     // Ptr + (Offset & ~15).
5274     if (Offset < 0)
5275       return SDValue();
5276     if ((Offset % RequiredAlign) & 3)
5277       return SDValue();
5278     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5279     if (StartOffset)
5280       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5281                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5282
5283     int EltNo = (Offset - StartOffset) >> 2;
5284     unsigned NumElems = VT.getVectorNumElements();
5285
5286     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5287     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5288                              LD->getPointerInfo().getWithOffset(StartOffset),
5289                              false, false, false, 0);
5290
5291     SmallVector<int, 8> Mask;
5292     for (unsigned i = 0; i != NumElems; ++i)
5293       Mask.push_back(EltNo);
5294
5295     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5296   }
5297
5298   return SDValue();
5299 }
5300
5301 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5302 /// vector of type 'VT', see if the elements can be replaced by a single large
5303 /// load which has the same value as a build_vector whose operands are 'elts'.
5304 ///
5305 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5306 ///
5307 /// FIXME: we'd also like to handle the case where the last elements are zero
5308 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5309 /// There's even a handy isZeroNode for that purpose.
5310 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5311                                         SDLoc &DL, SelectionDAG &DAG) {
5312   EVT EltVT = VT.getVectorElementType();
5313   unsigned NumElems = Elts.size();
5314
5315   LoadSDNode *LDBase = NULL;
5316   unsigned LastLoadedElt = -1U;
5317
5318   // For each element in the initializer, see if we've found a load or an undef.
5319   // If we don't find an initial load element, or later load elements are
5320   // non-consecutive, bail out.
5321   for (unsigned i = 0; i < NumElems; ++i) {
5322     SDValue Elt = Elts[i];
5323
5324     if (!Elt.getNode() ||
5325         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5326       return SDValue();
5327     if (!LDBase) {
5328       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5329         return SDValue();
5330       LDBase = cast<LoadSDNode>(Elt.getNode());
5331       LastLoadedElt = i;
5332       continue;
5333     }
5334     if (Elt.getOpcode() == ISD::UNDEF)
5335       continue;
5336
5337     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5338     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5339       return SDValue();
5340     LastLoadedElt = i;
5341   }
5342
5343   // If we have found an entire vector of loads and undefs, then return a large
5344   // load of the entire vector width starting at the base pointer.  If we found
5345   // consecutive loads for the low half, generate a vzext_load node.
5346   if (LastLoadedElt == NumElems - 1) {
5347     SDValue NewLd = SDValue();
5348     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5349       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5350                           LDBase->getPointerInfo(),
5351                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5352                           LDBase->isInvariant(), 0);
5353     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5354                         LDBase->getPointerInfo(),
5355                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5356                         LDBase->isInvariant(), LDBase->getAlignment());
5357
5358     if (LDBase->hasAnyUseOfValue(1)) {
5359       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5360                                      SDValue(LDBase, 1),
5361                                      SDValue(NewLd.getNode(), 1));
5362       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5363       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5364                              SDValue(NewLd.getNode(), 1));
5365     }
5366
5367     return NewLd;
5368   }
5369   if (NumElems == 4 && LastLoadedElt == 1 &&
5370       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5371     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5372     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5373     SDValue ResNode =
5374         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5375                                 array_lengthof(Ops), MVT::i64,
5376                                 LDBase->getPointerInfo(),
5377                                 LDBase->getAlignment(),
5378                                 false/*isVolatile*/, true/*ReadMem*/,
5379                                 false/*WriteMem*/);
5380
5381     // Make sure the newly-created LOAD is in the same position as LDBase in
5382     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5383     // update uses of LDBase's output chain to use the TokenFactor.
5384     if (LDBase->hasAnyUseOfValue(1)) {
5385       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5386                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5387       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5388       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5389                              SDValue(ResNode.getNode(), 1));
5390     }
5391
5392     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5393   }
5394   return SDValue();
5395 }
5396
5397 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5398 /// to generate a splat value for the following cases:
5399 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5400 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5401 /// a scalar load, or a constant.
5402 /// The VBROADCAST node is returned when a pattern is found,
5403 /// or SDValue() otherwise.
5404 SDValue
5405 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5406   if (!Subtarget->hasFp256())
5407     return SDValue();
5408
5409   MVT VT = Op.getValueType().getSimpleVT();
5410   SDLoc dl(Op);
5411
5412   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5413          "Unsupported vector type for broadcast.");
5414
5415   SDValue Ld;
5416   bool ConstSplatVal;
5417
5418   switch (Op.getOpcode()) {
5419     default:
5420       // Unknown pattern found.
5421       return SDValue();
5422
5423     case ISD::BUILD_VECTOR: {
5424       // The BUILD_VECTOR node must be a splat.
5425       if (!isSplatVector(Op.getNode()))
5426         return SDValue();
5427
5428       Ld = Op.getOperand(0);
5429       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5430                      Ld.getOpcode() == ISD::ConstantFP);
5431
5432       // The suspected load node has several users. Make sure that all
5433       // of its users are from the BUILD_VECTOR node.
5434       // Constants may have multiple users.
5435       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5436         return SDValue();
5437       break;
5438     }
5439
5440     case ISD::VECTOR_SHUFFLE: {
5441       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5442
5443       // Shuffles must have a splat mask where the first element is
5444       // broadcasted.
5445       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5446         return SDValue();
5447
5448       SDValue Sc = Op.getOperand(0);
5449       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5450           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5451
5452         if (!Subtarget->hasInt256())
5453           return SDValue();
5454
5455         // Use the register form of the broadcast instruction available on AVX2.
5456         if (VT.is256BitVector())
5457           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5458         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5459       }
5460
5461       Ld = Sc.getOperand(0);
5462       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5463                        Ld.getOpcode() == ISD::ConstantFP);
5464
5465       // The scalar_to_vector node and the suspected
5466       // load node must have exactly one user.
5467       // Constants may have multiple users.
5468       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5469         return SDValue();
5470       break;
5471     }
5472   }
5473
5474   bool Is256 = VT.is256BitVector();
5475
5476   // Handle the broadcasting a single constant scalar from the constant pool
5477   // into a vector. On Sandybridge it is still better to load a constant vector
5478   // from the constant pool and not to broadcast it from a scalar.
5479   if (ConstSplatVal && Subtarget->hasInt256()) {
5480     EVT CVT = Ld.getValueType();
5481     assert(!CVT.isVector() && "Must not broadcast a vector type");
5482     unsigned ScalarSize = CVT.getSizeInBits();
5483
5484     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5485       const Constant *C = 0;
5486       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5487         C = CI->getConstantIntValue();
5488       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5489         C = CF->getConstantFPValue();
5490
5491       assert(C && "Invalid constant type");
5492
5493       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5494       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5495       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5496                        MachinePointerInfo::getConstantPool(),
5497                        false, false, false, Alignment);
5498
5499       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5500     }
5501   }
5502
5503   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5504   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5505
5506   // Handle AVX2 in-register broadcasts.
5507   if (!IsLoad && Subtarget->hasInt256() &&
5508       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5509     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5510
5511   // The scalar source must be a normal load.
5512   if (!IsLoad)
5513     return SDValue();
5514
5515   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5516     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5517
5518   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5519   // double since there is no vbroadcastsd xmm
5520   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5521     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5522       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523   }
5524
5525   // Unsupported broadcast.
5526   return SDValue();
5527 }
5528
5529 SDValue
5530 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5531   EVT VT = Op.getValueType();
5532
5533   // Skip if insert_vec_elt is not supported.
5534   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5535     return SDValue();
5536
5537   SDLoc DL(Op);
5538   unsigned NumElems = Op.getNumOperands();
5539
5540   SDValue VecIn1;
5541   SDValue VecIn2;
5542   SmallVector<unsigned, 4> InsertIndices;
5543   SmallVector<int, 8> Mask(NumElems, -1);
5544
5545   for (unsigned i = 0; i != NumElems; ++i) {
5546     unsigned Opc = Op.getOperand(i).getOpcode();
5547
5548     if (Opc == ISD::UNDEF)
5549       continue;
5550
5551     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5552       // Quit if more than 1 elements need inserting.
5553       if (InsertIndices.size() > 1)
5554         return SDValue();
5555
5556       InsertIndices.push_back(i);
5557       continue;
5558     }
5559
5560     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5561     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5562
5563     // Quit if extracted from vector of different type.
5564     if (ExtractedFromVec.getValueType() != VT)
5565       return SDValue();
5566
5567     // Quit if non-constant index.
5568     if (!isa<ConstantSDNode>(ExtIdx))
5569       return SDValue();
5570
5571     if (VecIn1.getNode() == 0)
5572       VecIn1 = ExtractedFromVec;
5573     else if (VecIn1 != ExtractedFromVec) {
5574       if (VecIn2.getNode() == 0)
5575         VecIn2 = ExtractedFromVec;
5576       else if (VecIn2 != ExtractedFromVec)
5577         // Quit if more than 2 vectors to shuffle
5578         return SDValue();
5579     }
5580
5581     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5582
5583     if (ExtractedFromVec == VecIn1)
5584       Mask[i] = Idx;
5585     else if (ExtractedFromVec == VecIn2)
5586       Mask[i] = Idx + NumElems;
5587   }
5588
5589   if (VecIn1.getNode() == 0)
5590     return SDValue();
5591
5592   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5593   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5594   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5595     unsigned Idx = InsertIndices[i];
5596     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5597                      DAG.getIntPtrConstant(Idx));
5598   }
5599
5600   return NV;
5601 }
5602
5603 SDValue
5604 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5605   SDLoc dl(Op);
5606
5607   MVT VT = Op.getValueType().getSimpleVT();
5608   MVT ExtVT = VT.getVectorElementType();
5609   unsigned NumElems = Op.getNumOperands();
5610
5611   // Vectors containing all zeros can be matched by pxor and xorps later
5612   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5613     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5614     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5615     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5616       return Op;
5617
5618     return getZeroVector(VT, Subtarget, DAG, dl);
5619   }
5620
5621   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5622   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5623   // vpcmpeqd on 256-bit vectors.
5624   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5625     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5626       return Op;
5627
5628     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5629   }
5630
5631   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5632   if (Broadcast.getNode())
5633     return Broadcast;
5634
5635   unsigned EVTBits = ExtVT.getSizeInBits();
5636
5637   unsigned NumZero  = 0;
5638   unsigned NumNonZero = 0;
5639   unsigned NonZeros = 0;
5640   bool IsAllConstants = true;
5641   SmallSet<SDValue, 8> Values;
5642   for (unsigned i = 0; i < NumElems; ++i) {
5643     SDValue Elt = Op.getOperand(i);
5644     if (Elt.getOpcode() == ISD::UNDEF)
5645       continue;
5646     Values.insert(Elt);
5647     if (Elt.getOpcode() != ISD::Constant &&
5648         Elt.getOpcode() != ISD::ConstantFP)
5649       IsAllConstants = false;
5650     if (X86::isZeroNode(Elt))
5651       NumZero++;
5652     else {
5653       NonZeros |= (1 << i);
5654       NumNonZero++;
5655     }
5656   }
5657
5658   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5659   if (NumNonZero == 0)
5660     return DAG.getUNDEF(VT);
5661
5662   // Special case for single non-zero, non-undef, element.
5663   if (NumNonZero == 1) {
5664     unsigned Idx = countTrailingZeros(NonZeros);
5665     SDValue Item = Op.getOperand(Idx);
5666
5667     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5668     // the value are obviously zero, truncate the value to i32 and do the
5669     // insertion that way.  Only do this if the value is non-constant or if the
5670     // value is a constant being inserted into element 0.  It is cheaper to do
5671     // a constant pool load than it is to do a movd + shuffle.
5672     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5673         (!IsAllConstants || Idx == 0)) {
5674       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5675         // Handle SSE only.
5676         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5677         EVT VecVT = MVT::v4i32;
5678         unsigned VecElts = 4;
5679
5680         // Truncate the value (which may itself be a constant) to i32, and
5681         // convert it to a vector with movd (S2V+shuffle to zero extend).
5682         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5683         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5684         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5685
5686         // Now we have our 32-bit value zero extended in the low element of
5687         // a vector.  If Idx != 0, swizzle it into place.
5688         if (Idx != 0) {
5689           SmallVector<int, 4> Mask;
5690           Mask.push_back(Idx);
5691           for (unsigned i = 1; i != VecElts; ++i)
5692             Mask.push_back(i);
5693           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5694                                       &Mask[0]);
5695         }
5696         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5697       }
5698     }
5699
5700     // If we have a constant or non-constant insertion into the low element of
5701     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5702     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5703     // depending on what the source datatype is.
5704     if (Idx == 0) {
5705       if (NumZero == 0)
5706         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5707
5708       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5709           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5710         if (VT.is256BitVector()) {
5711           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5712           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5713                              Item, DAG.getIntPtrConstant(0));
5714         }
5715         assert(VT.is128BitVector() && "Expected an SSE value type!");
5716         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5717         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5718         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5719       }
5720
5721       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5722         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5723         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5724         if (VT.is256BitVector()) {
5725           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5726           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5727         } else {
5728           assert(VT.is128BitVector() && "Expected an SSE value type!");
5729           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5730         }
5731         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5732       }
5733     }
5734
5735     // Is it a vector logical left shift?
5736     if (NumElems == 2 && Idx == 1 &&
5737         X86::isZeroNode(Op.getOperand(0)) &&
5738         !X86::isZeroNode(Op.getOperand(1))) {
5739       unsigned NumBits = VT.getSizeInBits();
5740       return getVShift(true, VT,
5741                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5742                                    VT, Op.getOperand(1)),
5743                        NumBits/2, DAG, *this, dl);
5744     }
5745
5746     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5747       return SDValue();
5748
5749     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5750     // is a non-constant being inserted into an element other than the low one,
5751     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5752     // movd/movss) to move this into the low element, then shuffle it into
5753     // place.
5754     if (EVTBits == 32) {
5755       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5756
5757       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5758       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5759       SmallVector<int, 8> MaskVec;
5760       for (unsigned i = 0; i != NumElems; ++i)
5761         MaskVec.push_back(i == Idx ? 0 : 1);
5762       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5763     }
5764   }
5765
5766   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5767   if (Values.size() == 1) {
5768     if (EVTBits == 32) {
5769       // Instead of a shuffle like this:
5770       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5771       // Check if it's possible to issue this instead.
5772       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5773       unsigned Idx = countTrailingZeros(NonZeros);
5774       SDValue Item = Op.getOperand(Idx);
5775       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5776         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5777     }
5778     return SDValue();
5779   }
5780
5781   // A vector full of immediates; various special cases are already
5782   // handled, so this is best done with a single constant-pool load.
5783   if (IsAllConstants)
5784     return SDValue();
5785
5786   // For AVX-length vectors, build the individual 128-bit pieces and use
5787   // shuffles to put them in place.
5788   if (VT.is256BitVector()) {
5789     SmallVector<SDValue, 32> V;
5790     for (unsigned i = 0; i != NumElems; ++i)
5791       V.push_back(Op.getOperand(i));
5792
5793     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5794
5795     // Build both the lower and upper subvector.
5796     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5797     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5798                                 NumElems/2);
5799
5800     // Recreate the wider vector with the lower and upper part.
5801     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5802   }
5803
5804   // Let legalizer expand 2-wide build_vectors.
5805   if (EVTBits == 64) {
5806     if (NumNonZero == 1) {
5807       // One half is zero or undef.
5808       unsigned Idx = countTrailingZeros(NonZeros);
5809       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5810                                  Op.getOperand(Idx));
5811       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5812     }
5813     return SDValue();
5814   }
5815
5816   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5817   if (EVTBits == 8 && NumElems == 16) {
5818     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5819                                         Subtarget, *this);
5820     if (V.getNode()) return V;
5821   }
5822
5823   if (EVTBits == 16 && NumElems == 8) {
5824     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5825                                       Subtarget, *this);
5826     if (V.getNode()) return V;
5827   }
5828
5829   // If element VT is == 32 bits, turn it into a number of shuffles.
5830   SmallVector<SDValue, 8> V(NumElems);
5831   if (NumElems == 4 && NumZero > 0) {
5832     for (unsigned i = 0; i < 4; ++i) {
5833       bool isZero = !(NonZeros & (1 << i));
5834       if (isZero)
5835         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5836       else
5837         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5838     }
5839
5840     for (unsigned i = 0; i < 2; ++i) {
5841       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5842         default: break;
5843         case 0:
5844           V[i] = V[i*2];  // Must be a zero vector.
5845           break;
5846         case 1:
5847           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5848           break;
5849         case 2:
5850           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5851           break;
5852         case 3:
5853           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5854           break;
5855       }
5856     }
5857
5858     bool Reverse1 = (NonZeros & 0x3) == 2;
5859     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5860     int MaskVec[] = {
5861       Reverse1 ? 1 : 0,
5862       Reverse1 ? 0 : 1,
5863       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5864       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5865     };
5866     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5867   }
5868
5869   if (Values.size() > 1 && VT.is128BitVector()) {
5870     // Check for a build vector of consecutive loads.
5871     for (unsigned i = 0; i < NumElems; ++i)
5872       V[i] = Op.getOperand(i);
5873
5874     // Check for elements which are consecutive loads.
5875     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5876     if (LD.getNode())
5877       return LD;
5878
5879     // Check for a build vector from mostly shuffle plus few inserting.
5880     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5881     if (Sh.getNode())
5882       return Sh;
5883
5884     // For SSE 4.1, use insertps to put the high elements into the low element.
5885     if (getSubtarget()->hasSSE41()) {
5886       SDValue Result;
5887       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5888         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5889       else
5890         Result = DAG.getUNDEF(VT);
5891
5892       for (unsigned i = 1; i < NumElems; ++i) {
5893         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5894         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5895                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5896       }
5897       return Result;
5898     }
5899
5900     // Otherwise, expand into a number of unpckl*, start by extending each of
5901     // our (non-undef) elements to the full vector width with the element in the
5902     // bottom slot of the vector (which generates no code for SSE).
5903     for (unsigned i = 0; i < NumElems; ++i) {
5904       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5905         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5906       else
5907         V[i] = DAG.getUNDEF(VT);
5908     }
5909
5910     // Next, we iteratively mix elements, e.g. for v4f32:
5911     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5912     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5913     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5914     unsigned EltStride = NumElems >> 1;
5915     while (EltStride != 0) {
5916       for (unsigned i = 0; i < EltStride; ++i) {
5917         // If V[i+EltStride] is undef and this is the first round of mixing,
5918         // then it is safe to just drop this shuffle: V[i] is already in the
5919         // right place, the one element (since it's the first round) being
5920         // inserted as undef can be dropped.  This isn't safe for successive
5921         // rounds because they will permute elements within both vectors.
5922         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5923             EltStride == NumElems/2)
5924           continue;
5925
5926         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5927       }
5928       EltStride >>= 1;
5929     }
5930     return V[0];
5931   }
5932   return SDValue();
5933 }
5934
5935 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5936 // to create 256-bit vectors from two other 128-bit ones.
5937 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5938   SDLoc dl(Op);
5939   MVT ResVT = Op.getValueType().getSimpleVT();
5940
5941   assert((ResVT.is256BitVector() ||
5942           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5943
5944   SDValue V1 = Op.getOperand(0);
5945   SDValue V2 = Op.getOperand(1);
5946   unsigned NumElems = ResVT.getVectorNumElements();
5947   if(ResVT.is256BitVector())
5948     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5949
5950   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5951 }
5952
5953 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5954   assert(Op.getNumOperands() == 2);
5955
5956   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
5957   // from two other 128-bit ones.
5958   return LowerAVXCONCAT_VECTORS(Op, DAG);
5959 }
5960
5961 // Try to lower a shuffle node into a simple blend instruction.
5962 static SDValue
5963 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5964                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5965   SDValue V1 = SVOp->getOperand(0);
5966   SDValue V2 = SVOp->getOperand(1);
5967   SDLoc dl(SVOp);
5968   MVT VT = SVOp->getValueType(0).getSimpleVT();
5969   MVT EltVT = VT.getVectorElementType();
5970   unsigned NumElems = VT.getVectorNumElements();
5971
5972   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5973     return SDValue();
5974   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5975     return SDValue();
5976
5977   // Check the mask for BLEND and build the value.
5978   unsigned MaskValue = 0;
5979   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5980   unsigned NumLanes = (NumElems-1)/8 + 1;
5981   unsigned NumElemsInLane = NumElems / NumLanes;
5982
5983   // Blend for v16i16 should be symetric for the both lanes.
5984   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5985
5986     int SndLaneEltIdx = (NumLanes == 2) ?
5987       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5988     int EltIdx = SVOp->getMaskElt(i);
5989
5990     if ((EltIdx < 0 || EltIdx == (int)i) &&
5991         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5992       continue;
5993
5994     if (((unsigned)EltIdx == (i + NumElems)) &&
5995         (SndLaneEltIdx < 0 ||
5996          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5997       MaskValue |= (1<<i);
5998     else
5999       return SDValue();
6000   }
6001
6002   // Convert i32 vectors to floating point if it is not AVX2.
6003   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6004   MVT BlendVT = VT;
6005   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6006     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6007                                NumElems);
6008     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6009     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6010   }
6011
6012   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6013                             DAG.getConstant(MaskValue, MVT::i32));
6014   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6015 }
6016
6017 // v8i16 shuffles - Prefer shuffles in the following order:
6018 // 1. [all]   pshuflw, pshufhw, optional move
6019 // 2. [ssse3] 1 x pshufb
6020 // 3. [ssse3] 2 x pshufb + 1 x por
6021 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6022 static SDValue
6023 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6024                          SelectionDAG &DAG) {
6025   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6026   SDValue V1 = SVOp->getOperand(0);
6027   SDValue V2 = SVOp->getOperand(1);
6028   SDLoc dl(SVOp);
6029   SmallVector<int, 8> MaskVals;
6030
6031   // Determine if more than 1 of the words in each of the low and high quadwords
6032   // of the result come from the same quadword of one of the two inputs.  Undef
6033   // mask values count as coming from any quadword, for better codegen.
6034   unsigned LoQuad[] = { 0, 0, 0, 0 };
6035   unsigned HiQuad[] = { 0, 0, 0, 0 };
6036   std::bitset<4> InputQuads;
6037   for (unsigned i = 0; i < 8; ++i) {
6038     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6039     int EltIdx = SVOp->getMaskElt(i);
6040     MaskVals.push_back(EltIdx);
6041     if (EltIdx < 0) {
6042       ++Quad[0];
6043       ++Quad[1];
6044       ++Quad[2];
6045       ++Quad[3];
6046       continue;
6047     }
6048     ++Quad[EltIdx / 4];
6049     InputQuads.set(EltIdx / 4);
6050   }
6051
6052   int BestLoQuad = -1;
6053   unsigned MaxQuad = 1;
6054   for (unsigned i = 0; i < 4; ++i) {
6055     if (LoQuad[i] > MaxQuad) {
6056       BestLoQuad = i;
6057       MaxQuad = LoQuad[i];
6058     }
6059   }
6060
6061   int BestHiQuad = -1;
6062   MaxQuad = 1;
6063   for (unsigned i = 0; i < 4; ++i) {
6064     if (HiQuad[i] > MaxQuad) {
6065       BestHiQuad = i;
6066       MaxQuad = HiQuad[i];
6067     }
6068   }
6069
6070   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6071   // of the two input vectors, shuffle them into one input vector so only a
6072   // single pshufb instruction is necessary. If There are more than 2 input
6073   // quads, disable the next transformation since it does not help SSSE3.
6074   bool V1Used = InputQuads[0] || InputQuads[1];
6075   bool V2Used = InputQuads[2] || InputQuads[3];
6076   if (Subtarget->hasSSSE3()) {
6077     if (InputQuads.count() == 2 && V1Used && V2Used) {
6078       BestLoQuad = InputQuads[0] ? 0 : 1;
6079       BestHiQuad = InputQuads[2] ? 2 : 3;
6080     }
6081     if (InputQuads.count() > 2) {
6082       BestLoQuad = -1;
6083       BestHiQuad = -1;
6084     }
6085   }
6086
6087   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6088   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6089   // words from all 4 input quadwords.
6090   SDValue NewV;
6091   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6092     int MaskV[] = {
6093       BestLoQuad < 0 ? 0 : BestLoQuad,
6094       BestHiQuad < 0 ? 1 : BestHiQuad
6095     };
6096     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6097                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6098                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6099     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6100
6101     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6102     // source words for the shuffle, to aid later transformations.
6103     bool AllWordsInNewV = true;
6104     bool InOrder[2] = { true, true };
6105     for (unsigned i = 0; i != 8; ++i) {
6106       int idx = MaskVals[i];
6107       if (idx != (int)i)
6108         InOrder[i/4] = false;
6109       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6110         continue;
6111       AllWordsInNewV = false;
6112       break;
6113     }
6114
6115     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6116     if (AllWordsInNewV) {
6117       for (int i = 0; i != 8; ++i) {
6118         int idx = MaskVals[i];
6119         if (idx < 0)
6120           continue;
6121         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6122         if ((idx != i) && idx < 4)
6123           pshufhw = false;
6124         if ((idx != i) && idx > 3)
6125           pshuflw = false;
6126       }
6127       V1 = NewV;
6128       V2Used = false;
6129       BestLoQuad = 0;
6130       BestHiQuad = 1;
6131     }
6132
6133     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6134     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6135     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6136       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6137       unsigned TargetMask = 0;
6138       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6139                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6140       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6141       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6142                              getShufflePSHUFLWImmediate(SVOp);
6143       V1 = NewV.getOperand(0);
6144       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6145     }
6146   }
6147
6148   // Promote splats to a larger type which usually leads to more efficient code.
6149   // FIXME: Is this true if pshufb is available?
6150   if (SVOp->isSplat())
6151     return PromoteSplat(SVOp, DAG);
6152
6153   // If we have SSSE3, and all words of the result are from 1 input vector,
6154   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6155   // is present, fall back to case 4.
6156   if (Subtarget->hasSSSE3()) {
6157     SmallVector<SDValue,16> pshufbMask;
6158
6159     // If we have elements from both input vectors, set the high bit of the
6160     // shuffle mask element to zero out elements that come from V2 in the V1
6161     // mask, and elements that come from V1 in the V2 mask, so that the two
6162     // results can be OR'd together.
6163     bool TwoInputs = V1Used && V2Used;
6164     for (unsigned i = 0; i != 8; ++i) {
6165       int EltIdx = MaskVals[i] * 2;
6166       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6167       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6168       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6169       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6170     }
6171     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6172     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6173                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6174                                  MVT::v16i8, &pshufbMask[0], 16));
6175     if (!TwoInputs)
6176       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6177
6178     // Calculate the shuffle mask for the second input, shuffle it, and
6179     // OR it with the first shuffled input.
6180     pshufbMask.clear();
6181     for (unsigned i = 0; i != 8; ++i) {
6182       int EltIdx = MaskVals[i] * 2;
6183       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6184       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6185       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6186       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6187     }
6188     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6189     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6190                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6191                                  MVT::v16i8, &pshufbMask[0], 16));
6192     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6193     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6194   }
6195
6196   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6197   // and update MaskVals with new element order.
6198   std::bitset<8> InOrder;
6199   if (BestLoQuad >= 0) {
6200     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6201     for (int i = 0; i != 4; ++i) {
6202       int idx = MaskVals[i];
6203       if (idx < 0) {
6204         InOrder.set(i);
6205       } else if ((idx / 4) == BestLoQuad) {
6206         MaskV[i] = idx & 3;
6207         InOrder.set(i);
6208       }
6209     }
6210     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6211                                 &MaskV[0]);
6212
6213     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6214       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6215       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6216                                   NewV.getOperand(0),
6217                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6218     }
6219   }
6220
6221   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6222   // and update MaskVals with the new element order.
6223   if (BestHiQuad >= 0) {
6224     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6225     for (unsigned i = 4; i != 8; ++i) {
6226       int idx = MaskVals[i];
6227       if (idx < 0) {
6228         InOrder.set(i);
6229       } else if ((idx / 4) == BestHiQuad) {
6230         MaskV[i] = (idx & 3) + 4;
6231         InOrder.set(i);
6232       }
6233     }
6234     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6235                                 &MaskV[0]);
6236
6237     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6238       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6239       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6240                                   NewV.getOperand(0),
6241                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6242     }
6243   }
6244
6245   // In case BestHi & BestLo were both -1, which means each quadword has a word
6246   // from each of the four input quadwords, calculate the InOrder bitvector now
6247   // before falling through to the insert/extract cleanup.
6248   if (BestLoQuad == -1 && BestHiQuad == -1) {
6249     NewV = V1;
6250     for (int i = 0; i != 8; ++i)
6251       if (MaskVals[i] < 0 || MaskVals[i] == i)
6252         InOrder.set(i);
6253   }
6254
6255   // The other elements are put in the right place using pextrw and pinsrw.
6256   for (unsigned i = 0; i != 8; ++i) {
6257     if (InOrder[i])
6258       continue;
6259     int EltIdx = MaskVals[i];
6260     if (EltIdx < 0)
6261       continue;
6262     SDValue ExtOp = (EltIdx < 8) ?
6263       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6264                   DAG.getIntPtrConstant(EltIdx)) :
6265       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6266                   DAG.getIntPtrConstant(EltIdx - 8));
6267     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6268                        DAG.getIntPtrConstant(i));
6269   }
6270   return NewV;
6271 }
6272
6273 // v16i8 shuffles - Prefer shuffles in the following order:
6274 // 1. [ssse3] 1 x pshufb
6275 // 2. [ssse3] 2 x pshufb + 1 x por
6276 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6277 static
6278 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6279                                  SelectionDAG &DAG,
6280                                  const X86TargetLowering &TLI) {
6281   SDValue V1 = SVOp->getOperand(0);
6282   SDValue V2 = SVOp->getOperand(1);
6283   SDLoc dl(SVOp);
6284   ArrayRef<int> MaskVals = SVOp->getMask();
6285
6286   // Promote splats to a larger type which usually leads to more efficient code.
6287   // FIXME: Is this true if pshufb is available?
6288   if (SVOp->isSplat())
6289     return PromoteSplat(SVOp, DAG);
6290
6291   // If we have SSSE3, case 1 is generated when all result bytes come from
6292   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6293   // present, fall back to case 3.
6294
6295   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6296   if (TLI.getSubtarget()->hasSSSE3()) {
6297     SmallVector<SDValue,16> pshufbMask;
6298
6299     // If all result elements are from one input vector, then only translate
6300     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6301     //
6302     // Otherwise, we have elements from both input vectors, and must zero out
6303     // elements that come from V2 in the first mask, and V1 in the second mask
6304     // so that we can OR them together.
6305     for (unsigned i = 0; i != 16; ++i) {
6306       int EltIdx = MaskVals[i];
6307       if (EltIdx < 0 || EltIdx >= 16)
6308         EltIdx = 0x80;
6309       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6310     }
6311     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6312                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6313                                  MVT::v16i8, &pshufbMask[0], 16));
6314
6315     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6316     // the 2nd operand if it's undefined or zero.
6317     if (V2.getOpcode() == ISD::UNDEF ||
6318         ISD::isBuildVectorAllZeros(V2.getNode()))
6319       return V1;
6320
6321     // Calculate the shuffle mask for the second input, shuffle it, and
6322     // OR it with the first shuffled input.
6323     pshufbMask.clear();
6324     for (unsigned i = 0; i != 16; ++i) {
6325       int EltIdx = MaskVals[i];
6326       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6327       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6328     }
6329     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6330                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6331                                  MVT::v16i8, &pshufbMask[0], 16));
6332     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6333   }
6334
6335   // No SSSE3 - Calculate in place words and then fix all out of place words
6336   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6337   // the 16 different words that comprise the two doublequadword input vectors.
6338   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6339   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6340   SDValue NewV = V1;
6341   for (int i = 0; i != 8; ++i) {
6342     int Elt0 = MaskVals[i*2];
6343     int Elt1 = MaskVals[i*2+1];
6344
6345     // This word of the result is all undef, skip it.
6346     if (Elt0 < 0 && Elt1 < 0)
6347       continue;
6348
6349     // This word of the result is already in the correct place, skip it.
6350     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6351       continue;
6352
6353     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6354     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6355     SDValue InsElt;
6356
6357     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6358     // using a single extract together, load it and store it.
6359     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6360       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6361                            DAG.getIntPtrConstant(Elt1 / 2));
6362       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6363                         DAG.getIntPtrConstant(i));
6364       continue;
6365     }
6366
6367     // If Elt1 is defined, extract it from the appropriate source.  If the
6368     // source byte is not also odd, shift the extracted word left 8 bits
6369     // otherwise clear the bottom 8 bits if we need to do an or.
6370     if (Elt1 >= 0) {
6371       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6372                            DAG.getIntPtrConstant(Elt1 / 2));
6373       if ((Elt1 & 1) == 0)
6374         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6375                              DAG.getConstant(8,
6376                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6377       else if (Elt0 >= 0)
6378         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6379                              DAG.getConstant(0xFF00, MVT::i16));
6380     }
6381     // If Elt0 is defined, extract it from the appropriate source.  If the
6382     // source byte is not also even, shift the extracted word right 8 bits. If
6383     // Elt1 was also defined, OR the extracted values together before
6384     // inserting them in the result.
6385     if (Elt0 >= 0) {
6386       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6387                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6388       if ((Elt0 & 1) != 0)
6389         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6390                               DAG.getConstant(8,
6391                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6392       else if (Elt1 >= 0)
6393         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6394                              DAG.getConstant(0x00FF, MVT::i16));
6395       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6396                          : InsElt0;
6397     }
6398     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6399                        DAG.getIntPtrConstant(i));
6400   }
6401   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6402 }
6403
6404 // v32i8 shuffles - Translate to VPSHUFB if possible.
6405 static
6406 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6407                                  const X86Subtarget *Subtarget,
6408                                  SelectionDAG &DAG) {
6409   MVT VT = SVOp->getValueType(0).getSimpleVT();
6410   SDValue V1 = SVOp->getOperand(0);
6411   SDValue V2 = SVOp->getOperand(1);
6412   SDLoc dl(SVOp);
6413   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6414
6415   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6416   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6417   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6418
6419   // VPSHUFB may be generated if
6420   // (1) one of input vector is undefined or zeroinitializer.
6421   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6422   // And (2) the mask indexes don't cross the 128-bit lane.
6423   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6424       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6425     return SDValue();
6426
6427   if (V1IsAllZero && !V2IsAllZero) {
6428     CommuteVectorShuffleMask(MaskVals, 32);
6429     V1 = V2;
6430   }
6431   SmallVector<SDValue, 32> pshufbMask;
6432   for (unsigned i = 0; i != 32; i++) {
6433     int EltIdx = MaskVals[i];
6434     if (EltIdx < 0 || EltIdx >= 32)
6435       EltIdx = 0x80;
6436     else {
6437       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6438         // Cross lane is not allowed.
6439         return SDValue();
6440       EltIdx &= 0xf;
6441     }
6442     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6443   }
6444   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6445                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6446                                   MVT::v32i8, &pshufbMask[0], 32));
6447 }
6448
6449 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6450 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6451 /// done when every pair / quad of shuffle mask elements point to elements in
6452 /// the right sequence. e.g.
6453 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6454 static
6455 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6456                                  SelectionDAG &DAG) {
6457   MVT VT = SVOp->getValueType(0).getSimpleVT();
6458   SDLoc dl(SVOp);
6459   unsigned NumElems = VT.getVectorNumElements();
6460   MVT NewVT;
6461   unsigned Scale;
6462   switch (VT.SimpleTy) {
6463   default: llvm_unreachable("Unexpected!");
6464   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6465   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6466   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6467   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6468   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6469   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6470   }
6471
6472   SmallVector<int, 8> MaskVec;
6473   for (unsigned i = 0; i != NumElems; i += Scale) {
6474     int StartIdx = -1;
6475     for (unsigned j = 0; j != Scale; ++j) {
6476       int EltIdx = SVOp->getMaskElt(i+j);
6477       if (EltIdx < 0)
6478         continue;
6479       if (StartIdx < 0)
6480         StartIdx = (EltIdx / Scale);
6481       if (EltIdx != (int)(StartIdx*Scale + j))
6482         return SDValue();
6483     }
6484     MaskVec.push_back(StartIdx);
6485   }
6486
6487   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6488   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6489   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6490 }
6491
6492 /// getVZextMovL - Return a zero-extending vector move low node.
6493 ///
6494 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6495                             SDValue SrcOp, SelectionDAG &DAG,
6496                             const X86Subtarget *Subtarget, SDLoc dl) {
6497   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6498     LoadSDNode *LD = NULL;
6499     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6500       LD = dyn_cast<LoadSDNode>(SrcOp);
6501     if (!LD) {
6502       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6503       // instead.
6504       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6505       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6506           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6507           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6508           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6509         // PR2108
6510         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6511         return DAG.getNode(ISD::BITCAST, dl, VT,
6512                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6513                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6514                                                    OpVT,
6515                                                    SrcOp.getOperand(0)
6516                                                           .getOperand(0))));
6517       }
6518     }
6519   }
6520
6521   return DAG.getNode(ISD::BITCAST, dl, VT,
6522                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6523                                  DAG.getNode(ISD::BITCAST, dl,
6524                                              OpVT, SrcOp)));
6525 }
6526
6527 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6528 /// which could not be matched by any known target speficic shuffle
6529 static SDValue
6530 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6531
6532   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6533   if (NewOp.getNode())
6534     return NewOp;
6535
6536   MVT VT = SVOp->getValueType(0).getSimpleVT();
6537
6538   unsigned NumElems = VT.getVectorNumElements();
6539   unsigned NumLaneElems = NumElems / 2;
6540
6541   SDLoc dl(SVOp);
6542   MVT EltVT = VT.getVectorElementType();
6543   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6544   SDValue Output[2];
6545
6546   SmallVector<int, 16> Mask;
6547   for (unsigned l = 0; l < 2; ++l) {
6548     // Build a shuffle mask for the output, discovering on the fly which
6549     // input vectors to use as shuffle operands (recorded in InputUsed).
6550     // If building a suitable shuffle vector proves too hard, then bail
6551     // out with UseBuildVector set.
6552     bool UseBuildVector = false;
6553     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6554     unsigned LaneStart = l * NumLaneElems;
6555     for (unsigned i = 0; i != NumLaneElems; ++i) {
6556       // The mask element.  This indexes into the input.
6557       int Idx = SVOp->getMaskElt(i+LaneStart);
6558       if (Idx < 0) {
6559         // the mask element does not index into any input vector.
6560         Mask.push_back(-1);
6561         continue;
6562       }
6563
6564       // The input vector this mask element indexes into.
6565       int Input = Idx / NumLaneElems;
6566
6567       // Turn the index into an offset from the start of the input vector.
6568       Idx -= Input * NumLaneElems;
6569
6570       // Find or create a shuffle vector operand to hold this input.
6571       unsigned OpNo;
6572       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6573         if (InputUsed[OpNo] == Input)
6574           // This input vector is already an operand.
6575           break;
6576         if (InputUsed[OpNo] < 0) {
6577           // Create a new operand for this input vector.
6578           InputUsed[OpNo] = Input;
6579           break;
6580         }
6581       }
6582
6583       if (OpNo >= array_lengthof(InputUsed)) {
6584         // More than two input vectors used!  Give up on trying to create a
6585         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6586         UseBuildVector = true;
6587         break;
6588       }
6589
6590       // Add the mask index for the new shuffle vector.
6591       Mask.push_back(Idx + OpNo * NumLaneElems);
6592     }
6593
6594     if (UseBuildVector) {
6595       SmallVector<SDValue, 16> SVOps;
6596       for (unsigned i = 0; i != NumLaneElems; ++i) {
6597         // The mask element.  This indexes into the input.
6598         int Idx = SVOp->getMaskElt(i+LaneStart);
6599         if (Idx < 0) {
6600           SVOps.push_back(DAG.getUNDEF(EltVT));
6601           continue;
6602         }
6603
6604         // The input vector this mask element indexes into.
6605         int Input = Idx / NumElems;
6606
6607         // Turn the index into an offset from the start of the input vector.
6608         Idx -= Input * NumElems;
6609
6610         // Extract the vector element by hand.
6611         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6612                                     SVOp->getOperand(Input),
6613                                     DAG.getIntPtrConstant(Idx)));
6614       }
6615
6616       // Construct the output using a BUILD_VECTOR.
6617       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6618                               SVOps.size());
6619     } else if (InputUsed[0] < 0) {
6620       // No input vectors were used! The result is undefined.
6621       Output[l] = DAG.getUNDEF(NVT);
6622     } else {
6623       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6624                                         (InputUsed[0] % 2) * NumLaneElems,
6625                                         DAG, dl);
6626       // If only one input was used, use an undefined vector for the other.
6627       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6628         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6629                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6630       // At least one input vector was used. Create a new shuffle vector.
6631       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6632     }
6633
6634     Mask.clear();
6635   }
6636
6637   // Concatenate the result back
6638   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6639 }
6640
6641 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6642 /// 4 elements, and match them with several different shuffle types.
6643 static SDValue
6644 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6645   SDValue V1 = SVOp->getOperand(0);
6646   SDValue V2 = SVOp->getOperand(1);
6647   SDLoc dl(SVOp);
6648   MVT VT = SVOp->getValueType(0).getSimpleVT();
6649
6650   assert(VT.is128BitVector() && "Unsupported vector size");
6651
6652   std::pair<int, int> Locs[4];
6653   int Mask1[] = { -1, -1, -1, -1 };
6654   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6655
6656   unsigned NumHi = 0;
6657   unsigned NumLo = 0;
6658   for (unsigned i = 0; i != 4; ++i) {
6659     int Idx = PermMask[i];
6660     if (Idx < 0) {
6661       Locs[i] = std::make_pair(-1, -1);
6662     } else {
6663       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6664       if (Idx < 4) {
6665         Locs[i] = std::make_pair(0, NumLo);
6666         Mask1[NumLo] = Idx;
6667         NumLo++;
6668       } else {
6669         Locs[i] = std::make_pair(1, NumHi);
6670         if (2+NumHi < 4)
6671           Mask1[2+NumHi] = Idx;
6672         NumHi++;
6673       }
6674     }
6675   }
6676
6677   if (NumLo <= 2 && NumHi <= 2) {
6678     // If no more than two elements come from either vector. This can be
6679     // implemented with two shuffles. First shuffle gather the elements.
6680     // The second shuffle, which takes the first shuffle as both of its
6681     // vector operands, put the elements into the right order.
6682     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6683
6684     int Mask2[] = { -1, -1, -1, -1 };
6685
6686     for (unsigned i = 0; i != 4; ++i)
6687       if (Locs[i].first != -1) {
6688         unsigned Idx = (i < 2) ? 0 : 4;
6689         Idx += Locs[i].first * 2 + Locs[i].second;
6690         Mask2[i] = Idx;
6691       }
6692
6693     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6694   }
6695
6696   if (NumLo == 3 || NumHi == 3) {
6697     // Otherwise, we must have three elements from one vector, call it X, and
6698     // one element from the other, call it Y.  First, use a shufps to build an
6699     // intermediate vector with the one element from Y and the element from X
6700     // that will be in the same half in the final destination (the indexes don't
6701     // matter). Then, use a shufps to build the final vector, taking the half
6702     // containing the element from Y from the intermediate, and the other half
6703     // from X.
6704     if (NumHi == 3) {
6705       // Normalize it so the 3 elements come from V1.
6706       CommuteVectorShuffleMask(PermMask, 4);
6707       std::swap(V1, V2);
6708     }
6709
6710     // Find the element from V2.
6711     unsigned HiIndex;
6712     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6713       int Val = PermMask[HiIndex];
6714       if (Val < 0)
6715         continue;
6716       if (Val >= 4)
6717         break;
6718     }
6719
6720     Mask1[0] = PermMask[HiIndex];
6721     Mask1[1] = -1;
6722     Mask1[2] = PermMask[HiIndex^1];
6723     Mask1[3] = -1;
6724     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6725
6726     if (HiIndex >= 2) {
6727       Mask1[0] = PermMask[0];
6728       Mask1[1] = PermMask[1];
6729       Mask1[2] = HiIndex & 1 ? 6 : 4;
6730       Mask1[3] = HiIndex & 1 ? 4 : 6;
6731       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6732     }
6733
6734     Mask1[0] = HiIndex & 1 ? 2 : 0;
6735     Mask1[1] = HiIndex & 1 ? 0 : 2;
6736     Mask1[2] = PermMask[2];
6737     Mask1[3] = PermMask[3];
6738     if (Mask1[2] >= 0)
6739       Mask1[2] += 4;
6740     if (Mask1[3] >= 0)
6741       Mask1[3] += 4;
6742     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6743   }
6744
6745   // Break it into (shuffle shuffle_hi, shuffle_lo).
6746   int LoMask[] = { -1, -1, -1, -1 };
6747   int HiMask[] = { -1, -1, -1, -1 };
6748
6749   int *MaskPtr = LoMask;
6750   unsigned MaskIdx = 0;
6751   unsigned LoIdx = 0;
6752   unsigned HiIdx = 2;
6753   for (unsigned i = 0; i != 4; ++i) {
6754     if (i == 2) {
6755       MaskPtr = HiMask;
6756       MaskIdx = 1;
6757       LoIdx = 0;
6758       HiIdx = 2;
6759     }
6760     int Idx = PermMask[i];
6761     if (Idx < 0) {
6762       Locs[i] = std::make_pair(-1, -1);
6763     } else if (Idx < 4) {
6764       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6765       MaskPtr[LoIdx] = Idx;
6766       LoIdx++;
6767     } else {
6768       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6769       MaskPtr[HiIdx] = Idx;
6770       HiIdx++;
6771     }
6772   }
6773
6774   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6775   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6776   int MaskOps[] = { -1, -1, -1, -1 };
6777   for (unsigned i = 0; i != 4; ++i)
6778     if (Locs[i].first != -1)
6779       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6780   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6781 }
6782
6783 static bool MayFoldVectorLoad(SDValue V) {
6784   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6785     V = V.getOperand(0);
6786
6787   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6788     V = V.getOperand(0);
6789   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6790       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6791     // BUILD_VECTOR (load), undef
6792     V = V.getOperand(0);
6793
6794   return MayFoldLoad(V);
6795 }
6796
6797 static
6798 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6799   EVT VT = Op.getValueType();
6800
6801   // Canonizalize to v2f64.
6802   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6803   return DAG.getNode(ISD::BITCAST, dl, VT,
6804                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6805                                           V1, DAG));
6806 }
6807
6808 static
6809 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6810                         bool HasSSE2) {
6811   SDValue V1 = Op.getOperand(0);
6812   SDValue V2 = Op.getOperand(1);
6813   EVT VT = Op.getValueType();
6814
6815   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6816
6817   if (HasSSE2 && VT == MVT::v2f64)
6818     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6819
6820   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6821   return DAG.getNode(ISD::BITCAST, dl, VT,
6822                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6823                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6824                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6825 }
6826
6827 static
6828 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6829   SDValue V1 = Op.getOperand(0);
6830   SDValue V2 = Op.getOperand(1);
6831   EVT VT = Op.getValueType();
6832
6833   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6834          "unsupported shuffle type");
6835
6836   if (V2.getOpcode() == ISD::UNDEF)
6837     V2 = V1;
6838
6839   // v4i32 or v4f32
6840   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6841 }
6842
6843 static
6844 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6845   SDValue V1 = Op.getOperand(0);
6846   SDValue V2 = Op.getOperand(1);
6847   EVT VT = Op.getValueType();
6848   unsigned NumElems = VT.getVectorNumElements();
6849
6850   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6851   // operand of these instructions is only memory, so check if there's a
6852   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6853   // same masks.
6854   bool CanFoldLoad = false;
6855
6856   // Trivial case, when V2 comes from a load.
6857   if (MayFoldVectorLoad(V2))
6858     CanFoldLoad = true;
6859
6860   // When V1 is a load, it can be folded later into a store in isel, example:
6861   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6862   //    turns into:
6863   //  (MOVLPSmr addr:$src1, VR128:$src2)
6864   // So, recognize this potential and also use MOVLPS or MOVLPD
6865   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6866     CanFoldLoad = true;
6867
6868   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6869   if (CanFoldLoad) {
6870     if (HasSSE2 && NumElems == 2)
6871       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6872
6873     if (NumElems == 4)
6874       // If we don't care about the second element, proceed to use movss.
6875       if (SVOp->getMaskElt(1) != -1)
6876         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6877   }
6878
6879   // movl and movlp will both match v2i64, but v2i64 is never matched by
6880   // movl earlier because we make it strict to avoid messing with the movlp load
6881   // folding logic (see the code above getMOVLP call). Match it here then,
6882   // this is horrible, but will stay like this until we move all shuffle
6883   // matching to x86 specific nodes. Note that for the 1st condition all
6884   // types are matched with movsd.
6885   if (HasSSE2) {
6886     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6887     // as to remove this logic from here, as much as possible
6888     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6889       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6890     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6891   }
6892
6893   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6894
6895   // Invert the operand order and use SHUFPS to match it.
6896   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6897                               getShuffleSHUFImmediate(SVOp), DAG);
6898 }
6899
6900 // Reduce a vector shuffle to zext.
6901 SDValue
6902 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6903   // PMOVZX is only available from SSE41.
6904   if (!Subtarget->hasSSE41())
6905     return SDValue();
6906
6907   EVT VT = Op.getValueType();
6908
6909   // Only AVX2 support 256-bit vector integer extending.
6910   if (!Subtarget->hasInt256() && VT.is256BitVector())
6911     return SDValue();
6912
6913   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6914   SDLoc DL(Op);
6915   SDValue V1 = Op.getOperand(0);
6916   SDValue V2 = Op.getOperand(1);
6917   unsigned NumElems = VT.getVectorNumElements();
6918
6919   // Extending is an unary operation and the element type of the source vector
6920   // won't be equal to or larger than i64.
6921   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6922       VT.getVectorElementType() == MVT::i64)
6923     return SDValue();
6924
6925   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6926   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6927   while ((1U << Shift) < NumElems) {
6928     if (SVOp->getMaskElt(1U << Shift) == 1)
6929       break;
6930     Shift += 1;
6931     // The maximal ratio is 8, i.e. from i8 to i64.
6932     if (Shift > 3)
6933       return SDValue();
6934   }
6935
6936   // Check the shuffle mask.
6937   unsigned Mask = (1U << Shift) - 1;
6938   for (unsigned i = 0; i != NumElems; ++i) {
6939     int EltIdx = SVOp->getMaskElt(i);
6940     if ((i & Mask) != 0 && EltIdx != -1)
6941       return SDValue();
6942     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6943       return SDValue();
6944   }
6945
6946   LLVMContext *Context = DAG.getContext();
6947   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6948   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6949   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6950
6951   if (!isTypeLegal(NVT))
6952     return SDValue();
6953
6954   // Simplify the operand as it's prepared to be fed into shuffle.
6955   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6956   if (V1.getOpcode() == ISD::BITCAST &&
6957       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6958       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6959       V1.getOperand(0)
6960         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6961     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6962     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6963     ConstantSDNode *CIdx =
6964       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6965     // If it's foldable, i.e. normal load with single use, we will let code
6966     // selection to fold it. Otherwise, we will short the conversion sequence.
6967     if (CIdx && CIdx->getZExtValue() == 0 &&
6968         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6969       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6970         // The "ext_vec_elt" node is wider than the result node.
6971         // In this case we should extract subvector from V.
6972         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6973         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6974         EVT FullVT = V.getValueType();
6975         EVT SubVecVT = EVT::getVectorVT(*Context,
6976                                         FullVT.getVectorElementType(),
6977                                         FullVT.getVectorNumElements()/Ratio);
6978         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6979                         DAG.getIntPtrConstant(0));
6980       }
6981       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6982     }
6983   }
6984
6985   return DAG.getNode(ISD::BITCAST, DL, VT,
6986                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6987 }
6988
6989 SDValue
6990 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6991   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6992   MVT VT = Op.getValueType().getSimpleVT();
6993   SDLoc dl(Op);
6994   SDValue V1 = Op.getOperand(0);
6995   SDValue V2 = Op.getOperand(1);
6996
6997   if (isZeroShuffle(SVOp))
6998     return getZeroVector(VT, Subtarget, DAG, dl);
6999
7000   // Handle splat operations
7001   if (SVOp->isSplat()) {
7002     // Use vbroadcast whenever the splat comes from a foldable load
7003     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7004     if (Broadcast.getNode())
7005       return Broadcast;
7006   }
7007
7008   // Check integer expanding shuffles.
7009   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7010   if (NewOp.getNode())
7011     return NewOp;
7012
7013   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7014   // do it!
7015   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7016       VT == MVT::v16i16 || VT == MVT::v32i8) {
7017     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7018     if (NewOp.getNode())
7019       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7020   } else if ((VT == MVT::v4i32 ||
7021              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7022     // FIXME: Figure out a cleaner way to do this.
7023     // Try to make use of movq to zero out the top part.
7024     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7025       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7026       if (NewOp.getNode()) {
7027         MVT NewVT = NewOp.getValueType().getSimpleVT();
7028         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7029                                NewVT, true, false))
7030           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7031                               DAG, Subtarget, dl);
7032       }
7033     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7034       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7035       if (NewOp.getNode()) {
7036         MVT NewVT = NewOp.getValueType().getSimpleVT();
7037         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7038           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7039                               DAG, Subtarget, dl);
7040       }
7041     }
7042   }
7043   return SDValue();
7044 }
7045
7046 SDValue
7047 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7049   SDValue V1 = Op.getOperand(0);
7050   SDValue V2 = Op.getOperand(1);
7051   MVT VT = Op.getValueType().getSimpleVT();
7052   SDLoc dl(Op);
7053   unsigned NumElems = VT.getVectorNumElements();
7054   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7055   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7056   bool V1IsSplat = false;
7057   bool V2IsSplat = false;
7058   bool HasSSE2 = Subtarget->hasSSE2();
7059   bool HasFp256    = Subtarget->hasFp256();
7060   bool HasInt256   = Subtarget->hasInt256();
7061   MachineFunction &MF = DAG.getMachineFunction();
7062   bool OptForSize = MF.getFunction()->getAttributes().
7063     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7064
7065   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7066
7067   if (V1IsUndef && V2IsUndef)
7068     return DAG.getUNDEF(VT);
7069
7070   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7071
7072   // Vector shuffle lowering takes 3 steps:
7073   //
7074   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7075   //    narrowing and commutation of operands should be handled.
7076   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7077   //    shuffle nodes.
7078   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7079   //    so the shuffle can be broken into other shuffles and the legalizer can
7080   //    try the lowering again.
7081   //
7082   // The general idea is that no vector_shuffle operation should be left to
7083   // be matched during isel, all of them must be converted to a target specific
7084   // node here.
7085
7086   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7087   // narrowing and commutation of operands should be handled. The actual code
7088   // doesn't include all of those, work in progress...
7089   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7090   if (NewOp.getNode())
7091     return NewOp;
7092
7093   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7094
7095   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7096   // unpckh_undef). Only use pshufd if speed is more important than size.
7097   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7098     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7099   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7100     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7101
7102   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7103       V2IsUndef && MayFoldVectorLoad(V1))
7104     return getMOVDDup(Op, dl, V1, DAG);
7105
7106   if (isMOVHLPS_v_undef_Mask(M, VT))
7107     return getMOVHighToLow(Op, dl, DAG);
7108
7109   // Use to match splats
7110   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7111       (VT == MVT::v2f64 || VT == MVT::v2i64))
7112     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7113
7114   if (isPSHUFDMask(M, VT)) {
7115     // The actual implementation will match the mask in the if above and then
7116     // during isel it can match several different instructions, not only pshufd
7117     // as its name says, sad but true, emulate the behavior for now...
7118     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7119       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7120
7121     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7122
7123     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7124       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7125
7126     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7127       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7128                                   DAG);
7129
7130     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7131                                 TargetMask, DAG);
7132   }
7133
7134   if (isPALIGNRMask(M, VT, Subtarget))
7135     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7136                                 getShufflePALIGNRImmediate(SVOp),
7137                                 DAG);
7138
7139   // Check if this can be converted into a logical shift.
7140   bool isLeft = false;
7141   unsigned ShAmt = 0;
7142   SDValue ShVal;
7143   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7144   if (isShift && ShVal.hasOneUse()) {
7145     // If the shifted value has multiple uses, it may be cheaper to use
7146     // v_set0 + movlhps or movhlps, etc.
7147     MVT EltVT = VT.getVectorElementType();
7148     ShAmt *= EltVT.getSizeInBits();
7149     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7150   }
7151
7152   if (isMOVLMask(M, VT)) {
7153     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7154       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7155     if (!isMOVLPMask(M, VT)) {
7156       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7157         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7158
7159       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7160         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7161     }
7162   }
7163
7164   // FIXME: fold these into legal mask.
7165   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7166     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7167
7168   if (isMOVHLPSMask(M, VT))
7169     return getMOVHighToLow(Op, dl, DAG);
7170
7171   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7172     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7173
7174   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7175     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7176
7177   if (isMOVLPMask(M, VT))
7178     return getMOVLP(Op, dl, DAG, HasSSE2);
7179
7180   if (ShouldXformToMOVHLPS(M, VT) ||
7181       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7182     return CommuteVectorShuffle(SVOp, DAG);
7183
7184   if (isShift) {
7185     // No better options. Use a vshldq / vsrldq.
7186     MVT EltVT = VT.getVectorElementType();
7187     ShAmt *= EltVT.getSizeInBits();
7188     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7189   }
7190
7191   bool Commuted = false;
7192   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7193   // 1,1,1,1 -> v8i16 though.
7194   V1IsSplat = isSplatVector(V1.getNode());
7195   V2IsSplat = isSplatVector(V2.getNode());
7196
7197   // Canonicalize the splat or undef, if present, to be on the RHS.
7198   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7199     CommuteVectorShuffleMask(M, NumElems);
7200     std::swap(V1, V2);
7201     std::swap(V1IsSplat, V2IsSplat);
7202     Commuted = true;
7203   }
7204
7205   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7206     // Shuffling low element of v1 into undef, just return v1.
7207     if (V2IsUndef)
7208       return V1;
7209     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7210     // the instruction selector will not match, so get a canonical MOVL with
7211     // swapped operands to undo the commute.
7212     return getMOVL(DAG, dl, VT, V2, V1);
7213   }
7214
7215   if (isUNPCKLMask(M, VT, HasInt256))
7216     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7217
7218   if (isUNPCKHMask(M, VT, HasInt256))
7219     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7220
7221   if (V2IsSplat) {
7222     // Normalize mask so all entries that point to V2 points to its first
7223     // element then try to match unpck{h|l} again. If match, return a
7224     // new vector_shuffle with the corrected mask.p
7225     SmallVector<int, 8> NewMask(M.begin(), M.end());
7226     NormalizeMask(NewMask, NumElems);
7227     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7228       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7229     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7230       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7231   }
7232
7233   if (Commuted) {
7234     // Commute is back and try unpck* again.
7235     // FIXME: this seems wrong.
7236     CommuteVectorShuffleMask(M, NumElems);
7237     std::swap(V1, V2);
7238     std::swap(V1IsSplat, V2IsSplat);
7239     Commuted = false;
7240
7241     if (isUNPCKLMask(M, VT, HasInt256))
7242       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7243
7244     if (isUNPCKHMask(M, VT, HasInt256))
7245       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7246   }
7247
7248   // Normalize the node to match x86 shuffle ops if needed
7249   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7250     return CommuteVectorShuffle(SVOp, DAG);
7251
7252   // The checks below are all present in isShuffleMaskLegal, but they are
7253   // inlined here right now to enable us to directly emit target specific
7254   // nodes, and remove one by one until they don't return Op anymore.
7255
7256   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7257       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7258     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7259       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7260   }
7261
7262   if (isPSHUFHWMask(M, VT, HasInt256))
7263     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7264                                 getShufflePSHUFHWImmediate(SVOp),
7265                                 DAG);
7266
7267   if (isPSHUFLWMask(M, VT, HasInt256))
7268     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7269                                 getShufflePSHUFLWImmediate(SVOp),
7270                                 DAG);
7271
7272   if (isSHUFPMask(M, VT, HasFp256))
7273     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7274                                 getShuffleSHUFImmediate(SVOp), DAG);
7275
7276   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7277     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7278   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7279     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7280
7281   //===--------------------------------------------------------------------===//
7282   // Generate target specific nodes for 128 or 256-bit shuffles only
7283   // supported in the AVX instruction set.
7284   //
7285
7286   // Handle VMOVDDUPY permutations
7287   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7288     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7289
7290   // Handle VPERMILPS/D* permutations
7291   if (isVPERMILPMask(M, VT, HasFp256)) {
7292     if (HasInt256 && VT == MVT::v8i32)
7293       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7294                                   getShuffleSHUFImmediate(SVOp), DAG);
7295     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7296                                 getShuffleSHUFImmediate(SVOp), DAG);
7297   }
7298
7299   // Handle VPERM2F128/VPERM2I128 permutations
7300   if (isVPERM2X128Mask(M, VT, HasFp256))
7301     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7302                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7303
7304   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7305   if (BlendOp.getNode())
7306     return BlendOp;
7307
7308   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7309     SmallVector<SDValue, 8> permclMask;
7310     for (unsigned i = 0; i != 8; ++i) {
7311       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7312     }
7313     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7314                                &permclMask[0], 8);
7315     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7316     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7317                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7318   }
7319
7320   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7321     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7322                                 getShuffleCLImmediate(SVOp), DAG);
7323
7324   //===--------------------------------------------------------------------===//
7325   // Since no target specific shuffle was selected for this generic one,
7326   // lower it into other known shuffles. FIXME: this isn't true yet, but
7327   // this is the plan.
7328   //
7329
7330   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7331   if (VT == MVT::v8i16) {
7332     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7333     if (NewOp.getNode())
7334       return NewOp;
7335   }
7336
7337   if (VT == MVT::v16i8) {
7338     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7339     if (NewOp.getNode())
7340       return NewOp;
7341   }
7342
7343   if (VT == MVT::v32i8) {
7344     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7345     if (NewOp.getNode())
7346       return NewOp;
7347   }
7348
7349   // Handle all 128-bit wide vectors with 4 elements, and match them with
7350   // several different shuffle types.
7351   if (NumElems == 4 && VT.is128BitVector())
7352     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7353
7354   // Handle general 256-bit shuffles
7355   if (VT.is256BitVector())
7356     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7357
7358   return SDValue();
7359 }
7360
7361 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7362   MVT VT = Op.getValueType().getSimpleVT();
7363   SDLoc dl(Op);
7364
7365   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7366     return SDValue();
7367
7368   if (VT.getSizeInBits() == 8) {
7369     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7370                                   Op.getOperand(0), Op.getOperand(1));
7371     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7372                                   DAG.getValueType(VT));
7373     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7374   }
7375
7376   if (VT.getSizeInBits() == 16) {
7377     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7378     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7379     if (Idx == 0)
7380       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7381                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7382                                      DAG.getNode(ISD::BITCAST, dl,
7383                                                  MVT::v4i32,
7384                                                  Op.getOperand(0)),
7385                                      Op.getOperand(1)));
7386     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7387                                   Op.getOperand(0), Op.getOperand(1));
7388     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7389                                   DAG.getValueType(VT));
7390     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7391   }
7392
7393   if (VT == MVT::f32) {
7394     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7395     // the result back to FR32 register. It's only worth matching if the
7396     // result has a single use which is a store or a bitcast to i32.  And in
7397     // the case of a store, it's not worth it if the index is a constant 0,
7398     // because a MOVSSmr can be used instead, which is smaller and faster.
7399     if (!Op.hasOneUse())
7400       return SDValue();
7401     SDNode *User = *Op.getNode()->use_begin();
7402     if ((User->getOpcode() != ISD::STORE ||
7403          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7404           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7405         (User->getOpcode() != ISD::BITCAST ||
7406          User->getValueType(0) != MVT::i32))
7407       return SDValue();
7408     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7409                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7410                                               Op.getOperand(0)),
7411                                               Op.getOperand(1));
7412     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7413   }
7414
7415   if (VT == MVT::i32 || VT == MVT::i64) {
7416     // ExtractPS/pextrq works with constant index.
7417     if (isa<ConstantSDNode>(Op.getOperand(1)))
7418       return Op;
7419   }
7420   return SDValue();
7421 }
7422
7423 SDValue
7424 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7425                                            SelectionDAG &DAG) const {
7426   SDLoc dl(Op);
7427   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7428     return SDValue();
7429
7430   SDValue Vec = Op.getOperand(0);
7431   MVT VecVT = Vec.getValueType().getSimpleVT();
7432
7433   // If this is a 256-bit vector result, first extract the 128-bit vector and
7434   // then extract the element from the 128-bit vector.
7435   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7436     SDValue Idx = Op.getOperand(1);
7437     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7438
7439     // Get the 128-bit vector.
7440     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7441     EVT EltVT = VecVT.getVectorElementType();
7442
7443     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7444
7445     //if (IdxVal >= NumElems/2)
7446     //  IdxVal -= NumElems/2;
7447     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7448     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7449                        DAG.getConstant(IdxVal, MVT::i32));
7450   }
7451
7452   assert(VecVT.is128BitVector() && "Unexpected vector length");
7453
7454   if (Subtarget->hasSSE41()) {
7455     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7456     if (Res.getNode())
7457       return Res;
7458   }
7459
7460   MVT VT = Op.getValueType().getSimpleVT();
7461   // TODO: handle v16i8.
7462   if (VT.getSizeInBits() == 16) {
7463     SDValue Vec = Op.getOperand(0);
7464     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7465     if (Idx == 0)
7466       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7467                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7468                                      DAG.getNode(ISD::BITCAST, dl,
7469                                                  MVT::v4i32, Vec),
7470                                      Op.getOperand(1)));
7471     // Transform it so it match pextrw which produces a 32-bit result.
7472     MVT EltVT = MVT::i32;
7473     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7474                                   Op.getOperand(0), Op.getOperand(1));
7475     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7476                                   DAG.getValueType(VT));
7477     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7478   }
7479
7480   if (VT.getSizeInBits() == 32) {
7481     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7482     if (Idx == 0)
7483       return Op;
7484
7485     // SHUFPS the element to the lowest double word, then movss.
7486     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7487     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7488     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7489                                        DAG.getUNDEF(VVT), Mask);
7490     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7491                        DAG.getIntPtrConstant(0));
7492   }
7493
7494   if (VT.getSizeInBits() == 64) {
7495     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7496     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7497     //        to match extract_elt for f64.
7498     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7499     if (Idx == 0)
7500       return Op;
7501
7502     // UNPCKHPD the element to the lowest double word, then movsd.
7503     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7504     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7505     int Mask[2] = { 1, -1 };
7506     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7507     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7508                                        DAG.getUNDEF(VVT), Mask);
7509     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7510                        DAG.getIntPtrConstant(0));
7511   }
7512
7513   return SDValue();
7514 }
7515
7516 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7517   MVT VT = Op.getValueType().getSimpleVT();
7518   MVT EltVT = VT.getVectorElementType();
7519   SDLoc dl(Op);
7520
7521   SDValue N0 = Op.getOperand(0);
7522   SDValue N1 = Op.getOperand(1);
7523   SDValue N2 = Op.getOperand(2);
7524
7525   if (!VT.is128BitVector())
7526     return SDValue();
7527
7528   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7529       isa<ConstantSDNode>(N2)) {
7530     unsigned Opc;
7531     if (VT == MVT::v8i16)
7532       Opc = X86ISD::PINSRW;
7533     else if (VT == MVT::v16i8)
7534       Opc = X86ISD::PINSRB;
7535     else
7536       Opc = X86ISD::PINSRB;
7537
7538     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7539     // argument.
7540     if (N1.getValueType() != MVT::i32)
7541       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7542     if (N2.getValueType() != MVT::i32)
7543       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7544     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7545   }
7546
7547   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7548     // Bits [7:6] of the constant are the source select.  This will always be
7549     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7550     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7551     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7552     // Bits [5:4] of the constant are the destination select.  This is the
7553     //  value of the incoming immediate.
7554     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7555     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7556     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7557     // Create this as a scalar to vector..
7558     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7559     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7560   }
7561
7562   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7563     // PINSR* works with constant index.
7564     return Op;
7565   }
7566   return SDValue();
7567 }
7568
7569 SDValue
7570 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7571   MVT VT = Op.getValueType().getSimpleVT();
7572   MVT EltVT = VT.getVectorElementType();
7573
7574   SDLoc dl(Op);
7575   SDValue N0 = Op.getOperand(0);
7576   SDValue N1 = Op.getOperand(1);
7577   SDValue N2 = Op.getOperand(2);
7578
7579   // If this is a 256-bit vector result, first extract the 128-bit vector,
7580   // insert the element into the extracted half and then place it back.
7581   if (VT.is256BitVector() || VT.is512BitVector()) {
7582     if (!isa<ConstantSDNode>(N2))
7583       return SDValue();
7584
7585     // Get the desired 128-bit vector half.
7586     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7587     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7588
7589     // Insert the element into the desired half.
7590     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7591     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7592
7593     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7594                     DAG.getConstant(IdxIn128, MVT::i32));
7595
7596     // Insert the changed part back to the 256-bit vector
7597     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7598   }
7599
7600   if (Subtarget->hasSSE41())
7601     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7602
7603   if (EltVT == MVT::i8)
7604     return SDValue();
7605
7606   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7607     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7608     // as its second argument.
7609     if (N1.getValueType() != MVT::i32)
7610       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7611     if (N2.getValueType() != MVT::i32)
7612       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7613     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7614   }
7615   return SDValue();
7616 }
7617
7618 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7619   LLVMContext *Context = DAG.getContext();
7620   SDLoc dl(Op);
7621   MVT OpVT = Op.getValueType().getSimpleVT();
7622
7623   // If this is a 256-bit vector result, first insert into a 128-bit
7624   // vector and then insert into the 256-bit vector.
7625   if (!OpVT.is128BitVector()) {
7626     // Insert into a 128-bit vector.
7627     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7628     EVT VT128 = EVT::getVectorVT(*Context,
7629                                  OpVT.getVectorElementType(),
7630                                  OpVT.getVectorNumElements() / SizeFactor);
7631
7632     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7633
7634     // Insert the 128-bit vector.
7635     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7636   }
7637
7638   if (OpVT == MVT::v1i64 &&
7639       Op.getOperand(0).getValueType() == MVT::i64)
7640     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7641
7642   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7643   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7644   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7645                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7646 }
7647
7648 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7649 // a simple subregister reference or explicit instructions to grab
7650 // upper bits of a vector.
7651 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7652                                       SelectionDAG &DAG) {
7653   SDLoc dl(Op);
7654   SDValue In =  Op.getOperand(0);
7655   SDValue Idx = Op.getOperand(1);
7656   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7657   EVT ResVT   = Op.getValueType();
7658   EVT InVT    = In.getValueType();
7659
7660   if (Subtarget->hasFp256()) {
7661     if (ResVT.is128BitVector() &&
7662         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7663         isa<ConstantSDNode>(Idx)) {
7664       return Extract128BitVector(In, IdxVal, DAG, dl);
7665     }
7666     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7667         isa<ConstantSDNode>(Idx)) {
7668       return Extract256BitVector(In, IdxVal, DAG, dl);
7669     }
7670   }
7671   return SDValue();
7672 }
7673
7674 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7675 // simple superregister reference or explicit instructions to insert
7676 // the upper bits of a vector.
7677 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7678                                      SelectionDAG &DAG) {
7679   if (Subtarget->hasFp256()) {
7680     SDLoc dl(Op.getNode());
7681     SDValue Vec = Op.getNode()->getOperand(0);
7682     SDValue SubVec = Op.getNode()->getOperand(1);
7683     SDValue Idx = Op.getNode()->getOperand(2);
7684
7685     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7686          Op.getNode()->getValueType(0).is512BitVector()) &&
7687         SubVec.getNode()->getValueType(0).is128BitVector() &&
7688         isa<ConstantSDNode>(Idx)) {
7689       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7690       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7691     }
7692
7693     if (Op.getNode()->getValueType(0).is512BitVector() &&
7694         SubVec.getNode()->getValueType(0).is256BitVector() &&
7695         isa<ConstantSDNode>(Idx)) {
7696       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7697       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7698     }
7699   }
7700   return SDValue();
7701 }
7702
7703 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7704 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7705 // one of the above mentioned nodes. It has to be wrapped because otherwise
7706 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7707 // be used to form addressing mode. These wrapped nodes will be selected
7708 // into MOV32ri.
7709 SDValue
7710 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7711   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7712
7713   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7714   // global base reg.
7715   unsigned char OpFlag = 0;
7716   unsigned WrapperKind = X86ISD::Wrapper;
7717   CodeModel::Model M = getTargetMachine().getCodeModel();
7718
7719   if (Subtarget->isPICStyleRIPRel() &&
7720       (M == CodeModel::Small || M == CodeModel::Kernel))
7721     WrapperKind = X86ISD::WrapperRIP;
7722   else if (Subtarget->isPICStyleGOT())
7723     OpFlag = X86II::MO_GOTOFF;
7724   else if (Subtarget->isPICStyleStubPIC())
7725     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7726
7727   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7728                                              CP->getAlignment(),
7729                                              CP->getOffset(), OpFlag);
7730   SDLoc DL(CP);
7731   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7732   // With PIC, the address is actually $g + Offset.
7733   if (OpFlag) {
7734     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7735                          DAG.getNode(X86ISD::GlobalBaseReg,
7736                                      SDLoc(), getPointerTy()),
7737                          Result);
7738   }
7739
7740   return Result;
7741 }
7742
7743 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7744   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7745
7746   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7747   // global base reg.
7748   unsigned char OpFlag = 0;
7749   unsigned WrapperKind = X86ISD::Wrapper;
7750   CodeModel::Model M = getTargetMachine().getCodeModel();
7751
7752   if (Subtarget->isPICStyleRIPRel() &&
7753       (M == CodeModel::Small || M == CodeModel::Kernel))
7754     WrapperKind = X86ISD::WrapperRIP;
7755   else if (Subtarget->isPICStyleGOT())
7756     OpFlag = X86II::MO_GOTOFF;
7757   else if (Subtarget->isPICStyleStubPIC())
7758     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7759
7760   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7761                                           OpFlag);
7762   SDLoc DL(JT);
7763   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7764
7765   // With PIC, the address is actually $g + Offset.
7766   if (OpFlag)
7767     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7768                          DAG.getNode(X86ISD::GlobalBaseReg,
7769                                      SDLoc(), getPointerTy()),
7770                          Result);
7771
7772   return Result;
7773 }
7774
7775 SDValue
7776 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7777   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7778
7779   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7780   // global base reg.
7781   unsigned char OpFlag = 0;
7782   unsigned WrapperKind = X86ISD::Wrapper;
7783   CodeModel::Model M = getTargetMachine().getCodeModel();
7784
7785   if (Subtarget->isPICStyleRIPRel() &&
7786       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7787     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7788       OpFlag = X86II::MO_GOTPCREL;
7789     WrapperKind = X86ISD::WrapperRIP;
7790   } else if (Subtarget->isPICStyleGOT()) {
7791     OpFlag = X86II::MO_GOT;
7792   } else if (Subtarget->isPICStyleStubPIC()) {
7793     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7794   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7795     OpFlag = X86II::MO_DARWIN_NONLAZY;
7796   }
7797
7798   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7799
7800   SDLoc DL(Op);
7801   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7802
7803   // With PIC, the address is actually $g + Offset.
7804   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7805       !Subtarget->is64Bit()) {
7806     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7807                          DAG.getNode(X86ISD::GlobalBaseReg,
7808                                      SDLoc(), getPointerTy()),
7809                          Result);
7810   }
7811
7812   // For symbols that require a load from a stub to get the address, emit the
7813   // load.
7814   if (isGlobalStubReference(OpFlag))
7815     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7816                          MachinePointerInfo::getGOT(), false, false, false, 0);
7817
7818   return Result;
7819 }
7820
7821 SDValue
7822 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7823   // Create the TargetBlockAddressAddress node.
7824   unsigned char OpFlags =
7825     Subtarget->ClassifyBlockAddressReference();
7826   CodeModel::Model M = getTargetMachine().getCodeModel();
7827   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7828   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7829   SDLoc dl(Op);
7830   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7831                                              OpFlags);
7832
7833   if (Subtarget->isPICStyleRIPRel() &&
7834       (M == CodeModel::Small || M == CodeModel::Kernel))
7835     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7836   else
7837     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7838
7839   // With PIC, the address is actually $g + Offset.
7840   if (isGlobalRelativeToPICBase(OpFlags)) {
7841     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7842                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7843                          Result);
7844   }
7845
7846   return Result;
7847 }
7848
7849 SDValue
7850 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7851                                       int64_t Offset, SelectionDAG &DAG) const {
7852   // Create the TargetGlobalAddress node, folding in the constant
7853   // offset if it is legal.
7854   unsigned char OpFlags =
7855     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7856   CodeModel::Model M = getTargetMachine().getCodeModel();
7857   SDValue Result;
7858   if (OpFlags == X86II::MO_NO_FLAG &&
7859       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7860     // A direct static reference to a global.
7861     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7862     Offset = 0;
7863   } else {
7864     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7865   }
7866
7867   if (Subtarget->isPICStyleRIPRel() &&
7868       (M == CodeModel::Small || M == CodeModel::Kernel))
7869     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7870   else
7871     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7872
7873   // With PIC, the address is actually $g + Offset.
7874   if (isGlobalRelativeToPICBase(OpFlags)) {
7875     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7876                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7877                          Result);
7878   }
7879
7880   // For globals that require a load from a stub to get the address, emit the
7881   // load.
7882   if (isGlobalStubReference(OpFlags))
7883     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7884                          MachinePointerInfo::getGOT(), false, false, false, 0);
7885
7886   // If there was a non-zero offset that we didn't fold, create an explicit
7887   // addition for it.
7888   if (Offset != 0)
7889     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7890                          DAG.getConstant(Offset, getPointerTy()));
7891
7892   return Result;
7893 }
7894
7895 SDValue
7896 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7897   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7898   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7899   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7900 }
7901
7902 static SDValue
7903 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7904            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7905            unsigned char OperandFlags, bool LocalDynamic = false) {
7906   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7907   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7908   SDLoc dl(GA);
7909   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7910                                            GA->getValueType(0),
7911                                            GA->getOffset(),
7912                                            OperandFlags);
7913
7914   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7915                                            : X86ISD::TLSADDR;
7916
7917   if (InFlag) {
7918     SDValue Ops[] = { Chain,  TGA, *InFlag };
7919     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7920   } else {
7921     SDValue Ops[]  = { Chain, TGA };
7922     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7923   }
7924
7925   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7926   MFI->setAdjustsStack(true);
7927
7928   SDValue Flag = Chain.getValue(1);
7929   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7930 }
7931
7932 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7933 static SDValue
7934 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7935                                 const EVT PtrVT) {
7936   SDValue InFlag;
7937   SDLoc dl(GA);  // ? function entry point might be better
7938   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7939                                    DAG.getNode(X86ISD::GlobalBaseReg,
7940                                                SDLoc(), PtrVT), InFlag);
7941   InFlag = Chain.getValue(1);
7942
7943   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7944 }
7945
7946 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7947 static SDValue
7948 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7949                                 const EVT PtrVT) {
7950   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7951                     X86::RAX, X86II::MO_TLSGD);
7952 }
7953
7954 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7955                                            SelectionDAG &DAG,
7956                                            const EVT PtrVT,
7957                                            bool is64Bit) {
7958   SDLoc dl(GA);
7959
7960   // Get the start address of the TLS block for this module.
7961   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7962       .getInfo<X86MachineFunctionInfo>();
7963   MFI->incNumLocalDynamicTLSAccesses();
7964
7965   SDValue Base;
7966   if (is64Bit) {
7967     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7968                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7969   } else {
7970     SDValue InFlag;
7971     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7972         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7973     InFlag = Chain.getValue(1);
7974     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7975                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7976   }
7977
7978   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7979   // of Base.
7980
7981   // Build x@dtpoff.
7982   unsigned char OperandFlags = X86II::MO_DTPOFF;
7983   unsigned WrapperKind = X86ISD::Wrapper;
7984   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7985                                            GA->getValueType(0),
7986                                            GA->getOffset(), OperandFlags);
7987   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7988
7989   // Add x@dtpoff with the base.
7990   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7991 }
7992
7993 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7994 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7995                                    const EVT PtrVT, TLSModel::Model model,
7996                                    bool is64Bit, bool isPIC) {
7997   SDLoc dl(GA);
7998
7999   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8000   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8001                                                          is64Bit ? 257 : 256));
8002
8003   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8004                                       DAG.getIntPtrConstant(0),
8005                                       MachinePointerInfo(Ptr),
8006                                       false, false, false, 0);
8007
8008   unsigned char OperandFlags = 0;
8009   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8010   // initialexec.
8011   unsigned WrapperKind = X86ISD::Wrapper;
8012   if (model == TLSModel::LocalExec) {
8013     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8014   } else if (model == TLSModel::InitialExec) {
8015     if (is64Bit) {
8016       OperandFlags = X86II::MO_GOTTPOFF;
8017       WrapperKind = X86ISD::WrapperRIP;
8018     } else {
8019       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8020     }
8021   } else {
8022     llvm_unreachable("Unexpected model");
8023   }
8024
8025   // emit "addl x@ntpoff,%eax" (local exec)
8026   // or "addl x@indntpoff,%eax" (initial exec)
8027   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8028   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8029                                            GA->getValueType(0),
8030                                            GA->getOffset(), OperandFlags);
8031   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8032
8033   if (model == TLSModel::InitialExec) {
8034     if (isPIC && !is64Bit) {
8035       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8036                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8037                            Offset);
8038     }
8039
8040     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8041                          MachinePointerInfo::getGOT(), false, false, false,
8042                          0);
8043   }
8044
8045   // The address of the thread local variable is the add of the thread
8046   // pointer with the offset of the variable.
8047   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8048 }
8049
8050 SDValue
8051 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8052
8053   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8054   const GlobalValue *GV = GA->getGlobal();
8055
8056   if (Subtarget->isTargetELF()) {
8057     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8058
8059     switch (model) {
8060       case TLSModel::GeneralDynamic:
8061         if (Subtarget->is64Bit())
8062           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8063         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8064       case TLSModel::LocalDynamic:
8065         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8066                                            Subtarget->is64Bit());
8067       case TLSModel::InitialExec:
8068       case TLSModel::LocalExec:
8069         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8070                                    Subtarget->is64Bit(),
8071                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8072     }
8073     llvm_unreachable("Unknown TLS model.");
8074   }
8075
8076   if (Subtarget->isTargetDarwin()) {
8077     // Darwin only has one model of TLS.  Lower to that.
8078     unsigned char OpFlag = 0;
8079     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8080                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8081
8082     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8083     // global base reg.
8084     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8085                   !Subtarget->is64Bit();
8086     if (PIC32)
8087       OpFlag = X86II::MO_TLVP_PIC_BASE;
8088     else
8089       OpFlag = X86II::MO_TLVP;
8090     SDLoc DL(Op);
8091     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8092                                                 GA->getValueType(0),
8093                                                 GA->getOffset(), OpFlag);
8094     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8095
8096     // With PIC32, the address is actually $g + Offset.
8097     if (PIC32)
8098       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8099                            DAG.getNode(X86ISD::GlobalBaseReg,
8100                                        SDLoc(), getPointerTy()),
8101                            Offset);
8102
8103     // Lowering the machine isd will make sure everything is in the right
8104     // location.
8105     SDValue Chain = DAG.getEntryNode();
8106     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8107     SDValue Args[] = { Chain, Offset };
8108     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8109
8110     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8111     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8112     MFI->setAdjustsStack(true);
8113
8114     // And our return value (tls address) is in the standard call return value
8115     // location.
8116     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8117     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8118                               Chain.getValue(1));
8119   }
8120
8121   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8122     // Just use the implicit TLS architecture
8123     // Need to generate someting similar to:
8124     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8125     //                                  ; from TEB
8126     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8127     //   mov     rcx, qword [rdx+rcx*8]
8128     //   mov     eax, .tls$:tlsvar
8129     //   [rax+rcx] contains the address
8130     // Windows 64bit: gs:0x58
8131     // Windows 32bit: fs:__tls_array
8132
8133     // If GV is an alias then use the aliasee for determining
8134     // thread-localness.
8135     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8136       GV = GA->resolveAliasedGlobal(false);
8137     SDLoc dl(GA);
8138     SDValue Chain = DAG.getEntryNode();
8139
8140     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8141     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8142     // use its literal value of 0x2C.
8143     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8144                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8145                                                              256)
8146                                         : Type::getInt32PtrTy(*DAG.getContext(),
8147                                                               257));
8148
8149     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8150       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8151         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8152
8153     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8154                                         MachinePointerInfo(Ptr),
8155                                         false, false, false, 0);
8156
8157     // Load the _tls_index variable
8158     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8159     if (Subtarget->is64Bit())
8160       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8161                            IDX, MachinePointerInfo(), MVT::i32,
8162                            false, false, 0);
8163     else
8164       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8165                         false, false, false, 0);
8166
8167     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8168                                     getPointerTy());
8169     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8170
8171     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8172     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8173                       false, false, false, 0);
8174
8175     // Get the offset of start of .tls section
8176     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8177                                              GA->getValueType(0),
8178                                              GA->getOffset(), X86II::MO_SECREL);
8179     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8180
8181     // The address of the thread local variable is the add of the thread
8182     // pointer with the offset of the variable.
8183     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8184   }
8185
8186   llvm_unreachable("TLS not implemented for this target.");
8187 }
8188
8189 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8190 /// and take a 2 x i32 value to shift plus a shift amount.
8191 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8192   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8193   EVT VT = Op.getValueType();
8194   unsigned VTBits = VT.getSizeInBits();
8195   SDLoc dl(Op);
8196   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8197   SDValue ShOpLo = Op.getOperand(0);
8198   SDValue ShOpHi = Op.getOperand(1);
8199   SDValue ShAmt  = Op.getOperand(2);
8200   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8201                                      DAG.getConstant(VTBits - 1, MVT::i8))
8202                        : DAG.getConstant(0, VT);
8203
8204   SDValue Tmp2, Tmp3;
8205   if (Op.getOpcode() == ISD::SHL_PARTS) {
8206     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8207     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8208   } else {
8209     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8210     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8211   }
8212
8213   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8214                                 DAG.getConstant(VTBits, MVT::i8));
8215   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8216                              AndNode, DAG.getConstant(0, MVT::i8));
8217
8218   SDValue Hi, Lo;
8219   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8220   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8221   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8222
8223   if (Op.getOpcode() == ISD::SHL_PARTS) {
8224     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8225     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8226   } else {
8227     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8228     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8229   }
8230
8231   SDValue Ops[2] = { Lo, Hi };
8232   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8233 }
8234
8235 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8236                                            SelectionDAG &DAG) const {
8237   EVT SrcVT = Op.getOperand(0).getValueType();
8238
8239   if (SrcVT.isVector())
8240     return SDValue();
8241
8242   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8243          "Unknown SINT_TO_FP to lower!");
8244
8245   // These are really Legal; return the operand so the caller accepts it as
8246   // Legal.
8247   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8248     return Op;
8249   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8250       Subtarget->is64Bit()) {
8251     return Op;
8252   }
8253
8254   SDLoc dl(Op);
8255   unsigned Size = SrcVT.getSizeInBits()/8;
8256   MachineFunction &MF = DAG.getMachineFunction();
8257   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8258   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8259   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8260                                StackSlot,
8261                                MachinePointerInfo::getFixedStack(SSFI),
8262                                false, false, 0);
8263   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8264 }
8265
8266 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8267                                      SDValue StackSlot,
8268                                      SelectionDAG &DAG) const {
8269   // Build the FILD
8270   SDLoc DL(Op);
8271   SDVTList Tys;
8272   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8273   if (useSSE)
8274     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8275   else
8276     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8277
8278   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8279
8280   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8281   MachineMemOperand *MMO;
8282   if (FI) {
8283     int SSFI = FI->getIndex();
8284     MMO =
8285       DAG.getMachineFunction()
8286       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8287                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8288   } else {
8289     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8290     StackSlot = StackSlot.getOperand(1);
8291   }
8292   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8293   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8294                                            X86ISD::FILD, DL,
8295                                            Tys, Ops, array_lengthof(Ops),
8296                                            SrcVT, MMO);
8297
8298   if (useSSE) {
8299     Chain = Result.getValue(1);
8300     SDValue InFlag = Result.getValue(2);
8301
8302     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8303     // shouldn't be necessary except that RFP cannot be live across
8304     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8305     MachineFunction &MF = DAG.getMachineFunction();
8306     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8307     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8308     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8309     Tys = DAG.getVTList(MVT::Other);
8310     SDValue Ops[] = {
8311       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8312     };
8313     MachineMemOperand *MMO =
8314       DAG.getMachineFunction()
8315       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8316                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8317
8318     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8319                                     Ops, array_lengthof(Ops),
8320                                     Op.getValueType(), MMO);
8321     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8322                          MachinePointerInfo::getFixedStack(SSFI),
8323                          false, false, false, 0);
8324   }
8325
8326   return Result;
8327 }
8328
8329 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8330 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8331                                                SelectionDAG &DAG) const {
8332   // This algorithm is not obvious. Here it is what we're trying to output:
8333   /*
8334      movq       %rax,  %xmm0
8335      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8336      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8337      #ifdef __SSE3__
8338        haddpd   %xmm0, %xmm0
8339      #else
8340        pshufd   $0x4e, %xmm0, %xmm1
8341        addpd    %xmm1, %xmm0
8342      #endif
8343   */
8344
8345   SDLoc dl(Op);
8346   LLVMContext *Context = DAG.getContext();
8347
8348   // Build some magic constants.
8349   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8350   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8351   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8352
8353   SmallVector<Constant*,2> CV1;
8354   CV1.push_back(
8355     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8356                                       APInt(64, 0x4330000000000000ULL))));
8357   CV1.push_back(
8358     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8359                                       APInt(64, 0x4530000000000000ULL))));
8360   Constant *C1 = ConstantVector::get(CV1);
8361   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8362
8363   // Load the 64-bit value into an XMM register.
8364   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8365                             Op.getOperand(0));
8366   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8367                               MachinePointerInfo::getConstantPool(),
8368                               false, false, false, 16);
8369   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8370                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8371                               CLod0);
8372
8373   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8374                               MachinePointerInfo::getConstantPool(),
8375                               false, false, false, 16);
8376   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8377   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8378   SDValue Result;
8379
8380   if (Subtarget->hasSSE3()) {
8381     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8382     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8383   } else {
8384     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8385     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8386                                            S2F, 0x4E, DAG);
8387     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8388                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8389                          Sub);
8390   }
8391
8392   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8393                      DAG.getIntPtrConstant(0));
8394 }
8395
8396 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8397 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8398                                                SelectionDAG &DAG) const {
8399   SDLoc dl(Op);
8400   // FP constant to bias correct the final result.
8401   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8402                                    MVT::f64);
8403
8404   // Load the 32-bit value into an XMM register.
8405   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8406                              Op.getOperand(0));
8407
8408   // Zero out the upper parts of the register.
8409   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8410
8411   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8412                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8413                      DAG.getIntPtrConstant(0));
8414
8415   // Or the load with the bias.
8416   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8417                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8418                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8419                                                    MVT::v2f64, Load)),
8420                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8421                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8422                                                    MVT::v2f64, Bias)));
8423   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8424                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8425                    DAG.getIntPtrConstant(0));
8426
8427   // Subtract the bias.
8428   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8429
8430   // Handle final rounding.
8431   EVT DestVT = Op.getValueType();
8432
8433   if (DestVT.bitsLT(MVT::f64))
8434     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8435                        DAG.getIntPtrConstant(0));
8436   if (DestVT.bitsGT(MVT::f64))
8437     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8438
8439   // Handle final rounding.
8440   return Sub;
8441 }
8442
8443 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8444                                                SelectionDAG &DAG) const {
8445   SDValue N0 = Op.getOperand(0);
8446   EVT SVT = N0.getValueType();
8447   SDLoc dl(Op);
8448
8449   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8450           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8451          "Custom UINT_TO_FP is not supported!");
8452
8453   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8454                              SVT.getVectorNumElements());
8455   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8456                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8457 }
8458
8459 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8460                                            SelectionDAG &DAG) const {
8461   SDValue N0 = Op.getOperand(0);
8462   SDLoc dl(Op);
8463
8464   if (Op.getValueType().isVector())
8465     return lowerUINT_TO_FP_vec(Op, DAG);
8466
8467   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8468   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8469   // the optimization here.
8470   if (DAG.SignBitIsZero(N0))
8471     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8472
8473   EVT SrcVT = N0.getValueType();
8474   EVT DstVT = Op.getValueType();
8475   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8476     return LowerUINT_TO_FP_i64(Op, DAG);
8477   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8478     return LowerUINT_TO_FP_i32(Op, DAG);
8479   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8480     return SDValue();
8481
8482   // Make a 64-bit buffer, and use it to build an FILD.
8483   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8484   if (SrcVT == MVT::i32) {
8485     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8486     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8487                                      getPointerTy(), StackSlot, WordOff);
8488     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8489                                   StackSlot, MachinePointerInfo(),
8490                                   false, false, 0);
8491     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8492                                   OffsetSlot, MachinePointerInfo(),
8493                                   false, false, 0);
8494     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8495     return Fild;
8496   }
8497
8498   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8499   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8500                                StackSlot, MachinePointerInfo(),
8501                                false, false, 0);
8502   // For i64 source, we need to add the appropriate power of 2 if the input
8503   // was negative.  This is the same as the optimization in
8504   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8505   // we must be careful to do the computation in x87 extended precision, not
8506   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8507   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8508   MachineMemOperand *MMO =
8509     DAG.getMachineFunction()
8510     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8511                           MachineMemOperand::MOLoad, 8, 8);
8512
8513   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8514   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8515   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8516                                          array_lengthof(Ops), MVT::i64, MMO);
8517
8518   APInt FF(32, 0x5F800000ULL);
8519
8520   // Check whether the sign bit is set.
8521   SDValue SignSet = DAG.getSetCC(dl,
8522                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8523                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8524                                  ISD::SETLT);
8525
8526   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8527   SDValue FudgePtr = DAG.getConstantPool(
8528                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8529                                          getPointerTy());
8530
8531   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8532   SDValue Zero = DAG.getIntPtrConstant(0);
8533   SDValue Four = DAG.getIntPtrConstant(4);
8534   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8535                                Zero, Four);
8536   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8537
8538   // Load the value out, extending it from f32 to f80.
8539   // FIXME: Avoid the extend by constructing the right constant pool?
8540   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8541                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8542                                  MVT::f32, false, false, 4);
8543   // Extend everything to 80 bits to force it to be done on x87.
8544   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8545   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8546 }
8547
8548 std::pair<SDValue,SDValue>
8549 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8550                                     bool IsSigned, bool IsReplace) const {
8551   SDLoc DL(Op);
8552
8553   EVT DstTy = Op.getValueType();
8554
8555   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8556     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8557     DstTy = MVT::i64;
8558   }
8559
8560   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8561          DstTy.getSimpleVT() >= MVT::i16 &&
8562          "Unknown FP_TO_INT to lower!");
8563
8564   // These are really Legal.
8565   if (DstTy == MVT::i32 &&
8566       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8567     return std::make_pair(SDValue(), SDValue());
8568   if (Subtarget->is64Bit() &&
8569       DstTy == MVT::i64 &&
8570       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8571     return std::make_pair(SDValue(), SDValue());
8572
8573   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8574   // stack slot, or into the FTOL runtime function.
8575   MachineFunction &MF = DAG.getMachineFunction();
8576   unsigned MemSize = DstTy.getSizeInBits()/8;
8577   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8578   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8579
8580   unsigned Opc;
8581   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8582     Opc = X86ISD::WIN_FTOL;
8583   else
8584     switch (DstTy.getSimpleVT().SimpleTy) {
8585     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8586     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8587     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8588     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8589     }
8590
8591   SDValue Chain = DAG.getEntryNode();
8592   SDValue Value = Op.getOperand(0);
8593   EVT TheVT = Op.getOperand(0).getValueType();
8594   // FIXME This causes a redundant load/store if the SSE-class value is already
8595   // in memory, such as if it is on the callstack.
8596   if (isScalarFPTypeInSSEReg(TheVT)) {
8597     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8598     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8599                          MachinePointerInfo::getFixedStack(SSFI),
8600                          false, false, 0);
8601     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8602     SDValue Ops[] = {
8603       Chain, StackSlot, DAG.getValueType(TheVT)
8604     };
8605
8606     MachineMemOperand *MMO =
8607       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8608                               MachineMemOperand::MOLoad, MemSize, MemSize);
8609     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8610                                     array_lengthof(Ops), DstTy, MMO);
8611     Chain = Value.getValue(1);
8612     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8613     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8614   }
8615
8616   MachineMemOperand *MMO =
8617     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8618                             MachineMemOperand::MOStore, MemSize, MemSize);
8619
8620   if (Opc != X86ISD::WIN_FTOL) {
8621     // Build the FP_TO_INT*_IN_MEM
8622     SDValue Ops[] = { Chain, Value, StackSlot };
8623     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8624                                            Ops, array_lengthof(Ops), DstTy,
8625                                            MMO);
8626     return std::make_pair(FIST, StackSlot);
8627   } else {
8628     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8629       DAG.getVTList(MVT::Other, MVT::Glue),
8630       Chain, Value);
8631     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8632       MVT::i32, ftol.getValue(1));
8633     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8634       MVT::i32, eax.getValue(2));
8635     SDValue Ops[] = { eax, edx };
8636     SDValue pair = IsReplace
8637       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8638       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8639     return std::make_pair(pair, SDValue());
8640   }
8641 }
8642
8643 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8644                               const X86Subtarget *Subtarget) {
8645   MVT VT = Op->getValueType(0).getSimpleVT();
8646   SDValue In = Op->getOperand(0);
8647   MVT InVT = In.getValueType().getSimpleVT();
8648   SDLoc dl(Op);
8649
8650   // Optimize vectors in AVX mode:
8651   //
8652   //   v8i16 -> v8i32
8653   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8654   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8655   //   Concat upper and lower parts.
8656   //
8657   //   v4i32 -> v4i64
8658   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8659   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8660   //   Concat upper and lower parts.
8661   //
8662
8663   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8664       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8665     return SDValue();
8666
8667   if (Subtarget->hasInt256())
8668     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8669
8670   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8671   SDValue Undef = DAG.getUNDEF(InVT);
8672   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8673   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8674   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8675
8676   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8677                              VT.getVectorNumElements()/2);
8678
8679   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8680   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8681
8682   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8683 }
8684
8685 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8686                                            SelectionDAG &DAG) const {
8687   if (Subtarget->hasFp256()) {
8688     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8689     if (Res.getNode())
8690       return Res;
8691   }
8692
8693   return SDValue();
8694 }
8695 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8696                                             SelectionDAG &DAG) const {
8697   SDLoc DL(Op);
8698   MVT VT = Op.getValueType().getSimpleVT();
8699   SDValue In = Op.getOperand(0);
8700   MVT SVT = In.getValueType().getSimpleVT();
8701
8702   if (Subtarget->hasFp256()) {
8703     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8704     if (Res.getNode())
8705       return Res;
8706   }
8707
8708   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8709       VT.getVectorNumElements() != SVT.getVectorNumElements())
8710     return SDValue();
8711
8712   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8713
8714   // AVX2 has better support of integer extending.
8715   if (Subtarget->hasInt256())
8716     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8717
8718   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8719   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8720   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8721                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8722                                                 DAG.getUNDEF(MVT::v8i16),
8723                                                 &Mask[0]));
8724
8725   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8726 }
8727
8728 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8729   SDLoc DL(Op);
8730   MVT VT = Op.getValueType().getSimpleVT();
8731   SDValue In = Op.getOperand(0);
8732   MVT SVT = In.getValueType().getSimpleVT();
8733
8734   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8735     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8736     if (Subtarget->hasInt256()) {
8737       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8738       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8739       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8740                                 ShufMask);
8741       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8742                          DAG.getIntPtrConstant(0));
8743     }
8744
8745     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8746     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8747                                DAG.getIntPtrConstant(0));
8748     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8749                                DAG.getIntPtrConstant(2));
8750
8751     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8752     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8753
8754     // The PSHUFD mask:
8755     static const int ShufMask1[] = {0, 2, 0, 0};
8756     SDValue Undef = DAG.getUNDEF(VT);
8757     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8758     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8759
8760     // The MOVLHPS mask:
8761     static const int ShufMask2[] = {0, 1, 4, 5};
8762     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8763   }
8764
8765   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8766     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8767     if (Subtarget->hasInt256()) {
8768       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8769
8770       SmallVector<SDValue,32> pshufbMask;
8771       for (unsigned i = 0; i < 2; ++i) {
8772         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8773         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8774         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8775         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8776         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8777         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8778         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8779         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8780         for (unsigned j = 0; j < 8; ++j)
8781           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8782       }
8783       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8784                                &pshufbMask[0], 32);
8785       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8786       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8787
8788       static const int ShufMask[] = {0,  2,  -1,  -1};
8789       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8790                                 &ShufMask[0]);
8791       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8792                        DAG.getIntPtrConstant(0));
8793       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8794     }
8795
8796     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8797                                DAG.getIntPtrConstant(0));
8798
8799     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8800                                DAG.getIntPtrConstant(4));
8801
8802     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8803     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8804
8805     // The PSHUFB mask:
8806     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8807                                    -1, -1, -1, -1, -1, -1, -1, -1};
8808
8809     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8810     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8811     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8812
8813     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8814     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8815
8816     // The MOVLHPS Mask:
8817     static const int ShufMask2[] = {0, 1, 4, 5};
8818     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8819     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8820   }
8821
8822   // Handle truncation of V256 to V128 using shuffles.
8823   if (!VT.is128BitVector() || !SVT.is256BitVector())
8824     return SDValue();
8825
8826   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8827          "Invalid op");
8828   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8829
8830   unsigned NumElems = VT.getVectorNumElements();
8831   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8832                              NumElems * 2);
8833
8834   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8835   // Prepare truncation shuffle mask
8836   for (unsigned i = 0; i != NumElems; ++i)
8837     MaskVec[i] = i * 2;
8838   SDValue V = DAG.getVectorShuffle(NVT, DL,
8839                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8840                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8841   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8842                      DAG.getIntPtrConstant(0));
8843 }
8844
8845 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8846                                            SelectionDAG &DAG) const {
8847   MVT VT = Op.getValueType().getSimpleVT();
8848   if (VT.isVector()) {
8849     if (VT == MVT::v8i16)
8850       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8851                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8852                                      MVT::v8i32, Op.getOperand(0)));
8853     return SDValue();
8854   }
8855
8856   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8857     /*IsSigned=*/ true, /*IsReplace=*/ false);
8858   SDValue FIST = Vals.first, StackSlot = Vals.second;
8859   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8860   if (FIST.getNode() == 0) return Op;
8861
8862   if (StackSlot.getNode())
8863     // Load the result.
8864     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8865                        FIST, StackSlot, MachinePointerInfo(),
8866                        false, false, false, 0);
8867
8868   // The node is the result.
8869   return FIST;
8870 }
8871
8872 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8873                                            SelectionDAG &DAG) const {
8874   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8875     /*IsSigned=*/ false, /*IsReplace=*/ false);
8876   SDValue FIST = Vals.first, StackSlot = Vals.second;
8877   assert(FIST.getNode() && "Unexpected failure");
8878
8879   if (StackSlot.getNode())
8880     // Load the result.
8881     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8882                        FIST, StackSlot, MachinePointerInfo(),
8883                        false, false, false, 0);
8884
8885   // The node is the result.
8886   return FIST;
8887 }
8888
8889 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8890   SDLoc DL(Op);
8891   MVT VT = Op.getValueType().getSimpleVT();
8892   SDValue In = Op.getOperand(0);
8893   MVT SVT = In.getValueType().getSimpleVT();
8894
8895   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8896
8897   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8898                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8899                                  In, DAG.getUNDEF(SVT)));
8900 }
8901
8902 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8903   LLVMContext *Context = DAG.getContext();
8904   SDLoc dl(Op);
8905   MVT VT = Op.getValueType().getSimpleVT();
8906   MVT EltVT = VT;
8907   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8908   if (VT.isVector()) {
8909     EltVT = VT.getVectorElementType();
8910     NumElts = VT.getVectorNumElements();
8911   }
8912   Constant *C;
8913   if (EltVT == MVT::f64)
8914     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8915                                           APInt(64, ~(1ULL << 63))));
8916   else
8917     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8918                                           APInt(32, ~(1U << 31))));
8919   C = ConstantVector::getSplat(NumElts, C);
8920   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8921   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8922   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8923                              MachinePointerInfo::getConstantPool(),
8924                              false, false, false, Alignment);
8925   if (VT.isVector()) {
8926     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8927     return DAG.getNode(ISD::BITCAST, dl, VT,
8928                        DAG.getNode(ISD::AND, dl, ANDVT,
8929                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8930                                                Op.getOperand(0)),
8931                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8932   }
8933   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8934 }
8935
8936 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8937   LLVMContext *Context = DAG.getContext();
8938   SDLoc dl(Op);
8939   MVT VT = Op.getValueType().getSimpleVT();
8940   MVT EltVT = VT;
8941   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8942   if (VT.isVector()) {
8943     EltVT = VT.getVectorElementType();
8944     NumElts = VT.getVectorNumElements();
8945   }
8946   Constant *C;
8947   if (EltVT == MVT::f64)
8948     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8949                                           APInt(64, 1ULL << 63)));
8950   else
8951     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8952                                           APInt(32, 1U << 31)));
8953   C = ConstantVector::getSplat(NumElts, C);
8954   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8955   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8956   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8957                              MachinePointerInfo::getConstantPool(),
8958                              false, false, false, Alignment);
8959   if (VT.isVector()) {
8960     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8961     return DAG.getNode(ISD::BITCAST, dl, VT,
8962                        DAG.getNode(ISD::XOR, dl, XORVT,
8963                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8964                                                Op.getOperand(0)),
8965                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8966   }
8967
8968   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8969 }
8970
8971 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8972   LLVMContext *Context = DAG.getContext();
8973   SDValue Op0 = Op.getOperand(0);
8974   SDValue Op1 = Op.getOperand(1);
8975   SDLoc dl(Op);
8976   MVT VT = Op.getValueType().getSimpleVT();
8977   MVT SrcVT = Op1.getValueType().getSimpleVT();
8978
8979   // If second operand is smaller, extend it first.
8980   if (SrcVT.bitsLT(VT)) {
8981     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8982     SrcVT = VT;
8983   }
8984   // And if it is bigger, shrink it first.
8985   if (SrcVT.bitsGT(VT)) {
8986     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8987     SrcVT = VT;
8988   }
8989
8990   // At this point the operands and the result should have the same
8991   // type, and that won't be f80 since that is not custom lowered.
8992
8993   // First get the sign bit of second operand.
8994   SmallVector<Constant*,4> CV;
8995   if (SrcVT == MVT::f64) {
8996     const fltSemantics &Sem = APFloat::IEEEdouble;
8997     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8998     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8999   } else {
9000     const fltSemantics &Sem = APFloat::IEEEsingle;
9001     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9002     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
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   }
9006   Constant *C = ConstantVector::get(CV);
9007   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9008   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9009                               MachinePointerInfo::getConstantPool(),
9010                               false, false, false, 16);
9011   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9012
9013   // Shift sign bit right or left if the two operands have different types.
9014   if (SrcVT.bitsGT(VT)) {
9015     // Op0 is MVT::f32, Op1 is MVT::f64.
9016     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9017     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9018                           DAG.getConstant(32, MVT::i32));
9019     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9020     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9021                           DAG.getIntPtrConstant(0));
9022   }
9023
9024   // Clear first operand sign bit.
9025   CV.clear();
9026   if (VT == MVT::f64) {
9027     const fltSemantics &Sem = APFloat::IEEEdouble;
9028     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9029                                                    APInt(64, ~(1ULL << 63)))));
9030     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9031   } else {
9032     const fltSemantics &Sem = APFloat::IEEEsingle;
9033     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9034                                                    APInt(32, ~(1U << 31)))));
9035     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
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   }
9039   C = ConstantVector::get(CV);
9040   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9041   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9042                               MachinePointerInfo::getConstantPool(),
9043                               false, false, false, 16);
9044   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9045
9046   // Or the value with the sign bit.
9047   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9048 }
9049
9050 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9051   SDValue N0 = Op.getOperand(0);
9052   SDLoc dl(Op);
9053   MVT VT = Op.getValueType().getSimpleVT();
9054
9055   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9056   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9057                                   DAG.getConstant(1, VT));
9058   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9059 }
9060
9061 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9062 //
9063 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9064                                                   SelectionDAG &DAG) const {
9065   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9066
9067   if (!Subtarget->hasSSE41())
9068     return SDValue();
9069
9070   if (!Op->hasOneUse())
9071     return SDValue();
9072
9073   SDNode *N = Op.getNode();
9074   SDLoc DL(N);
9075
9076   SmallVector<SDValue, 8> Opnds;
9077   DenseMap<SDValue, unsigned> VecInMap;
9078   EVT VT = MVT::Other;
9079
9080   // Recognize a special case where a vector is casted into wide integer to
9081   // test all 0s.
9082   Opnds.push_back(N->getOperand(0));
9083   Opnds.push_back(N->getOperand(1));
9084
9085   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9086     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9087     // BFS traverse all OR'd operands.
9088     if (I->getOpcode() == ISD::OR) {
9089       Opnds.push_back(I->getOperand(0));
9090       Opnds.push_back(I->getOperand(1));
9091       // Re-evaluate the number of nodes to be traversed.
9092       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9093       continue;
9094     }
9095
9096     // Quit if a non-EXTRACT_VECTOR_ELT
9097     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9098       return SDValue();
9099
9100     // Quit if without a constant index.
9101     SDValue Idx = I->getOperand(1);
9102     if (!isa<ConstantSDNode>(Idx))
9103       return SDValue();
9104
9105     SDValue ExtractedFromVec = I->getOperand(0);
9106     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9107     if (M == VecInMap.end()) {
9108       VT = ExtractedFromVec.getValueType();
9109       // Quit if not 128/256-bit vector.
9110       if (!VT.is128BitVector() && !VT.is256BitVector())
9111         return SDValue();
9112       // Quit if not the same type.
9113       if (VecInMap.begin() != VecInMap.end() &&
9114           VT != VecInMap.begin()->first.getValueType())
9115         return SDValue();
9116       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9117     }
9118     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9119   }
9120
9121   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9122          "Not extracted from 128-/256-bit vector.");
9123
9124   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9125   SmallVector<SDValue, 8> VecIns;
9126
9127   for (DenseMap<SDValue, unsigned>::const_iterator
9128         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9129     // Quit if not all elements are used.
9130     if (I->second != FullMask)
9131       return SDValue();
9132     VecIns.push_back(I->first);
9133   }
9134
9135   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9136
9137   // Cast all vectors into TestVT for PTEST.
9138   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9139     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9140
9141   // If more than one full vectors are evaluated, OR them first before PTEST.
9142   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9143     // Each iteration will OR 2 nodes and append the result until there is only
9144     // 1 node left, i.e. the final OR'd value of all vectors.
9145     SDValue LHS = VecIns[Slot];
9146     SDValue RHS = VecIns[Slot + 1];
9147     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9148   }
9149
9150   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9151                      VecIns.back(), VecIns.back());
9152 }
9153
9154 /// Emit nodes that will be selected as "test Op0,Op0", or something
9155 /// equivalent.
9156 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9157                                     SelectionDAG &DAG) const {
9158   SDLoc dl(Op);
9159
9160   // CF and OF aren't always set the way we want. Determine which
9161   // of these we need.
9162   bool NeedCF = false;
9163   bool NeedOF = false;
9164   switch (X86CC) {
9165   default: break;
9166   case X86::COND_A: case X86::COND_AE:
9167   case X86::COND_B: case X86::COND_BE:
9168     NeedCF = true;
9169     break;
9170   case X86::COND_G: case X86::COND_GE:
9171   case X86::COND_L: case X86::COND_LE:
9172   case X86::COND_O: case X86::COND_NO:
9173     NeedOF = true;
9174     break;
9175   }
9176
9177   // See if we can use the EFLAGS value from the operand instead of
9178   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9179   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9180   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9181     // Emit a CMP with 0, which is the TEST pattern.
9182     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9183                        DAG.getConstant(0, Op.getValueType()));
9184
9185   unsigned Opcode = 0;
9186   unsigned NumOperands = 0;
9187
9188   // Truncate operations may prevent the merge of the SETCC instruction
9189   // and the arithmetic intruction before it. Attempt to truncate the operands
9190   // of the arithmetic instruction and use a reduced bit-width instruction.
9191   bool NeedTruncation = false;
9192   SDValue ArithOp = Op;
9193   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9194     SDValue Arith = Op->getOperand(0);
9195     // Both the trunc and the arithmetic op need to have one user each.
9196     if (Arith->hasOneUse())
9197       switch (Arith.getOpcode()) {
9198         default: break;
9199         case ISD::ADD:
9200         case ISD::SUB:
9201         case ISD::AND:
9202         case ISD::OR:
9203         case ISD::XOR: {
9204           NeedTruncation = true;
9205           ArithOp = Arith;
9206         }
9207       }
9208   }
9209
9210   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9211   // which may be the result of a CAST.  We use the variable 'Op', which is the
9212   // non-casted variable when we check for possible users.
9213   switch (ArithOp.getOpcode()) {
9214   case ISD::ADD:
9215     // Due to an isel shortcoming, be conservative if this add is likely to be
9216     // selected as part of a load-modify-store instruction. When the root node
9217     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9218     // uses of other nodes in the match, such as the ADD in this case. This
9219     // leads to the ADD being left around and reselected, with the result being
9220     // two adds in the output.  Alas, even if none our users are stores, that
9221     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9222     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9223     // climbing the DAG back to the root, and it doesn't seem to be worth the
9224     // effort.
9225     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9226          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9227       if (UI->getOpcode() != ISD::CopyToReg &&
9228           UI->getOpcode() != ISD::SETCC &&
9229           UI->getOpcode() != ISD::STORE)
9230         goto default_case;
9231
9232     if (ConstantSDNode *C =
9233         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9234       // An add of one will be selected as an INC.
9235       if (C->getAPIntValue() == 1) {
9236         Opcode = X86ISD::INC;
9237         NumOperands = 1;
9238         break;
9239       }
9240
9241       // An add of negative one (subtract of one) will be selected as a DEC.
9242       if (C->getAPIntValue().isAllOnesValue()) {
9243         Opcode = X86ISD::DEC;
9244         NumOperands = 1;
9245         break;
9246       }
9247     }
9248
9249     // Otherwise use a regular EFLAGS-setting add.
9250     Opcode = X86ISD::ADD;
9251     NumOperands = 2;
9252     break;
9253   case ISD::AND: {
9254     // If the primary and result isn't used, don't bother using X86ISD::AND,
9255     // because a TEST instruction will be better.
9256     bool NonFlagUse = false;
9257     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9258            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9259       SDNode *User = *UI;
9260       unsigned UOpNo = UI.getOperandNo();
9261       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9262         // Look pass truncate.
9263         UOpNo = User->use_begin().getOperandNo();
9264         User = *User->use_begin();
9265       }
9266
9267       if (User->getOpcode() != ISD::BRCOND &&
9268           User->getOpcode() != ISD::SETCC &&
9269           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9270         NonFlagUse = true;
9271         break;
9272       }
9273     }
9274
9275     if (!NonFlagUse)
9276       break;
9277   }
9278     // FALL THROUGH
9279   case ISD::SUB:
9280   case ISD::OR:
9281   case ISD::XOR:
9282     // Due to the ISEL shortcoming noted above, be conservative if this op is
9283     // likely to be selected as part of a load-modify-store instruction.
9284     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9285            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9286       if (UI->getOpcode() == ISD::STORE)
9287         goto default_case;
9288
9289     // Otherwise use a regular EFLAGS-setting instruction.
9290     switch (ArithOp.getOpcode()) {
9291     default: llvm_unreachable("unexpected operator!");
9292     case ISD::SUB: Opcode = X86ISD::SUB; break;
9293     case ISD::XOR: Opcode = X86ISD::XOR; break;
9294     case ISD::AND: Opcode = X86ISD::AND; break;
9295     case ISD::OR: {
9296       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9297         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9298         if (EFLAGS.getNode())
9299           return EFLAGS;
9300       }
9301       Opcode = X86ISD::OR;
9302       break;
9303     }
9304     }
9305
9306     NumOperands = 2;
9307     break;
9308   case X86ISD::ADD:
9309   case X86ISD::SUB:
9310   case X86ISD::INC:
9311   case X86ISD::DEC:
9312   case X86ISD::OR:
9313   case X86ISD::XOR:
9314   case X86ISD::AND:
9315     return SDValue(Op.getNode(), 1);
9316   default:
9317   default_case:
9318     break;
9319   }
9320
9321   // If we found that truncation is beneficial, perform the truncation and
9322   // update 'Op'.
9323   if (NeedTruncation) {
9324     EVT VT = Op.getValueType();
9325     SDValue WideVal = Op->getOperand(0);
9326     EVT WideVT = WideVal.getValueType();
9327     unsigned ConvertedOp = 0;
9328     // Use a target machine opcode to prevent further DAGCombine
9329     // optimizations that may separate the arithmetic operations
9330     // from the setcc node.
9331     switch (WideVal.getOpcode()) {
9332       default: break;
9333       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9334       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9335       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9336       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9337       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9338     }
9339
9340     if (ConvertedOp) {
9341       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9342       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9343         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9344         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9345         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9346       }
9347     }
9348   }
9349
9350   if (Opcode == 0)
9351     // Emit a CMP with 0, which is the TEST pattern.
9352     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9353                        DAG.getConstant(0, Op.getValueType()));
9354
9355   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9356   SmallVector<SDValue, 4> Ops;
9357   for (unsigned i = 0; i != NumOperands; ++i)
9358     Ops.push_back(Op.getOperand(i));
9359
9360   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9361   DAG.ReplaceAllUsesWith(Op, New);
9362   return SDValue(New.getNode(), 1);
9363 }
9364
9365 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9366 /// equivalent.
9367 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9368                                    SelectionDAG &DAG) const {
9369   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9370     if (C->getAPIntValue() == 0)
9371       return EmitTest(Op0, X86CC, DAG);
9372
9373   SDLoc dl(Op0);
9374   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9375        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9376     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9377     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9378     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9379                               Op0, Op1);
9380     return SDValue(Sub.getNode(), 1);
9381   }
9382   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9383 }
9384
9385 /// Convert a comparison if required by the subtarget.
9386 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9387                                                  SelectionDAG &DAG) const {
9388   // If the subtarget does not support the FUCOMI instruction, floating-point
9389   // comparisons have to be converted.
9390   if (Subtarget->hasCMov() ||
9391       Cmp.getOpcode() != X86ISD::CMP ||
9392       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9393       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9394     return Cmp;
9395
9396   // The instruction selector will select an FUCOM instruction instead of
9397   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9398   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9399   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9400   SDLoc dl(Cmp);
9401   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9402   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9403   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9404                             DAG.getConstant(8, MVT::i8));
9405   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9406   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9407 }
9408
9409 static bool isAllOnes(SDValue V) {
9410   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9411   return C && C->isAllOnesValue();
9412 }
9413
9414 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9415 /// if it's possible.
9416 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9417                                      SDLoc dl, SelectionDAG &DAG) const {
9418   SDValue Op0 = And.getOperand(0);
9419   SDValue Op1 = And.getOperand(1);
9420   if (Op0.getOpcode() == ISD::TRUNCATE)
9421     Op0 = Op0.getOperand(0);
9422   if (Op1.getOpcode() == ISD::TRUNCATE)
9423     Op1 = Op1.getOperand(0);
9424
9425   SDValue LHS, RHS;
9426   if (Op1.getOpcode() == ISD::SHL)
9427     std::swap(Op0, Op1);
9428   if (Op0.getOpcode() == ISD::SHL) {
9429     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9430       if (And00C->getZExtValue() == 1) {
9431         // If we looked past a truncate, check that it's only truncating away
9432         // known zeros.
9433         unsigned BitWidth = Op0.getValueSizeInBits();
9434         unsigned AndBitWidth = And.getValueSizeInBits();
9435         if (BitWidth > AndBitWidth) {
9436           APInt Zeros, Ones;
9437           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9438           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9439             return SDValue();
9440         }
9441         LHS = Op1;
9442         RHS = Op0.getOperand(1);
9443       }
9444   } else if (Op1.getOpcode() == ISD::Constant) {
9445     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9446     uint64_t AndRHSVal = AndRHS->getZExtValue();
9447     SDValue AndLHS = Op0;
9448
9449     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9450       LHS = AndLHS.getOperand(0);
9451       RHS = AndLHS.getOperand(1);
9452     }
9453
9454     // Use BT if the immediate can't be encoded in a TEST instruction.
9455     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9456       LHS = AndLHS;
9457       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9458     }
9459   }
9460
9461   if (LHS.getNode()) {
9462     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9463     // instruction.  Since the shift amount is in-range-or-undefined, we know
9464     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9465     // the encoding for the i16 version is larger than the i32 version.
9466     // Also promote i16 to i32 for performance / code size reason.
9467     if (LHS.getValueType() == MVT::i8 ||
9468         LHS.getValueType() == MVT::i16)
9469       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9470
9471     // If the operand types disagree, extend the shift amount to match.  Since
9472     // BT ignores high bits (like shifts) we can use anyextend.
9473     if (LHS.getValueType() != RHS.getValueType())
9474       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9475
9476     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9477     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9478     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9479                        DAG.getConstant(Cond, MVT::i8), BT);
9480   }
9481
9482   return SDValue();
9483 }
9484
9485 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9486 // ones, and then concatenate the result back.
9487 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9488   MVT VT = Op.getValueType().getSimpleVT();
9489
9490   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9491          "Unsupported value type for operation");
9492
9493   unsigned NumElems = VT.getVectorNumElements();
9494   SDLoc dl(Op);
9495   SDValue CC = Op.getOperand(2);
9496
9497   // Extract the LHS vectors
9498   SDValue LHS = Op.getOperand(0);
9499   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9500   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9501
9502   // Extract the RHS vectors
9503   SDValue RHS = Op.getOperand(1);
9504   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9505   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9506
9507   // Issue the operation on the smaller types and concatenate the result back
9508   MVT EltVT = VT.getVectorElementType();
9509   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9510   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9511                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9512                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9513 }
9514
9515 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9516                            SelectionDAG &DAG) {
9517   SDValue Cond;
9518   SDValue Op0 = Op.getOperand(0);
9519   SDValue Op1 = Op.getOperand(1);
9520   SDValue CC = Op.getOperand(2);
9521   MVT VT = Op.getValueType().getSimpleVT();
9522   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9523   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9524   SDLoc dl(Op);
9525
9526   if (isFP) {
9527 #ifndef NDEBUG
9528     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9529     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9530 #endif
9531
9532     unsigned SSECC;
9533     bool Swap = false;
9534
9535     // SSE Condition code mapping:
9536     //  0 - EQ
9537     //  1 - LT
9538     //  2 - LE
9539     //  3 - UNORD
9540     //  4 - NEQ
9541     //  5 - NLT
9542     //  6 - NLE
9543     //  7 - ORD
9544     switch (SetCCOpcode) {
9545     default: llvm_unreachable("Unexpected SETCC condition");
9546     case ISD::SETOEQ:
9547     case ISD::SETEQ:  SSECC = 0; break;
9548     case ISD::SETOGT:
9549     case ISD::SETGT: Swap = true; // Fallthrough
9550     case ISD::SETLT:
9551     case ISD::SETOLT: SSECC = 1; break;
9552     case ISD::SETOGE:
9553     case ISD::SETGE: Swap = true; // Fallthrough
9554     case ISD::SETLE:
9555     case ISD::SETOLE: SSECC = 2; break;
9556     case ISD::SETUO:  SSECC = 3; break;
9557     case ISD::SETUNE:
9558     case ISD::SETNE:  SSECC = 4; break;
9559     case ISD::SETULE: Swap = true; // Fallthrough
9560     case ISD::SETUGE: SSECC = 5; break;
9561     case ISD::SETULT: Swap = true; // Fallthrough
9562     case ISD::SETUGT: SSECC = 6; break;
9563     case ISD::SETO:   SSECC = 7; break;
9564     case ISD::SETUEQ:
9565     case ISD::SETONE: SSECC = 8; break;
9566     }
9567     if (Swap)
9568       std::swap(Op0, Op1);
9569
9570     // In the two special cases we can't handle, emit two comparisons.
9571     if (SSECC == 8) {
9572       unsigned CC0, CC1;
9573       unsigned CombineOpc;
9574       if (SetCCOpcode == ISD::SETUEQ) {
9575         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9576       } else {
9577         assert(SetCCOpcode == ISD::SETONE);
9578         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9579       }
9580
9581       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9582                                  DAG.getConstant(CC0, MVT::i8));
9583       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9584                                  DAG.getConstant(CC1, MVT::i8));
9585       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9586     }
9587     // Handle all other FP comparisons here.
9588     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9589                        DAG.getConstant(SSECC, MVT::i8));
9590   }
9591
9592   // Break 256-bit integer vector compare into smaller ones.
9593   if (VT.is256BitVector() && !Subtarget->hasInt256())
9594     return Lower256IntVSETCC(Op, DAG);
9595
9596   // We are handling one of the integer comparisons here.  Since SSE only has
9597   // GT and EQ comparisons for integer, swapping operands and multiple
9598   // operations may be required for some comparisons.
9599   unsigned Opc;
9600   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9601   
9602   switch (SetCCOpcode) {
9603   default: llvm_unreachable("Unexpected SETCC condition");
9604   case ISD::SETNE:  Invert = true;
9605   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9606   case ISD::SETLT:  Swap = true;
9607   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9608   case ISD::SETGE:  Swap = true;
9609   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9610   case ISD::SETULT: Swap = true;
9611   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9612   case ISD::SETUGE: Swap = true;
9613   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9614   }
9615   
9616   // Special case: Use min/max operations for SETULE/SETUGE
9617   MVT VET = VT.getVectorElementType();
9618   bool hasMinMax =
9619        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9620     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9621   
9622   if (hasMinMax) {
9623     switch (SetCCOpcode) {
9624     default: break;
9625     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9626     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9627     }
9628     
9629     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9630   }
9631   
9632   if (Swap)
9633     std::swap(Op0, Op1);
9634
9635   // Check that the operation in question is available (most are plain SSE2,
9636   // but PCMPGTQ and PCMPEQQ have different requirements).
9637   if (VT == MVT::v2i64) {
9638     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9639       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9640
9641       // First cast everything to the right type.
9642       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9643       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9644
9645       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9646       // bits of the inputs before performing those operations. The lower
9647       // compare is always unsigned.
9648       SDValue SB;
9649       if (FlipSigns) {
9650         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9651       } else {
9652         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9653         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9654         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9655                          Sign, Zero, Sign, Zero);
9656       }
9657       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9658       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9659
9660       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9661       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9662       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9663
9664       // Create masks for only the low parts/high parts of the 64 bit integers.
9665       static const int MaskHi[] = { 1, 1, 3, 3 };
9666       static const int MaskLo[] = { 0, 0, 2, 2 };
9667       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9668       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9669       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9670
9671       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9672       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9673
9674       if (Invert)
9675         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9676
9677       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9678     }
9679
9680     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9681       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9682       // pcmpeqd + pshufd + pand.
9683       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9684
9685       // First cast everything to the right type.
9686       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9687       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9688
9689       // Do the compare.
9690       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9691
9692       // Make sure the lower and upper halves are both all-ones.
9693       static const int Mask[] = { 1, 0, 3, 2 };
9694       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9695       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9696
9697       if (Invert)
9698         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9699
9700       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9701     }
9702   }
9703
9704   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9705   // bits of the inputs before performing those operations.
9706   if (FlipSigns) {
9707     EVT EltVT = VT.getVectorElementType();
9708     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9709     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9710     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9711   }
9712
9713   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9714
9715   // If the logical-not of the result is required, perform that now.
9716   if (Invert)
9717     Result = DAG.getNOT(dl, Result, VT);
9718   
9719   if (MinMax)
9720     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9721
9722   return Result;
9723 }
9724
9725 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9726
9727   MVT VT = Op.getValueType().getSimpleVT();
9728
9729   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9730
9731   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9732   SDValue Op0 = Op.getOperand(0);
9733   SDValue Op1 = Op.getOperand(1);
9734   SDLoc dl(Op);
9735   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9736
9737   // Optimize to BT if possible.
9738   // Lower (X & (1 << N)) == 0 to BT(X, N).
9739   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9740   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9741   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9742       Op1.getOpcode() == ISD::Constant &&
9743       cast<ConstantSDNode>(Op1)->isNullValue() &&
9744       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9745     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9746     if (NewSetCC.getNode())
9747       return NewSetCC;
9748   }
9749
9750   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9751   // these.
9752   if (Op1.getOpcode() == ISD::Constant &&
9753       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9754        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9755       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9756
9757     // If the input is a setcc, then reuse the input setcc or use a new one with
9758     // the inverted condition.
9759     if (Op0.getOpcode() == X86ISD::SETCC) {
9760       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9761       bool Invert = (CC == ISD::SETNE) ^
9762         cast<ConstantSDNode>(Op1)->isNullValue();
9763       if (!Invert) return Op0;
9764
9765       CCode = X86::GetOppositeBranchCondition(CCode);
9766       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9767                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9768     }
9769   }
9770
9771   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9772   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9773   if (X86CC == X86::COND_INVALID)
9774     return SDValue();
9775
9776   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9777   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9778   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9779                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9780 }
9781
9782 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9783 static bool isX86LogicalCmp(SDValue Op) {
9784   unsigned Opc = Op.getNode()->getOpcode();
9785   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9786       Opc == X86ISD::SAHF)
9787     return true;
9788   if (Op.getResNo() == 1 &&
9789       (Opc == X86ISD::ADD ||
9790        Opc == X86ISD::SUB ||
9791        Opc == X86ISD::ADC ||
9792        Opc == X86ISD::SBB ||
9793        Opc == X86ISD::SMUL ||
9794        Opc == X86ISD::UMUL ||
9795        Opc == X86ISD::INC ||
9796        Opc == X86ISD::DEC ||
9797        Opc == X86ISD::OR ||
9798        Opc == X86ISD::XOR ||
9799        Opc == X86ISD::AND))
9800     return true;
9801
9802   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9803     return true;
9804
9805   return false;
9806 }
9807
9808 static bool isZero(SDValue V) {
9809   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9810   return C && C->isNullValue();
9811 }
9812
9813 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9814   if (V.getOpcode() != ISD::TRUNCATE)
9815     return false;
9816
9817   SDValue VOp0 = V.getOperand(0);
9818   unsigned InBits = VOp0.getValueSizeInBits();
9819   unsigned Bits = V.getValueSizeInBits();
9820   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9821 }
9822
9823 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9824   bool addTest = true;
9825   SDValue Cond  = Op.getOperand(0);
9826   SDValue Op1 = Op.getOperand(1);
9827   SDValue Op2 = Op.getOperand(2);
9828   SDLoc DL(Op);
9829   SDValue CC;
9830
9831   if (Cond.getOpcode() == ISD::SETCC) {
9832     SDValue NewCond = LowerSETCC(Cond, DAG);
9833     if (NewCond.getNode())
9834       Cond = NewCond;
9835   }
9836
9837   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9838   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9839   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9840   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9841   if (Cond.getOpcode() == X86ISD::SETCC &&
9842       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9843       isZero(Cond.getOperand(1).getOperand(1))) {
9844     SDValue Cmp = Cond.getOperand(1);
9845
9846     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9847
9848     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9849         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9850       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9851
9852       SDValue CmpOp0 = Cmp.getOperand(0);
9853       // Apply further optimizations for special cases
9854       // (select (x != 0), -1, 0) -> neg & sbb
9855       // (select (x == 0), 0, -1) -> neg & sbb
9856       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9857         if (YC->isNullValue() &&
9858             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9859           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9860           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9861                                     DAG.getConstant(0, CmpOp0.getValueType()),
9862                                     CmpOp0);
9863           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9864                                     DAG.getConstant(X86::COND_B, MVT::i8),
9865                                     SDValue(Neg.getNode(), 1));
9866           return Res;
9867         }
9868
9869       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9870                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9871       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9872
9873       SDValue Res =   // Res = 0 or -1.
9874         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9875                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9876
9877       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9878         Res = DAG.getNOT(DL, Res, Res.getValueType());
9879
9880       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9881       if (N2C == 0 || !N2C->isNullValue())
9882         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9883       return Res;
9884     }
9885   }
9886
9887   // Look past (and (setcc_carry (cmp ...)), 1).
9888   if (Cond.getOpcode() == ISD::AND &&
9889       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9890     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9891     if (C && C->getAPIntValue() == 1)
9892       Cond = Cond.getOperand(0);
9893   }
9894
9895   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9896   // setting operand in place of the X86ISD::SETCC.
9897   unsigned CondOpcode = Cond.getOpcode();
9898   if (CondOpcode == X86ISD::SETCC ||
9899       CondOpcode == X86ISD::SETCC_CARRY) {
9900     CC = Cond.getOperand(0);
9901
9902     SDValue Cmp = Cond.getOperand(1);
9903     unsigned Opc = Cmp.getOpcode();
9904     MVT VT = Op.getValueType().getSimpleVT();
9905
9906     bool IllegalFPCMov = false;
9907     if (VT.isFloatingPoint() && !VT.isVector() &&
9908         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9909       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9910
9911     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9912         Opc == X86ISD::BT) { // FIXME
9913       Cond = Cmp;
9914       addTest = false;
9915     }
9916   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9917              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9918              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9919               Cond.getOperand(0).getValueType() != MVT::i8)) {
9920     SDValue LHS = Cond.getOperand(0);
9921     SDValue RHS = Cond.getOperand(1);
9922     unsigned X86Opcode;
9923     unsigned X86Cond;
9924     SDVTList VTs;
9925     switch (CondOpcode) {
9926     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9927     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9928     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9929     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9930     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9931     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9932     default: llvm_unreachable("unexpected overflowing operator");
9933     }
9934     if (CondOpcode == ISD::UMULO)
9935       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9936                           MVT::i32);
9937     else
9938       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9939
9940     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9941
9942     if (CondOpcode == ISD::UMULO)
9943       Cond = X86Op.getValue(2);
9944     else
9945       Cond = X86Op.getValue(1);
9946
9947     CC = DAG.getConstant(X86Cond, MVT::i8);
9948     addTest = false;
9949   }
9950
9951   if (addTest) {
9952     // Look pass the truncate if the high bits are known zero.
9953     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9954         Cond = Cond.getOperand(0);
9955
9956     // We know the result of AND is compared against zero. Try to match
9957     // it to BT.
9958     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9959       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9960       if (NewSetCC.getNode()) {
9961         CC = NewSetCC.getOperand(0);
9962         Cond = NewSetCC.getOperand(1);
9963         addTest = false;
9964       }
9965     }
9966   }
9967
9968   if (addTest) {
9969     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9970     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9971   }
9972
9973   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9974   // a <  b ?  0 : -1 -> RES = setcc_carry
9975   // a >= b ? -1 :  0 -> RES = setcc_carry
9976   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9977   if (Cond.getOpcode() == X86ISD::SUB) {
9978     Cond = ConvertCmpIfNecessary(Cond, DAG);
9979     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9980
9981     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9982         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9983       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9984                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9985       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9986         return DAG.getNOT(DL, Res, Res.getValueType());
9987       return Res;
9988     }
9989   }
9990
9991   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9992   // widen the cmov and push the truncate through. This avoids introducing a new
9993   // branch during isel and doesn't add any extensions.
9994   if (Op.getValueType() == MVT::i8 &&
9995       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9996     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9997     if (T1.getValueType() == T2.getValueType() &&
9998         // Blacklist CopyFromReg to avoid partial register stalls.
9999         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10000       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10001       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10002       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10003     }
10004   }
10005
10006   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10007   // condition is true.
10008   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10009   SDValue Ops[] = { Op2, Op1, CC, Cond };
10010   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10011 }
10012
10013 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10014                                             SelectionDAG &DAG) const {
10015   MVT VT = Op->getValueType(0).getSimpleVT();
10016   SDValue In = Op->getOperand(0);
10017   MVT InVT = In.getValueType().getSimpleVT();
10018   SDLoc dl(Op);
10019
10020   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10021       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10022     return SDValue();
10023
10024   if (Subtarget->hasInt256())
10025     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10026
10027   // Optimize vectors in AVX mode
10028   // Sign extend  v8i16 to v8i32 and
10029   //              v4i32 to v4i64
10030   //
10031   // Divide input vector into two parts
10032   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10033   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10034   // concat the vectors to original VT
10035
10036   unsigned NumElems = InVT.getVectorNumElements();
10037   SDValue Undef = DAG.getUNDEF(InVT);
10038
10039   SmallVector<int,8> ShufMask1(NumElems, -1);
10040   for (unsigned i = 0; i != NumElems/2; ++i)
10041     ShufMask1[i] = i;
10042
10043   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10044
10045   SmallVector<int,8> ShufMask2(NumElems, -1);
10046   for (unsigned i = 0; i != NumElems/2; ++i)
10047     ShufMask2[i] = i + NumElems/2;
10048
10049   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10050
10051   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10052                                 VT.getVectorNumElements()/2);
10053
10054   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10055   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10056
10057   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10058 }
10059
10060 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10061 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10062 // from the AND / OR.
10063 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10064   Opc = Op.getOpcode();
10065   if (Opc != ISD::OR && Opc != ISD::AND)
10066     return false;
10067   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10068           Op.getOperand(0).hasOneUse() &&
10069           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10070           Op.getOperand(1).hasOneUse());
10071 }
10072
10073 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10074 // 1 and that the SETCC node has a single use.
10075 static bool isXor1OfSetCC(SDValue Op) {
10076   if (Op.getOpcode() != ISD::XOR)
10077     return false;
10078   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10079   if (N1C && N1C->getAPIntValue() == 1) {
10080     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10081       Op.getOperand(0).hasOneUse();
10082   }
10083   return false;
10084 }
10085
10086 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10087   bool addTest = true;
10088   SDValue Chain = Op.getOperand(0);
10089   SDValue Cond  = Op.getOperand(1);
10090   SDValue Dest  = Op.getOperand(2);
10091   SDLoc dl(Op);
10092   SDValue CC;
10093   bool Inverted = false;
10094
10095   if (Cond.getOpcode() == ISD::SETCC) {
10096     // Check for setcc([su]{add,sub,mul}o == 0).
10097     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10098         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10099         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10100         Cond.getOperand(0).getResNo() == 1 &&
10101         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10102          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10103          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10104          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10105          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10106          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10107       Inverted = true;
10108       Cond = Cond.getOperand(0);
10109     } else {
10110       SDValue NewCond = LowerSETCC(Cond, DAG);
10111       if (NewCond.getNode())
10112         Cond = NewCond;
10113     }
10114   }
10115 #if 0
10116   // FIXME: LowerXALUO doesn't handle these!!
10117   else if (Cond.getOpcode() == X86ISD::ADD  ||
10118            Cond.getOpcode() == X86ISD::SUB  ||
10119            Cond.getOpcode() == X86ISD::SMUL ||
10120            Cond.getOpcode() == X86ISD::UMUL)
10121     Cond = LowerXALUO(Cond, DAG);
10122 #endif
10123
10124   // Look pass (and (setcc_carry (cmp ...)), 1).
10125   if (Cond.getOpcode() == ISD::AND &&
10126       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10127     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10128     if (C && C->getAPIntValue() == 1)
10129       Cond = Cond.getOperand(0);
10130   }
10131
10132   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10133   // setting operand in place of the X86ISD::SETCC.
10134   unsigned CondOpcode = Cond.getOpcode();
10135   if (CondOpcode == X86ISD::SETCC ||
10136       CondOpcode == X86ISD::SETCC_CARRY) {
10137     CC = Cond.getOperand(0);
10138
10139     SDValue Cmp = Cond.getOperand(1);
10140     unsigned Opc = Cmp.getOpcode();
10141     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10142     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10143       Cond = Cmp;
10144       addTest = false;
10145     } else {
10146       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10147       default: break;
10148       case X86::COND_O:
10149       case X86::COND_B:
10150         // These can only come from an arithmetic instruction with overflow,
10151         // e.g. SADDO, UADDO.
10152         Cond = Cond.getNode()->getOperand(1);
10153         addTest = false;
10154         break;
10155       }
10156     }
10157   }
10158   CondOpcode = Cond.getOpcode();
10159   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10160       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10161       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10162        Cond.getOperand(0).getValueType() != MVT::i8)) {
10163     SDValue LHS = Cond.getOperand(0);
10164     SDValue RHS = Cond.getOperand(1);
10165     unsigned X86Opcode;
10166     unsigned X86Cond;
10167     SDVTList VTs;
10168     switch (CondOpcode) {
10169     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10170     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10171     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10172     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10173     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10174     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10175     default: llvm_unreachable("unexpected overflowing operator");
10176     }
10177     if (Inverted)
10178       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10179     if (CondOpcode == ISD::UMULO)
10180       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10181                           MVT::i32);
10182     else
10183       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10184
10185     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10186
10187     if (CondOpcode == ISD::UMULO)
10188       Cond = X86Op.getValue(2);
10189     else
10190       Cond = X86Op.getValue(1);
10191
10192     CC = DAG.getConstant(X86Cond, MVT::i8);
10193     addTest = false;
10194   } else {
10195     unsigned CondOpc;
10196     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10197       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10198       if (CondOpc == ISD::OR) {
10199         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10200         // two branches instead of an explicit OR instruction with a
10201         // separate test.
10202         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10203             isX86LogicalCmp(Cmp)) {
10204           CC = Cond.getOperand(0).getOperand(0);
10205           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10206                               Chain, Dest, CC, Cmp);
10207           CC = Cond.getOperand(1).getOperand(0);
10208           Cond = Cmp;
10209           addTest = false;
10210         }
10211       } else { // ISD::AND
10212         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10213         // two branches instead of an explicit AND instruction with a
10214         // separate test. However, we only do this if this block doesn't
10215         // have a fall-through edge, because this requires an explicit
10216         // jmp when the condition is false.
10217         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10218             isX86LogicalCmp(Cmp) &&
10219             Op.getNode()->hasOneUse()) {
10220           X86::CondCode CCode =
10221             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10222           CCode = X86::GetOppositeBranchCondition(CCode);
10223           CC = DAG.getConstant(CCode, MVT::i8);
10224           SDNode *User = *Op.getNode()->use_begin();
10225           // Look for an unconditional branch following this conditional branch.
10226           // We need this because we need to reverse the successors in order
10227           // to implement FCMP_OEQ.
10228           if (User->getOpcode() == ISD::BR) {
10229             SDValue FalseBB = User->getOperand(1);
10230             SDNode *NewBR =
10231               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10232             assert(NewBR == User);
10233             (void)NewBR;
10234             Dest = FalseBB;
10235
10236             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10237                                 Chain, Dest, CC, Cmp);
10238             X86::CondCode CCode =
10239               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10240             CCode = X86::GetOppositeBranchCondition(CCode);
10241             CC = DAG.getConstant(CCode, MVT::i8);
10242             Cond = Cmp;
10243             addTest = false;
10244           }
10245         }
10246       }
10247     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10248       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10249       // It should be transformed during dag combiner except when the condition
10250       // is set by a arithmetics with overflow node.
10251       X86::CondCode CCode =
10252         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10253       CCode = X86::GetOppositeBranchCondition(CCode);
10254       CC = DAG.getConstant(CCode, MVT::i8);
10255       Cond = Cond.getOperand(0).getOperand(1);
10256       addTest = false;
10257     } else if (Cond.getOpcode() == ISD::SETCC &&
10258                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10259       // For FCMP_OEQ, we can emit
10260       // two branches instead of an explicit AND instruction with a
10261       // separate test. However, we only do this if this block doesn't
10262       // have a fall-through edge, because this requires an explicit
10263       // jmp when the condition is false.
10264       if (Op.getNode()->hasOneUse()) {
10265         SDNode *User = *Op.getNode()->use_begin();
10266         // Look for an unconditional branch following this conditional branch.
10267         // We need this because we need to reverse the successors in order
10268         // to implement FCMP_OEQ.
10269         if (User->getOpcode() == ISD::BR) {
10270           SDValue FalseBB = User->getOperand(1);
10271           SDNode *NewBR =
10272             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10273           assert(NewBR == User);
10274           (void)NewBR;
10275           Dest = FalseBB;
10276
10277           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10278                                     Cond.getOperand(0), Cond.getOperand(1));
10279           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10280           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10281           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10282                               Chain, Dest, CC, Cmp);
10283           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10284           Cond = Cmp;
10285           addTest = false;
10286         }
10287       }
10288     } else if (Cond.getOpcode() == ISD::SETCC &&
10289                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10290       // For FCMP_UNE, we can emit
10291       // two branches instead of an explicit AND instruction with a
10292       // separate test. However, we only do this if this block doesn't
10293       // have a fall-through edge, because this requires an explicit
10294       // jmp when the condition is false.
10295       if (Op.getNode()->hasOneUse()) {
10296         SDNode *User = *Op.getNode()->use_begin();
10297         // Look for an unconditional branch following this conditional branch.
10298         // We need this because we need to reverse the successors in order
10299         // to implement FCMP_UNE.
10300         if (User->getOpcode() == ISD::BR) {
10301           SDValue FalseBB = User->getOperand(1);
10302           SDNode *NewBR =
10303             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10304           assert(NewBR == User);
10305           (void)NewBR;
10306
10307           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10308                                     Cond.getOperand(0), Cond.getOperand(1));
10309           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10310           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10311           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10312                               Chain, Dest, CC, Cmp);
10313           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10314           Cond = Cmp;
10315           addTest = false;
10316           Dest = FalseBB;
10317         }
10318       }
10319     }
10320   }
10321
10322   if (addTest) {
10323     // Look pass the truncate if the high bits are known zero.
10324     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10325         Cond = Cond.getOperand(0);
10326
10327     // We know the result of AND is compared against zero. Try to match
10328     // it to BT.
10329     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10330       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10331       if (NewSetCC.getNode()) {
10332         CC = NewSetCC.getOperand(0);
10333         Cond = NewSetCC.getOperand(1);
10334         addTest = false;
10335       }
10336     }
10337   }
10338
10339   if (addTest) {
10340     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10341     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10342   }
10343   Cond = ConvertCmpIfNecessary(Cond, DAG);
10344   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10345                      Chain, Dest, CC, Cond);
10346 }
10347
10348 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10349 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10350 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10351 // that the guard pages used by the OS virtual memory manager are allocated in
10352 // correct sequence.
10353 SDValue
10354 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10355                                            SelectionDAG &DAG) const {
10356   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10357           getTargetMachine().Options.EnableSegmentedStacks) &&
10358          "This should be used only on Windows targets or when segmented stacks "
10359          "are being used");
10360   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10361   SDLoc dl(Op);
10362
10363   // Get the inputs.
10364   SDValue Chain = Op.getOperand(0);
10365   SDValue Size  = Op.getOperand(1);
10366   // FIXME: Ensure alignment here
10367
10368   bool Is64Bit = Subtarget->is64Bit();
10369   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10370
10371   if (getTargetMachine().Options.EnableSegmentedStacks) {
10372     MachineFunction &MF = DAG.getMachineFunction();
10373     MachineRegisterInfo &MRI = MF.getRegInfo();
10374
10375     if (Is64Bit) {
10376       // The 64 bit implementation of segmented stacks needs to clobber both r10
10377       // r11. This makes it impossible to use it along with nested parameters.
10378       const Function *F = MF.getFunction();
10379
10380       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10381            I != E; ++I)
10382         if (I->hasNestAttr())
10383           report_fatal_error("Cannot use segmented stacks with functions that "
10384                              "have nested arguments.");
10385     }
10386
10387     const TargetRegisterClass *AddrRegClass =
10388       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10389     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10390     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10391     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10392                                 DAG.getRegister(Vreg, SPTy));
10393     SDValue Ops1[2] = { Value, Chain };
10394     return DAG.getMergeValues(Ops1, 2, dl);
10395   } else {
10396     SDValue Flag;
10397     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10398
10399     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10400     Flag = Chain.getValue(1);
10401     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10402
10403     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10404     Flag = Chain.getValue(1);
10405
10406     const X86RegisterInfo *RegInfo =
10407       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10408     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10409                                SPTy).getValue(1);
10410
10411     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10412     return DAG.getMergeValues(Ops1, 2, dl);
10413   }
10414 }
10415
10416 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10417   MachineFunction &MF = DAG.getMachineFunction();
10418   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10419
10420   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10421   SDLoc DL(Op);
10422
10423   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10424     // vastart just stores the address of the VarArgsFrameIndex slot into the
10425     // memory location argument.
10426     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10427                                    getPointerTy());
10428     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10429                         MachinePointerInfo(SV), false, false, 0);
10430   }
10431
10432   // __va_list_tag:
10433   //   gp_offset         (0 - 6 * 8)
10434   //   fp_offset         (48 - 48 + 8 * 16)
10435   //   overflow_arg_area (point to parameters coming in memory).
10436   //   reg_save_area
10437   SmallVector<SDValue, 8> MemOps;
10438   SDValue FIN = Op.getOperand(1);
10439   // Store gp_offset
10440   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10441                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10442                                                MVT::i32),
10443                                FIN, MachinePointerInfo(SV), false, false, 0);
10444   MemOps.push_back(Store);
10445
10446   // Store fp_offset
10447   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10448                     FIN, DAG.getIntPtrConstant(4));
10449   Store = DAG.getStore(Op.getOperand(0), DL,
10450                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10451                                        MVT::i32),
10452                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10453   MemOps.push_back(Store);
10454
10455   // Store ptr to overflow_arg_area
10456   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10457                     FIN, DAG.getIntPtrConstant(4));
10458   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10459                                     getPointerTy());
10460   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10461                        MachinePointerInfo(SV, 8),
10462                        false, false, 0);
10463   MemOps.push_back(Store);
10464
10465   // Store ptr to reg_save_area.
10466   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10467                     FIN, DAG.getIntPtrConstant(8));
10468   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10469                                     getPointerTy());
10470   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10471                        MachinePointerInfo(SV, 16), false, false, 0);
10472   MemOps.push_back(Store);
10473   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10474                      &MemOps[0], MemOps.size());
10475 }
10476
10477 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10478   assert(Subtarget->is64Bit() &&
10479          "LowerVAARG only handles 64-bit va_arg!");
10480   assert((Subtarget->isTargetLinux() ||
10481           Subtarget->isTargetDarwin()) &&
10482           "Unhandled target in LowerVAARG");
10483   assert(Op.getNode()->getNumOperands() == 4);
10484   SDValue Chain = Op.getOperand(0);
10485   SDValue SrcPtr = Op.getOperand(1);
10486   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10487   unsigned Align = Op.getConstantOperandVal(3);
10488   SDLoc dl(Op);
10489
10490   EVT ArgVT = Op.getNode()->getValueType(0);
10491   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10492   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10493   uint8_t ArgMode;
10494
10495   // Decide which area this value should be read from.
10496   // TODO: Implement the AMD64 ABI in its entirety. This simple
10497   // selection mechanism works only for the basic types.
10498   if (ArgVT == MVT::f80) {
10499     llvm_unreachable("va_arg for f80 not yet implemented");
10500   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10501     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10502   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10503     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10504   } else {
10505     llvm_unreachable("Unhandled argument type in LowerVAARG");
10506   }
10507
10508   if (ArgMode == 2) {
10509     // Sanity Check: Make sure using fp_offset makes sense.
10510     assert(!getTargetMachine().Options.UseSoftFloat &&
10511            !(DAG.getMachineFunction()
10512                 .getFunction()->getAttributes()
10513                 .hasAttribute(AttributeSet::FunctionIndex,
10514                               Attribute::NoImplicitFloat)) &&
10515            Subtarget->hasSSE1());
10516   }
10517
10518   // Insert VAARG_64 node into the DAG
10519   // VAARG_64 returns two values: Variable Argument Address, Chain
10520   SmallVector<SDValue, 11> InstOps;
10521   InstOps.push_back(Chain);
10522   InstOps.push_back(SrcPtr);
10523   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10524   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10525   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10526   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10527   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10528                                           VTs, &InstOps[0], InstOps.size(),
10529                                           MVT::i64,
10530                                           MachinePointerInfo(SV),
10531                                           /*Align=*/0,
10532                                           /*Volatile=*/false,
10533                                           /*ReadMem=*/true,
10534                                           /*WriteMem=*/true);
10535   Chain = VAARG.getValue(1);
10536
10537   // Load the next argument and return it
10538   return DAG.getLoad(ArgVT, dl,
10539                      Chain,
10540                      VAARG,
10541                      MachinePointerInfo(),
10542                      false, false, false, 0);
10543 }
10544
10545 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10546                            SelectionDAG &DAG) {
10547   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10548   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10549   SDValue Chain = Op.getOperand(0);
10550   SDValue DstPtr = Op.getOperand(1);
10551   SDValue SrcPtr = Op.getOperand(2);
10552   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10553   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10554   SDLoc DL(Op);
10555
10556   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10557                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10558                        false,
10559                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10560 }
10561
10562 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10563 // may or may not be a constant. Takes immediate version of shift as input.
10564 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10565                                    SDValue SrcOp, SDValue ShAmt,
10566                                    SelectionDAG &DAG) {
10567   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10568
10569   if (isa<ConstantSDNode>(ShAmt)) {
10570     // Constant may be a TargetConstant. Use a regular constant.
10571     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10572     switch (Opc) {
10573       default: llvm_unreachable("Unknown target vector shift node");
10574       case X86ISD::VSHLI:
10575       case X86ISD::VSRLI:
10576       case X86ISD::VSRAI:
10577         return DAG.getNode(Opc, dl, VT, SrcOp,
10578                            DAG.getConstant(ShiftAmt, MVT::i32));
10579     }
10580   }
10581
10582   // Change opcode to non-immediate version
10583   switch (Opc) {
10584     default: llvm_unreachable("Unknown target vector shift node");
10585     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10586     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10587     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10588   }
10589
10590   // Need to build a vector containing shift amount
10591   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10592   SDValue ShOps[4];
10593   ShOps[0] = ShAmt;
10594   ShOps[1] = DAG.getConstant(0, MVT::i32);
10595   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10596   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10597
10598   // The return type has to be a 128-bit type with the same element
10599   // type as the input type.
10600   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10601   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10602
10603   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10604   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10605 }
10606
10607 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10608   SDLoc dl(Op);
10609   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10610   switch (IntNo) {
10611   default: return SDValue();    // Don't custom lower most intrinsics.
10612   // Comparison intrinsics.
10613   case Intrinsic::x86_sse_comieq_ss:
10614   case Intrinsic::x86_sse_comilt_ss:
10615   case Intrinsic::x86_sse_comile_ss:
10616   case Intrinsic::x86_sse_comigt_ss:
10617   case Intrinsic::x86_sse_comige_ss:
10618   case Intrinsic::x86_sse_comineq_ss:
10619   case Intrinsic::x86_sse_ucomieq_ss:
10620   case Intrinsic::x86_sse_ucomilt_ss:
10621   case Intrinsic::x86_sse_ucomile_ss:
10622   case Intrinsic::x86_sse_ucomigt_ss:
10623   case Intrinsic::x86_sse_ucomige_ss:
10624   case Intrinsic::x86_sse_ucomineq_ss:
10625   case Intrinsic::x86_sse2_comieq_sd:
10626   case Intrinsic::x86_sse2_comilt_sd:
10627   case Intrinsic::x86_sse2_comile_sd:
10628   case Intrinsic::x86_sse2_comigt_sd:
10629   case Intrinsic::x86_sse2_comige_sd:
10630   case Intrinsic::x86_sse2_comineq_sd:
10631   case Intrinsic::x86_sse2_ucomieq_sd:
10632   case Intrinsic::x86_sse2_ucomilt_sd:
10633   case Intrinsic::x86_sse2_ucomile_sd:
10634   case Intrinsic::x86_sse2_ucomigt_sd:
10635   case Intrinsic::x86_sse2_ucomige_sd:
10636   case Intrinsic::x86_sse2_ucomineq_sd: {
10637     unsigned Opc;
10638     ISD::CondCode CC;
10639     switch (IntNo) {
10640     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10641     case Intrinsic::x86_sse_comieq_ss:
10642     case Intrinsic::x86_sse2_comieq_sd:
10643       Opc = X86ISD::COMI;
10644       CC = ISD::SETEQ;
10645       break;
10646     case Intrinsic::x86_sse_comilt_ss:
10647     case Intrinsic::x86_sse2_comilt_sd:
10648       Opc = X86ISD::COMI;
10649       CC = ISD::SETLT;
10650       break;
10651     case Intrinsic::x86_sse_comile_ss:
10652     case Intrinsic::x86_sse2_comile_sd:
10653       Opc = X86ISD::COMI;
10654       CC = ISD::SETLE;
10655       break;
10656     case Intrinsic::x86_sse_comigt_ss:
10657     case Intrinsic::x86_sse2_comigt_sd:
10658       Opc = X86ISD::COMI;
10659       CC = ISD::SETGT;
10660       break;
10661     case Intrinsic::x86_sse_comige_ss:
10662     case Intrinsic::x86_sse2_comige_sd:
10663       Opc = X86ISD::COMI;
10664       CC = ISD::SETGE;
10665       break;
10666     case Intrinsic::x86_sse_comineq_ss:
10667     case Intrinsic::x86_sse2_comineq_sd:
10668       Opc = X86ISD::COMI;
10669       CC = ISD::SETNE;
10670       break;
10671     case Intrinsic::x86_sse_ucomieq_ss:
10672     case Intrinsic::x86_sse2_ucomieq_sd:
10673       Opc = X86ISD::UCOMI;
10674       CC = ISD::SETEQ;
10675       break;
10676     case Intrinsic::x86_sse_ucomilt_ss:
10677     case Intrinsic::x86_sse2_ucomilt_sd:
10678       Opc = X86ISD::UCOMI;
10679       CC = ISD::SETLT;
10680       break;
10681     case Intrinsic::x86_sse_ucomile_ss:
10682     case Intrinsic::x86_sse2_ucomile_sd:
10683       Opc = X86ISD::UCOMI;
10684       CC = ISD::SETLE;
10685       break;
10686     case Intrinsic::x86_sse_ucomigt_ss:
10687     case Intrinsic::x86_sse2_ucomigt_sd:
10688       Opc = X86ISD::UCOMI;
10689       CC = ISD::SETGT;
10690       break;
10691     case Intrinsic::x86_sse_ucomige_ss:
10692     case Intrinsic::x86_sse2_ucomige_sd:
10693       Opc = X86ISD::UCOMI;
10694       CC = ISD::SETGE;
10695       break;
10696     case Intrinsic::x86_sse_ucomineq_ss:
10697     case Intrinsic::x86_sse2_ucomineq_sd:
10698       Opc = X86ISD::UCOMI;
10699       CC = ISD::SETNE;
10700       break;
10701     }
10702
10703     SDValue LHS = Op.getOperand(1);
10704     SDValue RHS = Op.getOperand(2);
10705     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10706     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10707     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10708     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10709                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10710     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10711   }
10712
10713   // Arithmetic intrinsics.
10714   case Intrinsic::x86_sse2_pmulu_dq:
10715   case Intrinsic::x86_avx2_pmulu_dq:
10716     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10717                        Op.getOperand(1), Op.getOperand(2));
10718
10719   // SSE2/AVX2 sub with unsigned saturation intrinsics
10720   case Intrinsic::x86_sse2_psubus_b:
10721   case Intrinsic::x86_sse2_psubus_w:
10722   case Intrinsic::x86_avx2_psubus_b:
10723   case Intrinsic::x86_avx2_psubus_w:
10724     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10725                        Op.getOperand(1), Op.getOperand(2));
10726
10727   // SSE3/AVX horizontal add/sub intrinsics
10728   case Intrinsic::x86_sse3_hadd_ps:
10729   case Intrinsic::x86_sse3_hadd_pd:
10730   case Intrinsic::x86_avx_hadd_ps_256:
10731   case Intrinsic::x86_avx_hadd_pd_256:
10732   case Intrinsic::x86_sse3_hsub_ps:
10733   case Intrinsic::x86_sse3_hsub_pd:
10734   case Intrinsic::x86_avx_hsub_ps_256:
10735   case Intrinsic::x86_avx_hsub_pd_256:
10736   case Intrinsic::x86_ssse3_phadd_w_128:
10737   case Intrinsic::x86_ssse3_phadd_d_128:
10738   case Intrinsic::x86_avx2_phadd_w:
10739   case Intrinsic::x86_avx2_phadd_d:
10740   case Intrinsic::x86_ssse3_phsub_w_128:
10741   case Intrinsic::x86_ssse3_phsub_d_128:
10742   case Intrinsic::x86_avx2_phsub_w:
10743   case Intrinsic::x86_avx2_phsub_d: {
10744     unsigned Opcode;
10745     switch (IntNo) {
10746     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10747     case Intrinsic::x86_sse3_hadd_ps:
10748     case Intrinsic::x86_sse3_hadd_pd:
10749     case Intrinsic::x86_avx_hadd_ps_256:
10750     case Intrinsic::x86_avx_hadd_pd_256:
10751       Opcode = X86ISD::FHADD;
10752       break;
10753     case Intrinsic::x86_sse3_hsub_ps:
10754     case Intrinsic::x86_sse3_hsub_pd:
10755     case Intrinsic::x86_avx_hsub_ps_256:
10756     case Intrinsic::x86_avx_hsub_pd_256:
10757       Opcode = X86ISD::FHSUB;
10758       break;
10759     case Intrinsic::x86_ssse3_phadd_w_128:
10760     case Intrinsic::x86_ssse3_phadd_d_128:
10761     case Intrinsic::x86_avx2_phadd_w:
10762     case Intrinsic::x86_avx2_phadd_d:
10763       Opcode = X86ISD::HADD;
10764       break;
10765     case Intrinsic::x86_ssse3_phsub_w_128:
10766     case Intrinsic::x86_ssse3_phsub_d_128:
10767     case Intrinsic::x86_avx2_phsub_w:
10768     case Intrinsic::x86_avx2_phsub_d:
10769       Opcode = X86ISD::HSUB;
10770       break;
10771     }
10772     return DAG.getNode(Opcode, dl, Op.getValueType(),
10773                        Op.getOperand(1), Op.getOperand(2));
10774   }
10775
10776   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10777   case Intrinsic::x86_sse2_pmaxu_b:
10778   case Intrinsic::x86_sse41_pmaxuw:
10779   case Intrinsic::x86_sse41_pmaxud:
10780   case Intrinsic::x86_avx2_pmaxu_b:
10781   case Intrinsic::x86_avx2_pmaxu_w:
10782   case Intrinsic::x86_avx2_pmaxu_d:
10783   case Intrinsic::x86_sse2_pminu_b:
10784   case Intrinsic::x86_sse41_pminuw:
10785   case Intrinsic::x86_sse41_pminud:
10786   case Intrinsic::x86_avx2_pminu_b:
10787   case Intrinsic::x86_avx2_pminu_w:
10788   case Intrinsic::x86_avx2_pminu_d:
10789   case Intrinsic::x86_sse41_pmaxsb:
10790   case Intrinsic::x86_sse2_pmaxs_w:
10791   case Intrinsic::x86_sse41_pmaxsd:
10792   case Intrinsic::x86_avx2_pmaxs_b:
10793   case Intrinsic::x86_avx2_pmaxs_w:
10794   case Intrinsic::x86_avx2_pmaxs_d:
10795   case Intrinsic::x86_sse41_pminsb:
10796   case Intrinsic::x86_sse2_pmins_w:
10797   case Intrinsic::x86_sse41_pminsd:
10798   case Intrinsic::x86_avx2_pmins_b:
10799   case Intrinsic::x86_avx2_pmins_w:
10800   case Intrinsic::x86_avx2_pmins_d: {
10801     unsigned Opcode;
10802     switch (IntNo) {
10803     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10804     case Intrinsic::x86_sse2_pmaxu_b:
10805     case Intrinsic::x86_sse41_pmaxuw:
10806     case Intrinsic::x86_sse41_pmaxud:
10807     case Intrinsic::x86_avx2_pmaxu_b:
10808     case Intrinsic::x86_avx2_pmaxu_w:
10809     case Intrinsic::x86_avx2_pmaxu_d:
10810       Opcode = X86ISD::UMAX;
10811       break;
10812     case Intrinsic::x86_sse2_pminu_b:
10813     case Intrinsic::x86_sse41_pminuw:
10814     case Intrinsic::x86_sse41_pminud:
10815     case Intrinsic::x86_avx2_pminu_b:
10816     case Intrinsic::x86_avx2_pminu_w:
10817     case Intrinsic::x86_avx2_pminu_d:
10818       Opcode = X86ISD::UMIN;
10819       break;
10820     case Intrinsic::x86_sse41_pmaxsb:
10821     case Intrinsic::x86_sse2_pmaxs_w:
10822     case Intrinsic::x86_sse41_pmaxsd:
10823     case Intrinsic::x86_avx2_pmaxs_b:
10824     case Intrinsic::x86_avx2_pmaxs_w:
10825     case Intrinsic::x86_avx2_pmaxs_d:
10826       Opcode = X86ISD::SMAX;
10827       break;
10828     case Intrinsic::x86_sse41_pminsb:
10829     case Intrinsic::x86_sse2_pmins_w:
10830     case Intrinsic::x86_sse41_pminsd:
10831     case Intrinsic::x86_avx2_pmins_b:
10832     case Intrinsic::x86_avx2_pmins_w:
10833     case Intrinsic::x86_avx2_pmins_d:
10834       Opcode = X86ISD::SMIN;
10835       break;
10836     }
10837     return DAG.getNode(Opcode, dl, Op.getValueType(),
10838                        Op.getOperand(1), Op.getOperand(2));
10839   }
10840
10841   // SSE/SSE2/AVX floating point max/min intrinsics.
10842   case Intrinsic::x86_sse_max_ps:
10843   case Intrinsic::x86_sse2_max_pd:
10844   case Intrinsic::x86_avx_max_ps_256:
10845   case Intrinsic::x86_avx_max_pd_256:
10846   case Intrinsic::x86_sse_min_ps:
10847   case Intrinsic::x86_sse2_min_pd:
10848   case Intrinsic::x86_avx_min_ps_256:
10849   case Intrinsic::x86_avx_min_pd_256: {
10850     unsigned Opcode;
10851     switch (IntNo) {
10852     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10853     case Intrinsic::x86_sse_max_ps:
10854     case Intrinsic::x86_sse2_max_pd:
10855     case Intrinsic::x86_avx_max_ps_256:
10856     case Intrinsic::x86_avx_max_pd_256:
10857       Opcode = X86ISD::FMAX;
10858       break;
10859     case Intrinsic::x86_sse_min_ps:
10860     case Intrinsic::x86_sse2_min_pd:
10861     case Intrinsic::x86_avx_min_ps_256:
10862     case Intrinsic::x86_avx_min_pd_256:
10863       Opcode = X86ISD::FMIN;
10864       break;
10865     }
10866     return DAG.getNode(Opcode, dl, Op.getValueType(),
10867                        Op.getOperand(1), Op.getOperand(2));
10868   }
10869
10870   // AVX2 variable shift intrinsics
10871   case Intrinsic::x86_avx2_psllv_d:
10872   case Intrinsic::x86_avx2_psllv_q:
10873   case Intrinsic::x86_avx2_psllv_d_256:
10874   case Intrinsic::x86_avx2_psllv_q_256:
10875   case Intrinsic::x86_avx2_psrlv_d:
10876   case Intrinsic::x86_avx2_psrlv_q:
10877   case Intrinsic::x86_avx2_psrlv_d_256:
10878   case Intrinsic::x86_avx2_psrlv_q_256:
10879   case Intrinsic::x86_avx2_psrav_d:
10880   case Intrinsic::x86_avx2_psrav_d_256: {
10881     unsigned Opcode;
10882     switch (IntNo) {
10883     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10884     case Intrinsic::x86_avx2_psllv_d:
10885     case Intrinsic::x86_avx2_psllv_q:
10886     case Intrinsic::x86_avx2_psllv_d_256:
10887     case Intrinsic::x86_avx2_psllv_q_256:
10888       Opcode = ISD::SHL;
10889       break;
10890     case Intrinsic::x86_avx2_psrlv_d:
10891     case Intrinsic::x86_avx2_psrlv_q:
10892     case Intrinsic::x86_avx2_psrlv_d_256:
10893     case Intrinsic::x86_avx2_psrlv_q_256:
10894       Opcode = ISD::SRL;
10895       break;
10896     case Intrinsic::x86_avx2_psrav_d:
10897     case Intrinsic::x86_avx2_psrav_d_256:
10898       Opcode = ISD::SRA;
10899       break;
10900     }
10901     return DAG.getNode(Opcode, dl, Op.getValueType(),
10902                        Op.getOperand(1), Op.getOperand(2));
10903   }
10904
10905   case Intrinsic::x86_ssse3_pshuf_b_128:
10906   case Intrinsic::x86_avx2_pshuf_b:
10907     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10908                        Op.getOperand(1), Op.getOperand(2));
10909
10910   case Intrinsic::x86_ssse3_psign_b_128:
10911   case Intrinsic::x86_ssse3_psign_w_128:
10912   case Intrinsic::x86_ssse3_psign_d_128:
10913   case Intrinsic::x86_avx2_psign_b:
10914   case Intrinsic::x86_avx2_psign_w:
10915   case Intrinsic::x86_avx2_psign_d:
10916     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10917                        Op.getOperand(1), Op.getOperand(2));
10918
10919   case Intrinsic::x86_sse41_insertps:
10920     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10921                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10922
10923   case Intrinsic::x86_avx_vperm2f128_ps_256:
10924   case Intrinsic::x86_avx_vperm2f128_pd_256:
10925   case Intrinsic::x86_avx_vperm2f128_si_256:
10926   case Intrinsic::x86_avx2_vperm2i128:
10927     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10928                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10929
10930   case Intrinsic::x86_avx2_permd:
10931   case Intrinsic::x86_avx2_permps:
10932     // Operands intentionally swapped. Mask is last operand to intrinsic,
10933     // but second operand for node/intruction.
10934     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10935                        Op.getOperand(2), Op.getOperand(1));
10936
10937   case Intrinsic::x86_sse_sqrt_ps:
10938   case Intrinsic::x86_sse2_sqrt_pd:
10939   case Intrinsic::x86_avx_sqrt_ps_256:
10940   case Intrinsic::x86_avx_sqrt_pd_256:
10941     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10942
10943   // ptest and testp intrinsics. The intrinsic these come from are designed to
10944   // return an integer value, not just an instruction so lower it to the ptest
10945   // or testp pattern and a setcc for the result.
10946   case Intrinsic::x86_sse41_ptestz:
10947   case Intrinsic::x86_sse41_ptestc:
10948   case Intrinsic::x86_sse41_ptestnzc:
10949   case Intrinsic::x86_avx_ptestz_256:
10950   case Intrinsic::x86_avx_ptestc_256:
10951   case Intrinsic::x86_avx_ptestnzc_256:
10952   case Intrinsic::x86_avx_vtestz_ps:
10953   case Intrinsic::x86_avx_vtestc_ps:
10954   case Intrinsic::x86_avx_vtestnzc_ps:
10955   case Intrinsic::x86_avx_vtestz_pd:
10956   case Intrinsic::x86_avx_vtestc_pd:
10957   case Intrinsic::x86_avx_vtestnzc_pd:
10958   case Intrinsic::x86_avx_vtestz_ps_256:
10959   case Intrinsic::x86_avx_vtestc_ps_256:
10960   case Intrinsic::x86_avx_vtestnzc_ps_256:
10961   case Intrinsic::x86_avx_vtestz_pd_256:
10962   case Intrinsic::x86_avx_vtestc_pd_256:
10963   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10964     bool IsTestPacked = false;
10965     unsigned X86CC;
10966     switch (IntNo) {
10967     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10968     case Intrinsic::x86_avx_vtestz_ps:
10969     case Intrinsic::x86_avx_vtestz_pd:
10970     case Intrinsic::x86_avx_vtestz_ps_256:
10971     case Intrinsic::x86_avx_vtestz_pd_256:
10972       IsTestPacked = true; // Fallthrough
10973     case Intrinsic::x86_sse41_ptestz:
10974     case Intrinsic::x86_avx_ptestz_256:
10975       // ZF = 1
10976       X86CC = X86::COND_E;
10977       break;
10978     case Intrinsic::x86_avx_vtestc_ps:
10979     case Intrinsic::x86_avx_vtestc_pd:
10980     case Intrinsic::x86_avx_vtestc_ps_256:
10981     case Intrinsic::x86_avx_vtestc_pd_256:
10982       IsTestPacked = true; // Fallthrough
10983     case Intrinsic::x86_sse41_ptestc:
10984     case Intrinsic::x86_avx_ptestc_256:
10985       // CF = 1
10986       X86CC = X86::COND_B;
10987       break;
10988     case Intrinsic::x86_avx_vtestnzc_ps:
10989     case Intrinsic::x86_avx_vtestnzc_pd:
10990     case Intrinsic::x86_avx_vtestnzc_ps_256:
10991     case Intrinsic::x86_avx_vtestnzc_pd_256:
10992       IsTestPacked = true; // Fallthrough
10993     case Intrinsic::x86_sse41_ptestnzc:
10994     case Intrinsic::x86_avx_ptestnzc_256:
10995       // ZF and CF = 0
10996       X86CC = X86::COND_A;
10997       break;
10998     }
10999
11000     SDValue LHS = Op.getOperand(1);
11001     SDValue RHS = Op.getOperand(2);
11002     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11003     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11004     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11005     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11006     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11007   }
11008
11009   // SSE/AVX shift intrinsics
11010   case Intrinsic::x86_sse2_psll_w:
11011   case Intrinsic::x86_sse2_psll_d:
11012   case Intrinsic::x86_sse2_psll_q:
11013   case Intrinsic::x86_avx2_psll_w:
11014   case Intrinsic::x86_avx2_psll_d:
11015   case Intrinsic::x86_avx2_psll_q:
11016   case Intrinsic::x86_sse2_psrl_w:
11017   case Intrinsic::x86_sse2_psrl_d:
11018   case Intrinsic::x86_sse2_psrl_q:
11019   case Intrinsic::x86_avx2_psrl_w:
11020   case Intrinsic::x86_avx2_psrl_d:
11021   case Intrinsic::x86_avx2_psrl_q:
11022   case Intrinsic::x86_sse2_psra_w:
11023   case Intrinsic::x86_sse2_psra_d:
11024   case Intrinsic::x86_avx2_psra_w:
11025   case Intrinsic::x86_avx2_psra_d: {
11026     unsigned Opcode;
11027     switch (IntNo) {
11028     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11029     case Intrinsic::x86_sse2_psll_w:
11030     case Intrinsic::x86_sse2_psll_d:
11031     case Intrinsic::x86_sse2_psll_q:
11032     case Intrinsic::x86_avx2_psll_w:
11033     case Intrinsic::x86_avx2_psll_d:
11034     case Intrinsic::x86_avx2_psll_q:
11035       Opcode = X86ISD::VSHL;
11036       break;
11037     case Intrinsic::x86_sse2_psrl_w:
11038     case Intrinsic::x86_sse2_psrl_d:
11039     case Intrinsic::x86_sse2_psrl_q:
11040     case Intrinsic::x86_avx2_psrl_w:
11041     case Intrinsic::x86_avx2_psrl_d:
11042     case Intrinsic::x86_avx2_psrl_q:
11043       Opcode = X86ISD::VSRL;
11044       break;
11045     case Intrinsic::x86_sse2_psra_w:
11046     case Intrinsic::x86_sse2_psra_d:
11047     case Intrinsic::x86_avx2_psra_w:
11048     case Intrinsic::x86_avx2_psra_d:
11049       Opcode = X86ISD::VSRA;
11050       break;
11051     }
11052     return DAG.getNode(Opcode, dl, Op.getValueType(),
11053                        Op.getOperand(1), Op.getOperand(2));
11054   }
11055
11056   // SSE/AVX immediate shift intrinsics
11057   case Intrinsic::x86_sse2_pslli_w:
11058   case Intrinsic::x86_sse2_pslli_d:
11059   case Intrinsic::x86_sse2_pslli_q:
11060   case Intrinsic::x86_avx2_pslli_w:
11061   case Intrinsic::x86_avx2_pslli_d:
11062   case Intrinsic::x86_avx2_pslli_q:
11063   case Intrinsic::x86_sse2_psrli_w:
11064   case Intrinsic::x86_sse2_psrli_d:
11065   case Intrinsic::x86_sse2_psrli_q:
11066   case Intrinsic::x86_avx2_psrli_w:
11067   case Intrinsic::x86_avx2_psrli_d:
11068   case Intrinsic::x86_avx2_psrli_q:
11069   case Intrinsic::x86_sse2_psrai_w:
11070   case Intrinsic::x86_sse2_psrai_d:
11071   case Intrinsic::x86_avx2_psrai_w:
11072   case Intrinsic::x86_avx2_psrai_d: {
11073     unsigned Opcode;
11074     switch (IntNo) {
11075     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11076     case Intrinsic::x86_sse2_pslli_w:
11077     case Intrinsic::x86_sse2_pslli_d:
11078     case Intrinsic::x86_sse2_pslli_q:
11079     case Intrinsic::x86_avx2_pslli_w:
11080     case Intrinsic::x86_avx2_pslli_d:
11081     case Intrinsic::x86_avx2_pslli_q:
11082       Opcode = X86ISD::VSHLI;
11083       break;
11084     case Intrinsic::x86_sse2_psrli_w:
11085     case Intrinsic::x86_sse2_psrli_d:
11086     case Intrinsic::x86_sse2_psrli_q:
11087     case Intrinsic::x86_avx2_psrli_w:
11088     case Intrinsic::x86_avx2_psrli_d:
11089     case Intrinsic::x86_avx2_psrli_q:
11090       Opcode = X86ISD::VSRLI;
11091       break;
11092     case Intrinsic::x86_sse2_psrai_w:
11093     case Intrinsic::x86_sse2_psrai_d:
11094     case Intrinsic::x86_avx2_psrai_w:
11095     case Intrinsic::x86_avx2_psrai_d:
11096       Opcode = X86ISD::VSRAI;
11097       break;
11098     }
11099     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11100                                Op.getOperand(1), Op.getOperand(2), DAG);
11101   }
11102
11103   case Intrinsic::x86_sse42_pcmpistria128:
11104   case Intrinsic::x86_sse42_pcmpestria128:
11105   case Intrinsic::x86_sse42_pcmpistric128:
11106   case Intrinsic::x86_sse42_pcmpestric128:
11107   case Intrinsic::x86_sse42_pcmpistrio128:
11108   case Intrinsic::x86_sse42_pcmpestrio128:
11109   case Intrinsic::x86_sse42_pcmpistris128:
11110   case Intrinsic::x86_sse42_pcmpestris128:
11111   case Intrinsic::x86_sse42_pcmpistriz128:
11112   case Intrinsic::x86_sse42_pcmpestriz128: {
11113     unsigned Opcode;
11114     unsigned X86CC;
11115     switch (IntNo) {
11116     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11117     case Intrinsic::x86_sse42_pcmpistria128:
11118       Opcode = X86ISD::PCMPISTRI;
11119       X86CC = X86::COND_A;
11120       break;
11121     case Intrinsic::x86_sse42_pcmpestria128:
11122       Opcode = X86ISD::PCMPESTRI;
11123       X86CC = X86::COND_A;
11124       break;
11125     case Intrinsic::x86_sse42_pcmpistric128:
11126       Opcode = X86ISD::PCMPISTRI;
11127       X86CC = X86::COND_B;
11128       break;
11129     case Intrinsic::x86_sse42_pcmpestric128:
11130       Opcode = X86ISD::PCMPESTRI;
11131       X86CC = X86::COND_B;
11132       break;
11133     case Intrinsic::x86_sse42_pcmpistrio128:
11134       Opcode = X86ISD::PCMPISTRI;
11135       X86CC = X86::COND_O;
11136       break;
11137     case Intrinsic::x86_sse42_pcmpestrio128:
11138       Opcode = X86ISD::PCMPESTRI;
11139       X86CC = X86::COND_O;
11140       break;
11141     case Intrinsic::x86_sse42_pcmpistris128:
11142       Opcode = X86ISD::PCMPISTRI;
11143       X86CC = X86::COND_S;
11144       break;
11145     case Intrinsic::x86_sse42_pcmpestris128:
11146       Opcode = X86ISD::PCMPESTRI;
11147       X86CC = X86::COND_S;
11148       break;
11149     case Intrinsic::x86_sse42_pcmpistriz128:
11150       Opcode = X86ISD::PCMPISTRI;
11151       X86CC = X86::COND_E;
11152       break;
11153     case Intrinsic::x86_sse42_pcmpestriz128:
11154       Opcode = X86ISD::PCMPESTRI;
11155       X86CC = X86::COND_E;
11156       break;
11157     }
11158     SmallVector<SDValue, 5> NewOps;
11159     NewOps.append(Op->op_begin()+1, Op->op_end());
11160     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11161     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11162     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11163                                 DAG.getConstant(X86CC, MVT::i8),
11164                                 SDValue(PCMP.getNode(), 1));
11165     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11166   }
11167
11168   case Intrinsic::x86_sse42_pcmpistri128:
11169   case Intrinsic::x86_sse42_pcmpestri128: {
11170     unsigned Opcode;
11171     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11172       Opcode = X86ISD::PCMPISTRI;
11173     else
11174       Opcode = X86ISD::PCMPESTRI;
11175
11176     SmallVector<SDValue, 5> NewOps;
11177     NewOps.append(Op->op_begin()+1, Op->op_end());
11178     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11179     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11180   }
11181   case Intrinsic::x86_fma_vfmadd_ps:
11182   case Intrinsic::x86_fma_vfmadd_pd:
11183   case Intrinsic::x86_fma_vfmsub_ps:
11184   case Intrinsic::x86_fma_vfmsub_pd:
11185   case Intrinsic::x86_fma_vfnmadd_ps:
11186   case Intrinsic::x86_fma_vfnmadd_pd:
11187   case Intrinsic::x86_fma_vfnmsub_ps:
11188   case Intrinsic::x86_fma_vfnmsub_pd:
11189   case Intrinsic::x86_fma_vfmaddsub_ps:
11190   case Intrinsic::x86_fma_vfmaddsub_pd:
11191   case Intrinsic::x86_fma_vfmsubadd_ps:
11192   case Intrinsic::x86_fma_vfmsubadd_pd:
11193   case Intrinsic::x86_fma_vfmadd_ps_256:
11194   case Intrinsic::x86_fma_vfmadd_pd_256:
11195   case Intrinsic::x86_fma_vfmsub_ps_256:
11196   case Intrinsic::x86_fma_vfmsub_pd_256:
11197   case Intrinsic::x86_fma_vfnmadd_ps_256:
11198   case Intrinsic::x86_fma_vfnmadd_pd_256:
11199   case Intrinsic::x86_fma_vfnmsub_ps_256:
11200   case Intrinsic::x86_fma_vfnmsub_pd_256:
11201   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11202   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11203   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11204   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11205     unsigned Opc;
11206     switch (IntNo) {
11207     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11208     case Intrinsic::x86_fma_vfmadd_ps:
11209     case Intrinsic::x86_fma_vfmadd_pd:
11210     case Intrinsic::x86_fma_vfmadd_ps_256:
11211     case Intrinsic::x86_fma_vfmadd_pd_256:
11212       Opc = X86ISD::FMADD;
11213       break;
11214     case Intrinsic::x86_fma_vfmsub_ps:
11215     case Intrinsic::x86_fma_vfmsub_pd:
11216     case Intrinsic::x86_fma_vfmsub_ps_256:
11217     case Intrinsic::x86_fma_vfmsub_pd_256:
11218       Opc = X86ISD::FMSUB;
11219       break;
11220     case Intrinsic::x86_fma_vfnmadd_ps:
11221     case Intrinsic::x86_fma_vfnmadd_pd:
11222     case Intrinsic::x86_fma_vfnmadd_ps_256:
11223     case Intrinsic::x86_fma_vfnmadd_pd_256:
11224       Opc = X86ISD::FNMADD;
11225       break;
11226     case Intrinsic::x86_fma_vfnmsub_ps:
11227     case Intrinsic::x86_fma_vfnmsub_pd:
11228     case Intrinsic::x86_fma_vfnmsub_ps_256:
11229     case Intrinsic::x86_fma_vfnmsub_pd_256:
11230       Opc = X86ISD::FNMSUB;
11231       break;
11232     case Intrinsic::x86_fma_vfmaddsub_ps:
11233     case Intrinsic::x86_fma_vfmaddsub_pd:
11234     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11235     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11236       Opc = X86ISD::FMADDSUB;
11237       break;
11238     case Intrinsic::x86_fma_vfmsubadd_ps:
11239     case Intrinsic::x86_fma_vfmsubadd_pd:
11240     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11241     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11242       Opc = X86ISD::FMSUBADD;
11243       break;
11244     }
11245
11246     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11247                        Op.getOperand(2), Op.getOperand(3));
11248   }
11249   }
11250 }
11251
11252 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11253   SDLoc dl(Op);
11254   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11255   switch (IntNo) {
11256   default: return SDValue();    // Don't custom lower most intrinsics.
11257
11258   // RDRAND/RDSEED intrinsics.
11259   case Intrinsic::x86_rdrand_16:
11260   case Intrinsic::x86_rdrand_32:
11261   case Intrinsic::x86_rdrand_64:
11262   case Intrinsic::x86_rdseed_16:
11263   case Intrinsic::x86_rdseed_32:
11264   case Intrinsic::x86_rdseed_64: {
11265     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11266                        IntNo == Intrinsic::x86_rdseed_32 ||
11267                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11268                                                             X86ISD::RDRAND;
11269     // Emit the node with the right value type.
11270     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11271     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11272
11273     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11274     // Otherwise return the value from Rand, which is always 0, casted to i32.
11275     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11276                       DAG.getConstant(1, Op->getValueType(1)),
11277                       DAG.getConstant(X86::COND_B, MVT::i32),
11278                       SDValue(Result.getNode(), 1) };
11279     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11280                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11281                                   Ops, array_lengthof(Ops));
11282
11283     // Return { result, isValid, chain }.
11284     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11285                        SDValue(Result.getNode(), 2));
11286   }
11287
11288   // XTEST intrinsics.
11289   case Intrinsic::x86_xtest: {
11290     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11291     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11292     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11293                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11294                                 InTrans);
11295     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11296     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11297                        Ret, SDValue(InTrans.getNode(), 1));
11298   }
11299   }
11300 }
11301
11302 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11303                                            SelectionDAG &DAG) const {
11304   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11305   MFI->setReturnAddressIsTaken(true);
11306
11307   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11308   SDLoc dl(Op);
11309   EVT PtrVT = getPointerTy();
11310
11311   if (Depth > 0) {
11312     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11313     const X86RegisterInfo *RegInfo =
11314       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11315     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11316     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11317                        DAG.getNode(ISD::ADD, dl, PtrVT,
11318                                    FrameAddr, Offset),
11319                        MachinePointerInfo(), false, false, false, 0);
11320   }
11321
11322   // Just load the return address.
11323   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11324   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11325                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11326 }
11327
11328 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11329   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11330   MFI->setFrameAddressIsTaken(true);
11331
11332   EVT VT = Op.getValueType();
11333   SDLoc dl(Op);  // FIXME probably not meaningful
11334   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11335   const X86RegisterInfo *RegInfo =
11336     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11337   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11338   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11339           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11340          "Invalid Frame Register!");
11341   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11342   while (Depth--)
11343     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11344                             MachinePointerInfo(),
11345                             false, false, false, 0);
11346   return FrameAddr;
11347 }
11348
11349 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11350                                                      SelectionDAG &DAG) const {
11351   const X86RegisterInfo *RegInfo =
11352     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11353   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11354 }
11355
11356 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11357   SDValue Chain     = Op.getOperand(0);
11358   SDValue Offset    = Op.getOperand(1);
11359   SDValue Handler   = Op.getOperand(2);
11360   SDLoc dl      (Op);
11361
11362   EVT PtrVT = getPointerTy();
11363   const X86RegisterInfo *RegInfo =
11364     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11365   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11366   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11367           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11368          "Invalid Frame Register!");
11369   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11370   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11371
11372   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11373                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11374   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11375   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11376                        false, false, 0);
11377   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11378
11379   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11380                      DAG.getRegister(StoreAddrReg, PtrVT));
11381 }
11382
11383 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11384                                                SelectionDAG &DAG) const {
11385   SDLoc DL(Op);
11386   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11387                      DAG.getVTList(MVT::i32, MVT::Other),
11388                      Op.getOperand(0), Op.getOperand(1));
11389 }
11390
11391 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11392                                                 SelectionDAG &DAG) const {
11393   SDLoc DL(Op);
11394   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11395                      Op.getOperand(0), Op.getOperand(1));
11396 }
11397
11398 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11399   return Op.getOperand(0);
11400 }
11401
11402 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11403                                                 SelectionDAG &DAG) const {
11404   SDValue Root = Op.getOperand(0);
11405   SDValue Trmp = Op.getOperand(1); // trampoline
11406   SDValue FPtr = Op.getOperand(2); // nested function
11407   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11408   SDLoc dl (Op);
11409
11410   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11411   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11412
11413   if (Subtarget->is64Bit()) {
11414     SDValue OutChains[6];
11415
11416     // Large code-model.
11417     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11418     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11419
11420     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11421     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11422
11423     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11424
11425     // Load the pointer to the nested function into R11.
11426     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11427     SDValue Addr = Trmp;
11428     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11429                                 Addr, MachinePointerInfo(TrmpAddr),
11430                                 false, false, 0);
11431
11432     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11433                        DAG.getConstant(2, MVT::i64));
11434     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11435                                 MachinePointerInfo(TrmpAddr, 2),
11436                                 false, false, 2);
11437
11438     // Load the 'nest' parameter value into R10.
11439     // R10 is specified in X86CallingConv.td
11440     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11441     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11442                        DAG.getConstant(10, MVT::i64));
11443     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11444                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11445                                 false, false, 0);
11446
11447     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11448                        DAG.getConstant(12, MVT::i64));
11449     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11450                                 MachinePointerInfo(TrmpAddr, 12),
11451                                 false, false, 2);
11452
11453     // Jump to the nested function.
11454     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11455     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11456                        DAG.getConstant(20, MVT::i64));
11457     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11458                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11459                                 false, false, 0);
11460
11461     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11462     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11463                        DAG.getConstant(22, MVT::i64));
11464     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11465                                 MachinePointerInfo(TrmpAddr, 22),
11466                                 false, false, 0);
11467
11468     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11469   } else {
11470     const Function *Func =
11471       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11472     CallingConv::ID CC = Func->getCallingConv();
11473     unsigned NestReg;
11474
11475     switch (CC) {
11476     default:
11477       llvm_unreachable("Unsupported calling convention");
11478     case CallingConv::C:
11479     case CallingConv::X86_StdCall: {
11480       // Pass 'nest' parameter in ECX.
11481       // Must be kept in sync with X86CallingConv.td
11482       NestReg = X86::ECX;
11483
11484       // Check that ECX wasn't needed by an 'inreg' parameter.
11485       FunctionType *FTy = Func->getFunctionType();
11486       const AttributeSet &Attrs = Func->getAttributes();
11487
11488       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11489         unsigned InRegCount = 0;
11490         unsigned Idx = 1;
11491
11492         for (FunctionType::param_iterator I = FTy->param_begin(),
11493              E = FTy->param_end(); I != E; ++I, ++Idx)
11494           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11495             // FIXME: should only count parameters that are lowered to integers.
11496             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11497
11498         if (InRegCount > 2) {
11499           report_fatal_error("Nest register in use - reduce number of inreg"
11500                              " parameters!");
11501         }
11502       }
11503       break;
11504     }
11505     case CallingConv::X86_FastCall:
11506     case CallingConv::X86_ThisCall:
11507     case CallingConv::Fast:
11508       // Pass 'nest' parameter in EAX.
11509       // Must be kept in sync with X86CallingConv.td
11510       NestReg = X86::EAX;
11511       break;
11512     }
11513
11514     SDValue OutChains[4];
11515     SDValue Addr, Disp;
11516
11517     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11518                        DAG.getConstant(10, MVT::i32));
11519     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11520
11521     // This is storing the opcode for MOV32ri.
11522     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11523     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11524     OutChains[0] = DAG.getStore(Root, dl,
11525                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11526                                 Trmp, MachinePointerInfo(TrmpAddr),
11527                                 false, false, 0);
11528
11529     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11530                        DAG.getConstant(1, MVT::i32));
11531     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11532                                 MachinePointerInfo(TrmpAddr, 1),
11533                                 false, false, 1);
11534
11535     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11536     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11537                        DAG.getConstant(5, MVT::i32));
11538     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11539                                 MachinePointerInfo(TrmpAddr, 5),
11540                                 false, false, 1);
11541
11542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11543                        DAG.getConstant(6, MVT::i32));
11544     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11545                                 MachinePointerInfo(TrmpAddr, 6),
11546                                 false, false, 1);
11547
11548     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11549   }
11550 }
11551
11552 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11553                                             SelectionDAG &DAG) const {
11554   /*
11555    The rounding mode is in bits 11:10 of FPSR, and has the following
11556    settings:
11557      00 Round to nearest
11558      01 Round to -inf
11559      10 Round to +inf
11560      11 Round to 0
11561
11562   FLT_ROUNDS, on the other hand, expects the following:
11563     -1 Undefined
11564      0 Round to 0
11565      1 Round to nearest
11566      2 Round to +inf
11567      3 Round to -inf
11568
11569   To perform the conversion, we do:
11570     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11571   */
11572
11573   MachineFunction &MF = DAG.getMachineFunction();
11574   const TargetMachine &TM = MF.getTarget();
11575   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11576   unsigned StackAlignment = TFI.getStackAlignment();
11577   EVT VT = Op.getValueType();
11578   SDLoc DL(Op);
11579
11580   // Save FP Control Word to stack slot
11581   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11582   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11583
11584   MachineMemOperand *MMO =
11585    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11586                            MachineMemOperand::MOStore, 2, 2);
11587
11588   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11589   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11590                                           DAG.getVTList(MVT::Other),
11591                                           Ops, array_lengthof(Ops), MVT::i16,
11592                                           MMO);
11593
11594   // Load FP Control Word from stack slot
11595   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11596                             MachinePointerInfo(), false, false, false, 0);
11597
11598   // Transform as necessary
11599   SDValue CWD1 =
11600     DAG.getNode(ISD::SRL, DL, MVT::i16,
11601                 DAG.getNode(ISD::AND, DL, MVT::i16,
11602                             CWD, DAG.getConstant(0x800, MVT::i16)),
11603                 DAG.getConstant(11, MVT::i8));
11604   SDValue CWD2 =
11605     DAG.getNode(ISD::SRL, DL, MVT::i16,
11606                 DAG.getNode(ISD::AND, DL, MVT::i16,
11607                             CWD, DAG.getConstant(0x400, MVT::i16)),
11608                 DAG.getConstant(9, MVT::i8));
11609
11610   SDValue RetVal =
11611     DAG.getNode(ISD::AND, DL, MVT::i16,
11612                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11613                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11614                             DAG.getConstant(1, MVT::i16)),
11615                 DAG.getConstant(3, MVT::i16));
11616
11617   return DAG.getNode((VT.getSizeInBits() < 16 ?
11618                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11619 }
11620
11621 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11622   EVT VT = Op.getValueType();
11623   EVT OpVT = VT;
11624   unsigned NumBits = VT.getSizeInBits();
11625   SDLoc dl(Op);
11626
11627   Op = Op.getOperand(0);
11628   if (VT == MVT::i8) {
11629     // Zero extend to i32 since there is not an i8 bsr.
11630     OpVT = MVT::i32;
11631     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11632   }
11633
11634   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11635   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11636   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11637
11638   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11639   SDValue Ops[] = {
11640     Op,
11641     DAG.getConstant(NumBits+NumBits-1, OpVT),
11642     DAG.getConstant(X86::COND_E, MVT::i8),
11643     Op.getValue(1)
11644   };
11645   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11646
11647   // Finally xor with NumBits-1.
11648   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11649
11650   if (VT == MVT::i8)
11651     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11652   return Op;
11653 }
11654
11655 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11656   EVT VT = Op.getValueType();
11657   EVT OpVT = VT;
11658   unsigned NumBits = VT.getSizeInBits();
11659   SDLoc dl(Op);
11660
11661   Op = Op.getOperand(0);
11662   if (VT == MVT::i8) {
11663     // Zero extend to i32 since there is not an i8 bsr.
11664     OpVT = MVT::i32;
11665     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11666   }
11667
11668   // Issue a bsr (scan bits in reverse).
11669   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11670   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11671
11672   // And xor with NumBits-1.
11673   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11674
11675   if (VT == MVT::i8)
11676     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11677   return Op;
11678 }
11679
11680 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11681   EVT VT = Op.getValueType();
11682   unsigned NumBits = VT.getSizeInBits();
11683   SDLoc dl(Op);
11684   Op = Op.getOperand(0);
11685
11686   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11687   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11688   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11689
11690   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11691   SDValue Ops[] = {
11692     Op,
11693     DAG.getConstant(NumBits, VT),
11694     DAG.getConstant(X86::COND_E, MVT::i8),
11695     Op.getValue(1)
11696   };
11697   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11698 }
11699
11700 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11701 // ones, and then concatenate the result back.
11702 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11703   EVT VT = Op.getValueType();
11704
11705   assert(VT.is256BitVector() && VT.isInteger() &&
11706          "Unsupported value type for operation");
11707
11708   unsigned NumElems = VT.getVectorNumElements();
11709   SDLoc dl(Op);
11710
11711   // Extract the LHS vectors
11712   SDValue LHS = Op.getOperand(0);
11713   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11714   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11715
11716   // Extract the RHS vectors
11717   SDValue RHS = Op.getOperand(1);
11718   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11719   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11720
11721   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11722   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11723
11724   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11725                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11726                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11727 }
11728
11729 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11730   assert(Op.getValueType().is256BitVector() &&
11731          Op.getValueType().isInteger() &&
11732          "Only handle AVX 256-bit vector integer operation");
11733   return Lower256IntArith(Op, DAG);
11734 }
11735
11736 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11737   assert(Op.getValueType().is256BitVector() &&
11738          Op.getValueType().isInteger() &&
11739          "Only handle AVX 256-bit vector integer operation");
11740   return Lower256IntArith(Op, DAG);
11741 }
11742
11743 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11744                         SelectionDAG &DAG) {
11745   SDLoc dl(Op);
11746   EVT VT = Op.getValueType();
11747
11748   // Decompose 256-bit ops into smaller 128-bit ops.
11749   if (VT.is256BitVector() && !Subtarget->hasInt256())
11750     return Lower256IntArith(Op, DAG);
11751
11752   SDValue A = Op.getOperand(0);
11753   SDValue B = Op.getOperand(1);
11754
11755   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11756   if (VT == MVT::v4i32) {
11757     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11758            "Should not custom lower when pmuldq is available!");
11759
11760     // Extract the odd parts.
11761     static const int UnpackMask[] = { 1, -1, 3, -1 };
11762     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11763     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11764
11765     // Multiply the even parts.
11766     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11767     // Now multiply odd parts.
11768     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11769
11770     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11771     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11772
11773     // Merge the two vectors back together with a shuffle. This expands into 2
11774     // shuffles.
11775     static const int ShufMask[] = { 0, 4, 2, 6 };
11776     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11777   }
11778
11779   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11780          "Only know how to lower V2I64/V4I64 multiply");
11781
11782   //  Ahi = psrlqi(a, 32);
11783   //  Bhi = psrlqi(b, 32);
11784   //
11785   //  AloBlo = pmuludq(a, b);
11786   //  AloBhi = pmuludq(a, Bhi);
11787   //  AhiBlo = pmuludq(Ahi, b);
11788
11789   //  AloBhi = psllqi(AloBhi, 32);
11790   //  AhiBlo = psllqi(AhiBlo, 32);
11791   //  return AloBlo + AloBhi + AhiBlo;
11792
11793   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11794
11795   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11796   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11797
11798   // Bit cast to 32-bit vectors for MULUDQ
11799   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11800   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11801   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11802   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11803   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11804
11805   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11806   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11807   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11808
11809   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11810   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11811
11812   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11813   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11814 }
11815
11816 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11817   EVT VT = Op.getValueType();
11818   EVT EltTy = VT.getVectorElementType();
11819   unsigned NumElts = VT.getVectorNumElements();
11820   SDValue N0 = Op.getOperand(0);
11821   SDLoc dl(Op);
11822
11823   // Lower sdiv X, pow2-const.
11824   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11825   if (!C)
11826     return SDValue();
11827
11828   APInt SplatValue, SplatUndef;
11829   unsigned SplatBitSize;
11830   bool HasAnyUndefs;
11831   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11832                           HasAnyUndefs) ||
11833       EltTy.getSizeInBits() < SplatBitSize)
11834     return SDValue();
11835
11836   if ((SplatValue != 0) &&
11837       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11838     unsigned lg2 = SplatValue.countTrailingZeros();
11839     // Splat the sign bit.
11840     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11841     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11842     // Add (N0 < 0) ? abs2 - 1 : 0;
11843     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11844     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11845     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11846     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11847     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11848
11849     // If we're dividing by a positive value, we're done.  Otherwise, we must
11850     // negate the result.
11851     if (SplatValue.isNonNegative())
11852       return SRA;
11853
11854     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11855     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11856     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11857   }
11858   return SDValue();
11859 }
11860
11861 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11862                                          const X86Subtarget *Subtarget) {
11863   EVT VT = Op.getValueType();
11864   SDLoc dl(Op);
11865   SDValue R = Op.getOperand(0);
11866   SDValue Amt = Op.getOperand(1);
11867
11868   // Optimize shl/srl/sra with constant shift amount.
11869   if (isSplatVector(Amt.getNode())) {
11870     SDValue SclrAmt = Amt->getOperand(0);
11871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11872       uint64_t ShiftAmt = C->getZExtValue();
11873
11874       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11875           (Subtarget->hasInt256() &&
11876            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11877         if (Op.getOpcode() == ISD::SHL)
11878           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11879                              DAG.getConstant(ShiftAmt, MVT::i32));
11880         if (Op.getOpcode() == ISD::SRL)
11881           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11882                              DAG.getConstant(ShiftAmt, MVT::i32));
11883         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11884           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11885                              DAG.getConstant(ShiftAmt, MVT::i32));
11886       }
11887
11888       if (VT == MVT::v16i8) {
11889         if (Op.getOpcode() == ISD::SHL) {
11890           // Make a large shift.
11891           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11892                                     DAG.getConstant(ShiftAmt, MVT::i32));
11893           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11894           // Zero out the rightmost bits.
11895           SmallVector<SDValue, 16> V(16,
11896                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11897                                                      MVT::i8));
11898           return DAG.getNode(ISD::AND, dl, VT, SHL,
11899                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11900         }
11901         if (Op.getOpcode() == ISD::SRL) {
11902           // Make a large shift.
11903           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11904                                     DAG.getConstant(ShiftAmt, MVT::i32));
11905           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11906           // Zero out the leftmost bits.
11907           SmallVector<SDValue, 16> V(16,
11908                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11909                                                      MVT::i8));
11910           return DAG.getNode(ISD::AND, dl, VT, SRL,
11911                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11912         }
11913         if (Op.getOpcode() == ISD::SRA) {
11914           if (ShiftAmt == 7) {
11915             // R s>> 7  ===  R s< 0
11916             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11917             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11918           }
11919
11920           // R s>> a === ((R u>> a) ^ m) - m
11921           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11922           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11923                                                          MVT::i8));
11924           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11925           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11926           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11927           return Res;
11928         }
11929         llvm_unreachable("Unknown shift opcode.");
11930       }
11931
11932       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11933         if (Op.getOpcode() == ISD::SHL) {
11934           // Make a large shift.
11935           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11936                                     DAG.getConstant(ShiftAmt, MVT::i32));
11937           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11938           // Zero out the rightmost bits.
11939           SmallVector<SDValue, 32> V(32,
11940                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11941                                                      MVT::i8));
11942           return DAG.getNode(ISD::AND, dl, VT, SHL,
11943                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11944         }
11945         if (Op.getOpcode() == ISD::SRL) {
11946           // Make a large shift.
11947           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11948                                     DAG.getConstant(ShiftAmt, MVT::i32));
11949           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11950           // Zero out the leftmost bits.
11951           SmallVector<SDValue, 32> V(32,
11952                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11953                                                      MVT::i8));
11954           return DAG.getNode(ISD::AND, dl, VT, SRL,
11955                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11956         }
11957         if (Op.getOpcode() == ISD::SRA) {
11958           if (ShiftAmt == 7) {
11959             // R s>> 7  ===  R s< 0
11960             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11961             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11962           }
11963
11964           // R s>> a === ((R u>> a) ^ m) - m
11965           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11966           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11967                                                          MVT::i8));
11968           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11969           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11970           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11971           return Res;
11972         }
11973         llvm_unreachable("Unknown shift opcode.");
11974       }
11975     }
11976   }
11977
11978   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11979   if (!Subtarget->is64Bit() &&
11980       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11981       Amt.getOpcode() == ISD::BITCAST &&
11982       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11983     Amt = Amt.getOperand(0);
11984     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11985                      VT.getVectorNumElements();
11986     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11987     uint64_t ShiftAmt = 0;
11988     for (unsigned i = 0; i != Ratio; ++i) {
11989       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11990       if (C == 0)
11991         return SDValue();
11992       // 6 == Log2(64)
11993       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11994     }
11995     // Check remaining shift amounts.
11996     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11997       uint64_t ShAmt = 0;
11998       for (unsigned j = 0; j != Ratio; ++j) {
11999         ConstantSDNode *C =
12000           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12001         if (C == 0)
12002           return SDValue();
12003         // 6 == Log2(64)
12004         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12005       }
12006       if (ShAmt != ShiftAmt)
12007         return SDValue();
12008     }
12009     switch (Op.getOpcode()) {
12010     default:
12011       llvm_unreachable("Unknown shift opcode!");
12012     case ISD::SHL:
12013       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12014                          DAG.getConstant(ShiftAmt, MVT::i32));
12015     case ISD::SRL:
12016       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12017                          DAG.getConstant(ShiftAmt, MVT::i32));
12018     case ISD::SRA:
12019       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12020                          DAG.getConstant(ShiftAmt, MVT::i32));
12021     }
12022   }
12023
12024   return SDValue();
12025 }
12026
12027 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12028                                         const X86Subtarget* Subtarget) {
12029   EVT VT = Op.getValueType();
12030   SDLoc dl(Op);
12031   SDValue R = Op.getOperand(0);
12032   SDValue Amt = Op.getOperand(1);
12033
12034   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12035       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12036       (Subtarget->hasInt256() &&
12037        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12038         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12039     SDValue BaseShAmt;
12040     EVT EltVT = VT.getVectorElementType();
12041
12042     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12043       unsigned NumElts = VT.getVectorNumElements();
12044       unsigned i, j;
12045       for (i = 0; i != NumElts; ++i) {
12046         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12047           continue;
12048         break;
12049       }
12050       for (j = i; j != NumElts; ++j) {
12051         SDValue Arg = Amt.getOperand(j);
12052         if (Arg.getOpcode() == ISD::UNDEF) continue;
12053         if (Arg != Amt.getOperand(i))
12054           break;
12055       }
12056       if (i != NumElts && j == NumElts)
12057         BaseShAmt = Amt.getOperand(i);
12058     } else {
12059       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12060         Amt = Amt.getOperand(0);
12061       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12062                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12063         SDValue InVec = Amt.getOperand(0);
12064         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12065           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12066           unsigned i = 0;
12067           for (; i != NumElts; ++i) {
12068             SDValue Arg = InVec.getOperand(i);
12069             if (Arg.getOpcode() == ISD::UNDEF) continue;
12070             BaseShAmt = Arg;
12071             break;
12072           }
12073         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12074            if (ConstantSDNode *C =
12075                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12076              unsigned SplatIdx =
12077                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12078              if (C->getZExtValue() == SplatIdx)
12079                BaseShAmt = InVec.getOperand(1);
12080            }
12081         }
12082         if (BaseShAmt.getNode() == 0)
12083           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12084                                   DAG.getIntPtrConstant(0));
12085       }
12086     }
12087
12088     if (BaseShAmt.getNode()) {
12089       if (EltVT.bitsGT(MVT::i32))
12090         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12091       else if (EltVT.bitsLT(MVT::i32))
12092         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12093
12094       switch (Op.getOpcode()) {
12095       default:
12096         llvm_unreachable("Unknown shift opcode!");
12097       case ISD::SHL:
12098         switch (VT.getSimpleVT().SimpleTy) {
12099         default: return SDValue();
12100         case MVT::v2i64:
12101         case MVT::v4i32:
12102         case MVT::v8i16:
12103         case MVT::v4i64:
12104         case MVT::v8i32:
12105         case MVT::v16i16:
12106           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12107         }
12108       case ISD::SRA:
12109         switch (VT.getSimpleVT().SimpleTy) {
12110         default: return SDValue();
12111         case MVT::v4i32:
12112         case MVT::v8i16:
12113         case MVT::v8i32:
12114         case MVT::v16i16:
12115           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12116         }
12117       case ISD::SRL:
12118         switch (VT.getSimpleVT().SimpleTy) {
12119         default: return SDValue();
12120         case MVT::v2i64:
12121         case MVT::v4i32:
12122         case MVT::v8i16:
12123         case MVT::v4i64:
12124         case MVT::v8i32:
12125         case MVT::v16i16:
12126           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12127         }
12128       }
12129     }
12130   }
12131
12132   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12133   if (!Subtarget->is64Bit() &&
12134       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12135       Amt.getOpcode() == ISD::BITCAST &&
12136       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12137     Amt = Amt.getOperand(0);
12138     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12139                      VT.getVectorNumElements();
12140     std::vector<SDValue> Vals(Ratio);
12141     for (unsigned i = 0; i != Ratio; ++i)
12142       Vals[i] = Amt.getOperand(i);
12143     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12144       for (unsigned j = 0; j != Ratio; ++j)
12145         if (Vals[j] != Amt.getOperand(i + j))
12146           return SDValue();
12147     }
12148     switch (Op.getOpcode()) {
12149     default:
12150       llvm_unreachable("Unknown shift opcode!");
12151     case ISD::SHL:
12152       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12153     case ISD::SRL:
12154       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12155     case ISD::SRA:
12156       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12157     }
12158   }
12159
12160   return SDValue();
12161 }
12162
12163 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12164
12165   EVT VT = Op.getValueType();
12166   SDLoc dl(Op);
12167   SDValue R = Op.getOperand(0);
12168   SDValue Amt = Op.getOperand(1);
12169   SDValue V;
12170
12171   if (!Subtarget->hasSSE2())
12172     return SDValue();
12173
12174   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12175   if (V.getNode())
12176     return V;
12177
12178   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12179   if (V.getNode())
12180       return V;
12181
12182   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12183   if (Subtarget->hasInt256()) {
12184     if (Op.getOpcode() == ISD::SRL &&
12185         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12186          VT == MVT::v4i64 || VT == MVT::v8i32))
12187       return Op;
12188     if (Op.getOpcode() == ISD::SHL &&
12189         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12190          VT == MVT::v4i64 || VT == MVT::v8i32))
12191       return Op;
12192     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12193       return Op;
12194   }
12195
12196   // Lower SHL with variable shift amount.
12197   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12198     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12199
12200     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12201     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12202     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12203     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12204   }
12205   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12206     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12207
12208     // a = a << 5;
12209     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12210     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12211
12212     // Turn 'a' into a mask suitable for VSELECT
12213     SDValue VSelM = DAG.getConstant(0x80, VT);
12214     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12215     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12216
12217     SDValue CM1 = DAG.getConstant(0x0f, VT);
12218     SDValue CM2 = DAG.getConstant(0x3f, VT);
12219
12220     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12221     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12222     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12223                             DAG.getConstant(4, MVT::i32), DAG);
12224     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12225     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12226
12227     // a += a
12228     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12229     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12230     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12231
12232     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12233     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12234     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12235                             DAG.getConstant(2, MVT::i32), DAG);
12236     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12237     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12238
12239     // a += a
12240     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12241     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12242     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12243
12244     // return VSELECT(r, r+r, a);
12245     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12246                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12247     return R;
12248   }
12249
12250   // Decompose 256-bit shifts into smaller 128-bit shifts.
12251   if (VT.is256BitVector()) {
12252     unsigned NumElems = VT.getVectorNumElements();
12253     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12254     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12255
12256     // Extract the two vectors
12257     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12258     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12259
12260     // Recreate the shift amount vectors
12261     SDValue Amt1, Amt2;
12262     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12263       // Constant shift amount
12264       SmallVector<SDValue, 4> Amt1Csts;
12265       SmallVector<SDValue, 4> Amt2Csts;
12266       for (unsigned i = 0; i != NumElems/2; ++i)
12267         Amt1Csts.push_back(Amt->getOperand(i));
12268       for (unsigned i = NumElems/2; i != NumElems; ++i)
12269         Amt2Csts.push_back(Amt->getOperand(i));
12270
12271       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12272                                  &Amt1Csts[0], NumElems/2);
12273       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12274                                  &Amt2Csts[0], NumElems/2);
12275     } else {
12276       // Variable shift amount
12277       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12278       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12279     }
12280
12281     // Issue new vector shifts for the smaller types
12282     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12283     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12284
12285     // Concatenate the result back
12286     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12287   }
12288
12289   return SDValue();
12290 }
12291
12292 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12293   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12294   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12295   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12296   // has only one use.
12297   SDNode *N = Op.getNode();
12298   SDValue LHS = N->getOperand(0);
12299   SDValue RHS = N->getOperand(1);
12300   unsigned BaseOp = 0;
12301   unsigned Cond = 0;
12302   SDLoc DL(Op);
12303   switch (Op.getOpcode()) {
12304   default: llvm_unreachable("Unknown ovf instruction!");
12305   case ISD::SADDO:
12306     // A subtract of one will be selected as a INC. Note that INC doesn't
12307     // set CF, so we can't do this for UADDO.
12308     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12309       if (C->isOne()) {
12310         BaseOp = X86ISD::INC;
12311         Cond = X86::COND_O;
12312         break;
12313       }
12314     BaseOp = X86ISD::ADD;
12315     Cond = X86::COND_O;
12316     break;
12317   case ISD::UADDO:
12318     BaseOp = X86ISD::ADD;
12319     Cond = X86::COND_B;
12320     break;
12321   case ISD::SSUBO:
12322     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12323     // set CF, so we can't do this for USUBO.
12324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12325       if (C->isOne()) {
12326         BaseOp = X86ISD::DEC;
12327         Cond = X86::COND_O;
12328         break;
12329       }
12330     BaseOp = X86ISD::SUB;
12331     Cond = X86::COND_O;
12332     break;
12333   case ISD::USUBO:
12334     BaseOp = X86ISD::SUB;
12335     Cond = X86::COND_B;
12336     break;
12337   case ISD::SMULO:
12338     BaseOp = X86ISD::SMUL;
12339     Cond = X86::COND_O;
12340     break;
12341   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12342     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12343                                  MVT::i32);
12344     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12345
12346     SDValue SetCC =
12347       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12348                   DAG.getConstant(X86::COND_O, MVT::i32),
12349                   SDValue(Sum.getNode(), 2));
12350
12351     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12352   }
12353   }
12354
12355   // Also sets EFLAGS.
12356   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12357   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12358
12359   SDValue SetCC =
12360     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12361                 DAG.getConstant(Cond, MVT::i32),
12362                 SDValue(Sum.getNode(), 1));
12363
12364   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12365 }
12366
12367 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12368                                                   SelectionDAG &DAG) const {
12369   SDLoc dl(Op);
12370   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12371   EVT VT = Op.getValueType();
12372
12373   if (!Subtarget->hasSSE2() || !VT.isVector())
12374     return SDValue();
12375
12376   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12377                       ExtraVT.getScalarType().getSizeInBits();
12378   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12379
12380   switch (VT.getSimpleVT().SimpleTy) {
12381     default: return SDValue();
12382     case MVT::v8i32:
12383     case MVT::v16i16:
12384       if (!Subtarget->hasFp256())
12385         return SDValue();
12386       if (!Subtarget->hasInt256()) {
12387         // needs to be split
12388         unsigned NumElems = VT.getVectorNumElements();
12389
12390         // Extract the LHS vectors
12391         SDValue LHS = Op.getOperand(0);
12392         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12393         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12394
12395         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12396         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12397
12398         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12399         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12400         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12401                                    ExtraNumElems/2);
12402         SDValue Extra = DAG.getValueType(ExtraVT);
12403
12404         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12405         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12406
12407         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12408       }
12409       // fall through
12410     case MVT::v4i32:
12411     case MVT::v8i16: {
12412       // (sext (vzext x)) -> (vsext x)
12413       SDValue Op0 = Op.getOperand(0);
12414       SDValue Op00 = Op0.getOperand(0);
12415       SDValue Tmp1;
12416       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12417       if (Op0.getOpcode() == ISD::BITCAST &&
12418           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12419         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12420       if (Tmp1.getNode()) {
12421         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12422         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12423                "This optimization is invalid without a VZEXT.");
12424         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12425       }
12426
12427       // If the above didn't work, then just use Shift-Left + Shift-Right.
12428       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12429       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12430     }
12431   }
12432 }
12433
12434 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12435                                  SelectionDAG &DAG) {
12436   SDLoc dl(Op);
12437   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12438     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12439   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12440     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12441
12442   // The only fence that needs an instruction is a sequentially-consistent
12443   // cross-thread fence.
12444   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12445     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12446     // no-sse2). There isn't any reason to disable it if the target processor
12447     // supports it.
12448     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12449       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12450
12451     SDValue Chain = Op.getOperand(0);
12452     SDValue Zero = DAG.getConstant(0, MVT::i32);
12453     SDValue Ops[] = {
12454       DAG.getRegister(X86::ESP, MVT::i32), // Base
12455       DAG.getTargetConstant(1, MVT::i8),   // Scale
12456       DAG.getRegister(0, MVT::i32),        // Index
12457       DAG.getTargetConstant(0, MVT::i32),  // Disp
12458       DAG.getRegister(0, MVT::i32),        // Segment.
12459       Zero,
12460       Chain
12461     };
12462     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12463     return SDValue(Res, 0);
12464   }
12465
12466   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12467   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12468 }
12469
12470 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12471                              SelectionDAG &DAG) {
12472   EVT T = Op.getValueType();
12473   SDLoc DL(Op);
12474   unsigned Reg = 0;
12475   unsigned size = 0;
12476   switch(T.getSimpleVT().SimpleTy) {
12477   default: llvm_unreachable("Invalid value type!");
12478   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12479   case MVT::i16: Reg = X86::AX;  size = 2; break;
12480   case MVT::i32: Reg = X86::EAX; size = 4; break;
12481   case MVT::i64:
12482     assert(Subtarget->is64Bit() && "Node not type legal!");
12483     Reg = X86::RAX; size = 8;
12484     break;
12485   }
12486   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12487                                     Op.getOperand(2), SDValue());
12488   SDValue Ops[] = { cpIn.getValue(0),
12489                     Op.getOperand(1),
12490                     Op.getOperand(3),
12491                     DAG.getTargetConstant(size, MVT::i8),
12492                     cpIn.getValue(1) };
12493   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12494   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12495   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12496                                            Ops, array_lengthof(Ops), T, MMO);
12497   SDValue cpOut =
12498     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12499   return cpOut;
12500 }
12501
12502 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12503                                      SelectionDAG &DAG) {
12504   assert(Subtarget->is64Bit() && "Result not type legalized?");
12505   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12506   SDValue TheChain = Op.getOperand(0);
12507   SDLoc dl(Op);
12508   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12509   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12510   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12511                                    rax.getValue(2));
12512   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12513                             DAG.getConstant(32, MVT::i8));
12514   SDValue Ops[] = {
12515     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12516     rdx.getValue(1)
12517   };
12518   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12519 }
12520
12521 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12522   EVT SrcVT = Op.getOperand(0).getValueType();
12523   EVT DstVT = Op.getValueType();
12524   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12525          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12526   assert((DstVT == MVT::i64 ||
12527           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12528          "Unexpected custom BITCAST");
12529   // i64 <=> MMX conversions are Legal.
12530   if (SrcVT==MVT::i64 && DstVT.isVector())
12531     return Op;
12532   if (DstVT==MVT::i64 && SrcVT.isVector())
12533     return Op;
12534   // MMX <=> MMX conversions are Legal.
12535   if (SrcVT.isVector() && DstVT.isVector())
12536     return Op;
12537   // All other conversions need to be expanded.
12538   return SDValue();
12539 }
12540
12541 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12542   SDNode *Node = Op.getNode();
12543   SDLoc dl(Node);
12544   EVT T = Node->getValueType(0);
12545   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12546                               DAG.getConstant(0, T), Node->getOperand(2));
12547   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12548                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12549                        Node->getOperand(0),
12550                        Node->getOperand(1), negOp,
12551                        cast<AtomicSDNode>(Node)->getSrcValue(),
12552                        cast<AtomicSDNode>(Node)->getAlignment(),
12553                        cast<AtomicSDNode>(Node)->getOrdering(),
12554                        cast<AtomicSDNode>(Node)->getSynchScope());
12555 }
12556
12557 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12558   SDNode *Node = Op.getNode();
12559   SDLoc dl(Node);
12560   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12561
12562   // Convert seq_cst store -> xchg
12563   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12564   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12565   //        (The only way to get a 16-byte store is cmpxchg16b)
12566   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12567   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12568       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12569     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12570                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12571                                  Node->getOperand(0),
12572                                  Node->getOperand(1), Node->getOperand(2),
12573                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12574                                  cast<AtomicSDNode>(Node)->getOrdering(),
12575                                  cast<AtomicSDNode>(Node)->getSynchScope());
12576     return Swap.getValue(1);
12577   }
12578   // Other atomic stores have a simple pattern.
12579   return Op;
12580 }
12581
12582 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12583   EVT VT = Op.getNode()->getValueType(0);
12584
12585   // Let legalize expand this if it isn't a legal type yet.
12586   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12587     return SDValue();
12588
12589   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12590
12591   unsigned Opc;
12592   bool ExtraOp = false;
12593   switch (Op.getOpcode()) {
12594   default: llvm_unreachable("Invalid code");
12595   case ISD::ADDC: Opc = X86ISD::ADD; break;
12596   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12597   case ISD::SUBC: Opc = X86ISD::SUB; break;
12598   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12599   }
12600
12601   if (!ExtraOp)
12602     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12603                        Op.getOperand(1));
12604   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12605                      Op.getOperand(1), Op.getOperand(2));
12606 }
12607
12608 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12609   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12610
12611   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12612   // which returns the values as { float, float } (in XMM0) or
12613   // { double, double } (which is returned in XMM0, XMM1).
12614   SDLoc dl(Op);
12615   SDValue Arg = Op.getOperand(0);
12616   EVT ArgVT = Arg.getValueType();
12617   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12618
12619   ArgListTy Args;
12620   ArgListEntry Entry;
12621
12622   Entry.Node = Arg;
12623   Entry.Ty = ArgTy;
12624   Entry.isSExt = false;
12625   Entry.isZExt = false;
12626   Args.push_back(Entry);
12627
12628   bool isF64 = ArgVT == MVT::f64;
12629   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12630   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12631   // the results are returned via SRet in memory.
12632   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12633   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12634
12635   Type *RetTy = isF64
12636     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12637     : (Type*)VectorType::get(ArgTy, 4);
12638   TargetLowering::
12639     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12640                          false, false, false, false, 0,
12641                          CallingConv::C, /*isTaillCall=*/false,
12642                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12643                          Callee, Args, DAG, dl);
12644   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12645
12646   if (isF64)
12647     // Returned in xmm0 and xmm1.
12648     return CallResult.first;
12649
12650   // Returned in bits 0:31 and 32:64 xmm0.
12651   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12652                                CallResult.first, DAG.getIntPtrConstant(0));
12653   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12654                                CallResult.first, DAG.getIntPtrConstant(1));
12655   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12656   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12657 }
12658
12659 /// LowerOperation - Provide custom lowering hooks for some operations.
12660 ///
12661 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12662   switch (Op.getOpcode()) {
12663   default: llvm_unreachable("Should not custom lower this!");
12664   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12665   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12666   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12667   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12668   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12669   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12670   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12671   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12672   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12673   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12674   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12675   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12676   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12677   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12678   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12679   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12680   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12681   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12682   case ISD::SHL_PARTS:
12683   case ISD::SRA_PARTS:
12684   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12685   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12686   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12687   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12688   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12689   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12690   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12691   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12692   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12693   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12694   case ISD::FABS:               return LowerFABS(Op, DAG);
12695   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12696   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12697   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12698   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12699   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12700   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12701   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12702   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12703   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12704   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12705   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12706   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12707   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12708   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12709   case ISD::FRAME_TO_ARGS_OFFSET:
12710                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12711   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12712   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12713   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12714   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12715   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12716   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12717   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12718   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12719   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12720   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12721   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12722   case ISD::SRA:
12723   case ISD::SRL:
12724   case ISD::SHL:                return LowerShift(Op, DAG);
12725   case ISD::SADDO:
12726   case ISD::UADDO:
12727   case ISD::SSUBO:
12728   case ISD::USUBO:
12729   case ISD::SMULO:
12730   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12731   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12732   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12733   case ISD::ADDC:
12734   case ISD::ADDE:
12735   case ISD::SUBC:
12736   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12737   case ISD::ADD:                return LowerADD(Op, DAG);
12738   case ISD::SUB:                return LowerSUB(Op, DAG);
12739   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12740   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12741   }
12742 }
12743
12744 static void ReplaceATOMIC_LOAD(SDNode *Node,
12745                                   SmallVectorImpl<SDValue> &Results,
12746                                   SelectionDAG &DAG) {
12747   SDLoc dl(Node);
12748   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12749
12750   // Convert wide load -> cmpxchg8b/cmpxchg16b
12751   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12752   //        (The only way to get a 16-byte load is cmpxchg16b)
12753   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12754   SDValue Zero = DAG.getConstant(0, VT);
12755   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12756                                Node->getOperand(0),
12757                                Node->getOperand(1), Zero, Zero,
12758                                cast<AtomicSDNode>(Node)->getMemOperand(),
12759                                cast<AtomicSDNode>(Node)->getOrdering(),
12760                                cast<AtomicSDNode>(Node)->getSynchScope());
12761   Results.push_back(Swap.getValue(0));
12762   Results.push_back(Swap.getValue(1));
12763 }
12764
12765 static void
12766 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12767                         SelectionDAG &DAG, unsigned NewOp) {
12768   SDLoc dl(Node);
12769   assert (Node->getValueType(0) == MVT::i64 &&
12770           "Only know how to expand i64 atomics");
12771
12772   SDValue Chain = Node->getOperand(0);
12773   SDValue In1 = Node->getOperand(1);
12774   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12775                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12776   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12777                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12778   SDValue Ops[] = { Chain, In1, In2L, In2H };
12779   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12780   SDValue Result =
12781     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12782                             cast<MemSDNode>(Node)->getMemOperand());
12783   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12784   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12785   Results.push_back(Result.getValue(2));
12786 }
12787
12788 /// ReplaceNodeResults - Replace a node with an illegal result type
12789 /// with a new node built out of custom code.
12790 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12791                                            SmallVectorImpl<SDValue>&Results,
12792                                            SelectionDAG &DAG) const {
12793   SDLoc dl(N);
12794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12795   switch (N->getOpcode()) {
12796   default:
12797     llvm_unreachable("Do not know how to custom type legalize this operation!");
12798   case ISD::SIGN_EXTEND_INREG:
12799   case ISD::ADDC:
12800   case ISD::ADDE:
12801   case ISD::SUBC:
12802   case ISD::SUBE:
12803     // We don't want to expand or promote these.
12804     return;
12805   case ISD::FP_TO_SINT:
12806   case ISD::FP_TO_UINT: {
12807     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12808
12809     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12810       return;
12811
12812     std::pair<SDValue,SDValue> Vals =
12813         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12814     SDValue FIST = Vals.first, StackSlot = Vals.second;
12815     if (FIST.getNode() != 0) {
12816       EVT VT = N->getValueType(0);
12817       // Return a load from the stack slot.
12818       if (StackSlot.getNode() != 0)
12819         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12820                                       MachinePointerInfo(),
12821                                       false, false, false, 0));
12822       else
12823         Results.push_back(FIST);
12824     }
12825     return;
12826   }
12827   case ISD::UINT_TO_FP: {
12828     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12829     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12830         N->getValueType(0) != MVT::v2f32)
12831       return;
12832     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12833                                  N->getOperand(0));
12834     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12835                                      MVT::f64);
12836     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12837     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12838                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12839     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12840     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12841     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12842     return;
12843   }
12844   case ISD::FP_ROUND: {
12845     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12846         return;
12847     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12848     Results.push_back(V);
12849     return;
12850   }
12851   case ISD::READCYCLECOUNTER: {
12852     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12853     SDValue TheChain = N->getOperand(0);
12854     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12855     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12856                                      rd.getValue(1));
12857     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12858                                      eax.getValue(2));
12859     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12860     SDValue Ops[] = { eax, edx };
12861     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12862                                   array_lengthof(Ops)));
12863     Results.push_back(edx.getValue(1));
12864     return;
12865   }
12866   case ISD::ATOMIC_CMP_SWAP: {
12867     EVT T = N->getValueType(0);
12868     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12869     bool Regs64bit = T == MVT::i128;
12870     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12871     SDValue cpInL, cpInH;
12872     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12873                         DAG.getConstant(0, HalfT));
12874     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12875                         DAG.getConstant(1, HalfT));
12876     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12877                              Regs64bit ? X86::RAX : X86::EAX,
12878                              cpInL, SDValue());
12879     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12880                              Regs64bit ? X86::RDX : X86::EDX,
12881                              cpInH, cpInL.getValue(1));
12882     SDValue swapInL, swapInH;
12883     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12884                           DAG.getConstant(0, HalfT));
12885     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12886                           DAG.getConstant(1, HalfT));
12887     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12888                                Regs64bit ? X86::RBX : X86::EBX,
12889                                swapInL, cpInH.getValue(1));
12890     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12891                                Regs64bit ? X86::RCX : X86::ECX,
12892                                swapInH, swapInL.getValue(1));
12893     SDValue Ops[] = { swapInH.getValue(0),
12894                       N->getOperand(1),
12895                       swapInH.getValue(1) };
12896     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12897     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12898     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12899                                   X86ISD::LCMPXCHG8_DAG;
12900     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12901                                              Ops, array_lengthof(Ops), T, MMO);
12902     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12903                                         Regs64bit ? X86::RAX : X86::EAX,
12904                                         HalfT, Result.getValue(1));
12905     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12906                                         Regs64bit ? X86::RDX : X86::EDX,
12907                                         HalfT, cpOutL.getValue(2));
12908     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12909     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12910     Results.push_back(cpOutH.getValue(1));
12911     return;
12912   }
12913   case ISD::ATOMIC_LOAD_ADD:
12914   case ISD::ATOMIC_LOAD_AND:
12915   case ISD::ATOMIC_LOAD_NAND:
12916   case ISD::ATOMIC_LOAD_OR:
12917   case ISD::ATOMIC_LOAD_SUB:
12918   case ISD::ATOMIC_LOAD_XOR:
12919   case ISD::ATOMIC_LOAD_MAX:
12920   case ISD::ATOMIC_LOAD_MIN:
12921   case ISD::ATOMIC_LOAD_UMAX:
12922   case ISD::ATOMIC_LOAD_UMIN:
12923   case ISD::ATOMIC_SWAP: {
12924     unsigned Opc;
12925     switch (N->getOpcode()) {
12926     default: llvm_unreachable("Unexpected opcode");
12927     case ISD::ATOMIC_LOAD_ADD:
12928       Opc = X86ISD::ATOMADD64_DAG;
12929       break;
12930     case ISD::ATOMIC_LOAD_AND:
12931       Opc = X86ISD::ATOMAND64_DAG;
12932       break;
12933     case ISD::ATOMIC_LOAD_NAND:
12934       Opc = X86ISD::ATOMNAND64_DAG;
12935       break;
12936     case ISD::ATOMIC_LOAD_OR:
12937       Opc = X86ISD::ATOMOR64_DAG;
12938       break;
12939     case ISD::ATOMIC_LOAD_SUB:
12940       Opc = X86ISD::ATOMSUB64_DAG;
12941       break;
12942     case ISD::ATOMIC_LOAD_XOR:
12943       Opc = X86ISD::ATOMXOR64_DAG;
12944       break;
12945     case ISD::ATOMIC_LOAD_MAX:
12946       Opc = X86ISD::ATOMMAX64_DAG;
12947       break;
12948     case ISD::ATOMIC_LOAD_MIN:
12949       Opc = X86ISD::ATOMMIN64_DAG;
12950       break;
12951     case ISD::ATOMIC_LOAD_UMAX:
12952       Opc = X86ISD::ATOMUMAX64_DAG;
12953       break;
12954     case ISD::ATOMIC_LOAD_UMIN:
12955       Opc = X86ISD::ATOMUMIN64_DAG;
12956       break;
12957     case ISD::ATOMIC_SWAP:
12958       Opc = X86ISD::ATOMSWAP64_DAG;
12959       break;
12960     }
12961     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12962     return;
12963   }
12964   case ISD::ATOMIC_LOAD:
12965     ReplaceATOMIC_LOAD(N, Results, DAG);
12966   }
12967 }
12968
12969 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12970   switch (Opcode) {
12971   default: return NULL;
12972   case X86ISD::BSF:                return "X86ISD::BSF";
12973   case X86ISD::BSR:                return "X86ISD::BSR";
12974   case X86ISD::SHLD:               return "X86ISD::SHLD";
12975   case X86ISD::SHRD:               return "X86ISD::SHRD";
12976   case X86ISD::FAND:               return "X86ISD::FAND";
12977   case X86ISD::FOR:                return "X86ISD::FOR";
12978   case X86ISD::FXOR:               return "X86ISD::FXOR";
12979   case X86ISD::FSRL:               return "X86ISD::FSRL";
12980   case X86ISD::FILD:               return "X86ISD::FILD";
12981   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12982   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12983   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12984   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12985   case X86ISD::FLD:                return "X86ISD::FLD";
12986   case X86ISD::FST:                return "X86ISD::FST";
12987   case X86ISD::CALL:               return "X86ISD::CALL";
12988   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12989   case X86ISD::BT:                 return "X86ISD::BT";
12990   case X86ISD::CMP:                return "X86ISD::CMP";
12991   case X86ISD::COMI:               return "X86ISD::COMI";
12992   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12993   case X86ISD::SETCC:              return "X86ISD::SETCC";
12994   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12995   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12996   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12997   case X86ISD::CMOV:               return "X86ISD::CMOV";
12998   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12999   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13000   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13001   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13002   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13003   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13004   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13005   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13006   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13007   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13008   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13009   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13010   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13011   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13012   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13013   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13014   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13015   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13016   case X86ISD::HADD:               return "X86ISD::HADD";
13017   case X86ISD::HSUB:               return "X86ISD::HSUB";
13018   case X86ISD::FHADD:              return "X86ISD::FHADD";
13019   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13020   case X86ISD::UMAX:               return "X86ISD::UMAX";
13021   case X86ISD::UMIN:               return "X86ISD::UMIN";
13022   case X86ISD::SMAX:               return "X86ISD::SMAX";
13023   case X86ISD::SMIN:               return "X86ISD::SMIN";
13024   case X86ISD::FMAX:               return "X86ISD::FMAX";
13025   case X86ISD::FMIN:               return "X86ISD::FMIN";
13026   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13027   case X86ISD::FMINC:              return "X86ISD::FMINC";
13028   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13029   case X86ISD::FRCP:               return "X86ISD::FRCP";
13030   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13031   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13032   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13033   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13034   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13035   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13036   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13037   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13038   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13039   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13040   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13041   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13042   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13043   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13044   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13045   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13046   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13047   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13048   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13049   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13050   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13051   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13052   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13053   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13054   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13055   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13056   case X86ISD::VSHL:               return "X86ISD::VSHL";
13057   case X86ISD::VSRL:               return "X86ISD::VSRL";
13058   case X86ISD::VSRA:               return "X86ISD::VSRA";
13059   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13060   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13061   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13062   case X86ISD::CMPP:               return "X86ISD::CMPP";
13063   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13064   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13065   case X86ISD::ADD:                return "X86ISD::ADD";
13066   case X86ISD::SUB:                return "X86ISD::SUB";
13067   case X86ISD::ADC:                return "X86ISD::ADC";
13068   case X86ISD::SBB:                return "X86ISD::SBB";
13069   case X86ISD::SMUL:               return "X86ISD::SMUL";
13070   case X86ISD::UMUL:               return "X86ISD::UMUL";
13071   case X86ISD::INC:                return "X86ISD::INC";
13072   case X86ISD::DEC:                return "X86ISD::DEC";
13073   case X86ISD::OR:                 return "X86ISD::OR";
13074   case X86ISD::XOR:                return "X86ISD::XOR";
13075   case X86ISD::AND:                return "X86ISD::AND";
13076   case X86ISD::BLSI:               return "X86ISD::BLSI";
13077   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13078   case X86ISD::BLSR:               return "X86ISD::BLSR";
13079   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13080   case X86ISD::PTEST:              return "X86ISD::PTEST";
13081   case X86ISD::TESTP:              return "X86ISD::TESTP";
13082   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13083   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13084   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13085   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13086   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13087   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13088   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13089   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13090   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13091   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13092   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13093   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13094   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13095   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13096   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13097   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13098   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13099   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13100   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13101   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13102   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13103   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13104   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13105   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13106   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13107   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13108   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13109   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13110   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13111   case X86ISD::SAHF:               return "X86ISD::SAHF";
13112   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13113   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13114   case X86ISD::FMADD:              return "X86ISD::FMADD";
13115   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13116   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13117   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13118   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13119   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13120   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13121   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13122   case X86ISD::XTEST:              return "X86ISD::XTEST";
13123   }
13124 }
13125
13126 // isLegalAddressingMode - Return true if the addressing mode represented
13127 // by AM is legal for this target, for a load/store of the specified type.
13128 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13129                                               Type *Ty) const {
13130   // X86 supports extremely general addressing modes.
13131   CodeModel::Model M = getTargetMachine().getCodeModel();
13132   Reloc::Model R = getTargetMachine().getRelocationModel();
13133
13134   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13135   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13136     return false;
13137
13138   if (AM.BaseGV) {
13139     unsigned GVFlags =
13140       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13141
13142     // If a reference to this global requires an extra load, we can't fold it.
13143     if (isGlobalStubReference(GVFlags))
13144       return false;
13145
13146     // If BaseGV requires a register for the PIC base, we cannot also have a
13147     // BaseReg specified.
13148     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13149       return false;
13150
13151     // If lower 4G is not available, then we must use rip-relative addressing.
13152     if ((M != CodeModel::Small || R != Reloc::Static) &&
13153         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13154       return false;
13155   }
13156
13157   switch (AM.Scale) {
13158   case 0:
13159   case 1:
13160   case 2:
13161   case 4:
13162   case 8:
13163     // These scales always work.
13164     break;
13165   case 3:
13166   case 5:
13167   case 9:
13168     // These scales are formed with basereg+scalereg.  Only accept if there is
13169     // no basereg yet.
13170     if (AM.HasBaseReg)
13171       return false;
13172     break;
13173   default:  // Other stuff never works.
13174     return false;
13175   }
13176
13177   return true;
13178 }
13179
13180 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13181   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13182     return false;
13183   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13184   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13185   return NumBits1 > NumBits2;
13186 }
13187
13188 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13189   return isInt<32>(Imm);
13190 }
13191
13192 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13193   // Can also use sub to handle negated immediates.
13194   return isInt<32>(Imm);
13195 }
13196
13197 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13198   if (!VT1.isInteger() || !VT2.isInteger())
13199     return false;
13200   unsigned NumBits1 = VT1.getSizeInBits();
13201   unsigned NumBits2 = VT2.getSizeInBits();
13202   return NumBits1 > NumBits2;
13203 }
13204
13205 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13206   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13207   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13208 }
13209
13210 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13211   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13212   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13213 }
13214
13215 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13216   EVT VT1 = Val.getValueType();
13217   if (isZExtFree(VT1, VT2))
13218     return true;
13219
13220   if (Val.getOpcode() != ISD::LOAD)
13221     return false;
13222
13223   if (!VT1.isSimple() || !VT1.isInteger() ||
13224       !VT2.isSimple() || !VT2.isInteger())
13225     return false;
13226
13227   switch (VT1.getSimpleVT().SimpleTy) {
13228   default: break;
13229   case MVT::i8:
13230   case MVT::i16:
13231   case MVT::i32:
13232     // X86 has 8, 16, and 32-bit zero-extending loads.
13233     return true;
13234   }
13235
13236   return false;
13237 }
13238
13239 bool
13240 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13241   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13242     return false;
13243
13244   VT = VT.getScalarType();
13245
13246   if (!VT.isSimple())
13247     return false;
13248
13249   switch (VT.getSimpleVT().SimpleTy) {
13250   case MVT::f32:
13251   case MVT::f64:
13252     return true;
13253   default:
13254     break;
13255   }
13256
13257   return false;
13258 }
13259
13260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13261   // i16 instructions are longer (0x66 prefix) and potentially slower.
13262   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13263 }
13264
13265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13268 /// are assumed to be legal.
13269 bool
13270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13271                                       EVT VT) const {
13272   // Very little shuffling can be done for 64-bit vectors right now.
13273   if (VT.getSizeInBits() == 64)
13274     return false;
13275
13276   // FIXME: pshufb, blends, shifts.
13277   return (VT.getVectorNumElements() == 2 ||
13278           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13279           isMOVLMask(M, VT) ||
13280           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13281           isPSHUFDMask(M, VT) ||
13282           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13283           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13284           isPALIGNRMask(M, VT, Subtarget) ||
13285           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13286           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13287           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13288           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13289 }
13290
13291 bool
13292 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13293                                           EVT VT) const {
13294   unsigned NumElts = VT.getVectorNumElements();
13295   // FIXME: This collection of masks seems suspect.
13296   if (NumElts == 2)
13297     return true;
13298   if (NumElts == 4 && VT.is128BitVector()) {
13299     return (isMOVLMask(Mask, VT)  ||
13300             isCommutedMOVLMask(Mask, VT, true) ||
13301             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13302             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13303   }
13304   return false;
13305 }
13306
13307 //===----------------------------------------------------------------------===//
13308 //                           X86 Scheduler Hooks
13309 //===----------------------------------------------------------------------===//
13310
13311 /// Utility function to emit xbegin specifying the start of an RTM region.
13312 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13313                                      const TargetInstrInfo *TII) {
13314   DebugLoc DL = MI->getDebugLoc();
13315
13316   const BasicBlock *BB = MBB->getBasicBlock();
13317   MachineFunction::iterator I = MBB;
13318   ++I;
13319
13320   // For the v = xbegin(), we generate
13321   //
13322   // thisMBB:
13323   //  xbegin sinkMBB
13324   //
13325   // mainMBB:
13326   //  eax = -1
13327   //
13328   // sinkMBB:
13329   //  v = eax
13330
13331   MachineBasicBlock *thisMBB = MBB;
13332   MachineFunction *MF = MBB->getParent();
13333   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13334   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13335   MF->insert(I, mainMBB);
13336   MF->insert(I, sinkMBB);
13337
13338   // Transfer the remainder of BB and its successor edges to sinkMBB.
13339   sinkMBB->splice(sinkMBB->begin(), MBB,
13340                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13341   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13342
13343   // thisMBB:
13344   //  xbegin sinkMBB
13345   //  # fallthrough to mainMBB
13346   //  # abortion to sinkMBB
13347   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13348   thisMBB->addSuccessor(mainMBB);
13349   thisMBB->addSuccessor(sinkMBB);
13350
13351   // mainMBB:
13352   //  EAX = -1
13353   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13354   mainMBB->addSuccessor(sinkMBB);
13355
13356   // sinkMBB:
13357   // EAX is live into the sinkMBB
13358   sinkMBB->addLiveIn(X86::EAX);
13359   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13360           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13361     .addReg(X86::EAX);
13362
13363   MI->eraseFromParent();
13364   return sinkMBB;
13365 }
13366
13367 // Get CMPXCHG opcode for the specified data type.
13368 static unsigned getCmpXChgOpcode(EVT VT) {
13369   switch (VT.getSimpleVT().SimpleTy) {
13370   case MVT::i8:  return X86::LCMPXCHG8;
13371   case MVT::i16: return X86::LCMPXCHG16;
13372   case MVT::i32: return X86::LCMPXCHG32;
13373   case MVT::i64: return X86::LCMPXCHG64;
13374   default:
13375     break;
13376   }
13377   llvm_unreachable("Invalid operand size!");
13378 }
13379
13380 // Get LOAD opcode for the specified data type.
13381 static unsigned getLoadOpcode(EVT VT) {
13382   switch (VT.getSimpleVT().SimpleTy) {
13383   case MVT::i8:  return X86::MOV8rm;
13384   case MVT::i16: return X86::MOV16rm;
13385   case MVT::i32: return X86::MOV32rm;
13386   case MVT::i64: return X86::MOV64rm;
13387   default:
13388     break;
13389   }
13390   llvm_unreachable("Invalid operand size!");
13391 }
13392
13393 // Get opcode of the non-atomic one from the specified atomic instruction.
13394 static unsigned getNonAtomicOpcode(unsigned Opc) {
13395   switch (Opc) {
13396   case X86::ATOMAND8:  return X86::AND8rr;
13397   case X86::ATOMAND16: return X86::AND16rr;
13398   case X86::ATOMAND32: return X86::AND32rr;
13399   case X86::ATOMAND64: return X86::AND64rr;
13400   case X86::ATOMOR8:   return X86::OR8rr;
13401   case X86::ATOMOR16:  return X86::OR16rr;
13402   case X86::ATOMOR32:  return X86::OR32rr;
13403   case X86::ATOMOR64:  return X86::OR64rr;
13404   case X86::ATOMXOR8:  return X86::XOR8rr;
13405   case X86::ATOMXOR16: return X86::XOR16rr;
13406   case X86::ATOMXOR32: return X86::XOR32rr;
13407   case X86::ATOMXOR64: return X86::XOR64rr;
13408   }
13409   llvm_unreachable("Unhandled atomic-load-op opcode!");
13410 }
13411
13412 // Get opcode of the non-atomic one from the specified atomic instruction with
13413 // extra opcode.
13414 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13415                                                unsigned &ExtraOpc) {
13416   switch (Opc) {
13417   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13418   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13419   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13420   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13421   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13422   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13423   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13424   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13425   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13426   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13427   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13428   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13429   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13430   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13431   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13432   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13433   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13434   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13435   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13436   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13437   }
13438   llvm_unreachable("Unhandled atomic-load-op opcode!");
13439 }
13440
13441 // Get opcode of the non-atomic one from the specified atomic instruction for
13442 // 64-bit data type on 32-bit target.
13443 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13444   switch (Opc) {
13445   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13446   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13447   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13448   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13449   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13450   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13451   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13452   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13453   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13454   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13455   }
13456   llvm_unreachable("Unhandled atomic-load-op opcode!");
13457 }
13458
13459 // Get opcode of the non-atomic one from the specified atomic instruction for
13460 // 64-bit data type on 32-bit target with extra opcode.
13461 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13462                                                    unsigned &HiOpc,
13463                                                    unsigned &ExtraOpc) {
13464   switch (Opc) {
13465   case X86::ATOMNAND6432:
13466     ExtraOpc = X86::NOT32r;
13467     HiOpc = X86::AND32rr;
13468     return X86::AND32rr;
13469   }
13470   llvm_unreachable("Unhandled atomic-load-op opcode!");
13471 }
13472
13473 // Get pseudo CMOV opcode from the specified data type.
13474 static unsigned getPseudoCMOVOpc(EVT VT) {
13475   switch (VT.getSimpleVT().SimpleTy) {
13476   case MVT::i8:  return X86::CMOV_GR8;
13477   case MVT::i16: return X86::CMOV_GR16;
13478   case MVT::i32: return X86::CMOV_GR32;
13479   default:
13480     break;
13481   }
13482   llvm_unreachable("Unknown CMOV opcode!");
13483 }
13484
13485 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13486 // They will be translated into a spin-loop or compare-exchange loop from
13487 //
13488 //    ...
13489 //    dst = atomic-fetch-op MI.addr, MI.val
13490 //    ...
13491 //
13492 // to
13493 //
13494 //    ...
13495 //    t1 = LOAD MI.addr
13496 // loop:
13497 //    t4 = phi(t1, t3 / loop)
13498 //    t2 = OP MI.val, t4
13499 //    EAX = t4
13500 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13501 //    t3 = EAX
13502 //    JNE loop
13503 // sink:
13504 //    dst = t3
13505 //    ...
13506 MachineBasicBlock *
13507 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13508                                        MachineBasicBlock *MBB) const {
13509   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13510   DebugLoc DL = MI->getDebugLoc();
13511
13512   MachineFunction *MF = MBB->getParent();
13513   MachineRegisterInfo &MRI = MF->getRegInfo();
13514
13515   const BasicBlock *BB = MBB->getBasicBlock();
13516   MachineFunction::iterator I = MBB;
13517   ++I;
13518
13519   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13520          "Unexpected number of operands");
13521
13522   assert(MI->hasOneMemOperand() &&
13523          "Expected atomic-load-op to have one memoperand");
13524
13525   // Memory Reference
13526   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13527   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13528
13529   unsigned DstReg, SrcReg;
13530   unsigned MemOpndSlot;
13531
13532   unsigned CurOp = 0;
13533
13534   DstReg = MI->getOperand(CurOp++).getReg();
13535   MemOpndSlot = CurOp;
13536   CurOp += X86::AddrNumOperands;
13537   SrcReg = MI->getOperand(CurOp++).getReg();
13538
13539   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13540   MVT::SimpleValueType VT = *RC->vt_begin();
13541   unsigned t1 = MRI.createVirtualRegister(RC);
13542   unsigned t2 = MRI.createVirtualRegister(RC);
13543   unsigned t3 = MRI.createVirtualRegister(RC);
13544   unsigned t4 = MRI.createVirtualRegister(RC);
13545   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13546
13547   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13548   unsigned LOADOpc = getLoadOpcode(VT);
13549
13550   // For the atomic load-arith operator, we generate
13551   //
13552   //  thisMBB:
13553   //    t1 = LOAD [MI.addr]
13554   //  mainMBB:
13555   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13556   //    t1 = OP MI.val, EAX
13557   //    EAX = t4
13558   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13559   //    t3 = EAX
13560   //    JNE mainMBB
13561   //  sinkMBB:
13562   //    dst = t3
13563
13564   MachineBasicBlock *thisMBB = MBB;
13565   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13566   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13567   MF->insert(I, mainMBB);
13568   MF->insert(I, sinkMBB);
13569
13570   MachineInstrBuilder MIB;
13571
13572   // Transfer the remainder of BB and its successor edges to sinkMBB.
13573   sinkMBB->splice(sinkMBB->begin(), MBB,
13574                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13575   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13576
13577   // thisMBB:
13578   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13579   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13580     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13581     if (NewMO.isReg())
13582       NewMO.setIsKill(false);
13583     MIB.addOperand(NewMO);
13584   }
13585   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13586     unsigned flags = (*MMOI)->getFlags();
13587     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13588     MachineMemOperand *MMO =
13589       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13590                                (*MMOI)->getSize(),
13591                                (*MMOI)->getBaseAlignment(),
13592                                (*MMOI)->getTBAAInfo(),
13593                                (*MMOI)->getRanges());
13594     MIB.addMemOperand(MMO);
13595   }
13596
13597   thisMBB->addSuccessor(mainMBB);
13598
13599   // mainMBB:
13600   MachineBasicBlock *origMainMBB = mainMBB;
13601
13602   // Add a PHI.
13603   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13604                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13605
13606   unsigned Opc = MI->getOpcode();
13607   switch (Opc) {
13608   default:
13609     llvm_unreachable("Unhandled atomic-load-op opcode!");
13610   case X86::ATOMAND8:
13611   case X86::ATOMAND16:
13612   case X86::ATOMAND32:
13613   case X86::ATOMAND64:
13614   case X86::ATOMOR8:
13615   case X86::ATOMOR16:
13616   case X86::ATOMOR32:
13617   case X86::ATOMOR64:
13618   case X86::ATOMXOR8:
13619   case X86::ATOMXOR16:
13620   case X86::ATOMXOR32:
13621   case X86::ATOMXOR64: {
13622     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13623     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13624       .addReg(t4);
13625     break;
13626   }
13627   case X86::ATOMNAND8:
13628   case X86::ATOMNAND16:
13629   case X86::ATOMNAND32:
13630   case X86::ATOMNAND64: {
13631     unsigned Tmp = MRI.createVirtualRegister(RC);
13632     unsigned NOTOpc;
13633     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13634     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13635       .addReg(t4);
13636     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13637     break;
13638   }
13639   case X86::ATOMMAX8:
13640   case X86::ATOMMAX16:
13641   case X86::ATOMMAX32:
13642   case X86::ATOMMAX64:
13643   case X86::ATOMMIN8:
13644   case X86::ATOMMIN16:
13645   case X86::ATOMMIN32:
13646   case X86::ATOMMIN64:
13647   case X86::ATOMUMAX8:
13648   case X86::ATOMUMAX16:
13649   case X86::ATOMUMAX32:
13650   case X86::ATOMUMAX64:
13651   case X86::ATOMUMIN8:
13652   case X86::ATOMUMIN16:
13653   case X86::ATOMUMIN32:
13654   case X86::ATOMUMIN64: {
13655     unsigned CMPOpc;
13656     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13657
13658     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13659       .addReg(SrcReg)
13660       .addReg(t4);
13661
13662     if (Subtarget->hasCMov()) {
13663       if (VT != MVT::i8) {
13664         // Native support
13665         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13666           .addReg(SrcReg)
13667           .addReg(t4);
13668       } else {
13669         // Promote i8 to i32 to use CMOV32
13670         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13671         const TargetRegisterClass *RC32 =
13672           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13673         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13674         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13675         unsigned Tmp = MRI.createVirtualRegister(RC32);
13676
13677         unsigned Undef = MRI.createVirtualRegister(RC32);
13678         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13679
13680         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13681           .addReg(Undef)
13682           .addReg(SrcReg)
13683           .addImm(X86::sub_8bit);
13684         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13685           .addReg(Undef)
13686           .addReg(t4)
13687           .addImm(X86::sub_8bit);
13688
13689         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13690           .addReg(SrcReg32)
13691           .addReg(AccReg32);
13692
13693         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13694           .addReg(Tmp, 0, X86::sub_8bit);
13695       }
13696     } else {
13697       // Use pseudo select and lower them.
13698       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13699              "Invalid atomic-load-op transformation!");
13700       unsigned SelOpc = getPseudoCMOVOpc(VT);
13701       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13702       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13703       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13704               .addReg(SrcReg).addReg(t4)
13705               .addImm(CC);
13706       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13707       // Replace the original PHI node as mainMBB is changed after CMOV
13708       // lowering.
13709       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13710         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13711       Phi->eraseFromParent();
13712     }
13713     break;
13714   }
13715   }
13716
13717   // Copy PhyReg back from virtual register.
13718   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13719     .addReg(t4);
13720
13721   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13722   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13723     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13724     if (NewMO.isReg())
13725       NewMO.setIsKill(false);
13726     MIB.addOperand(NewMO);
13727   }
13728   MIB.addReg(t2);
13729   MIB.setMemRefs(MMOBegin, MMOEnd);
13730
13731   // Copy PhyReg back to virtual register.
13732   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13733     .addReg(PhyReg);
13734
13735   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13736
13737   mainMBB->addSuccessor(origMainMBB);
13738   mainMBB->addSuccessor(sinkMBB);
13739
13740   // sinkMBB:
13741   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13742           TII->get(TargetOpcode::COPY), DstReg)
13743     .addReg(t3);
13744
13745   MI->eraseFromParent();
13746   return sinkMBB;
13747 }
13748
13749 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13750 // instructions. They will be translated into a spin-loop or compare-exchange
13751 // loop from
13752 //
13753 //    ...
13754 //    dst = atomic-fetch-op MI.addr, MI.val
13755 //    ...
13756 //
13757 // to
13758 //
13759 //    ...
13760 //    t1L = LOAD [MI.addr + 0]
13761 //    t1H = LOAD [MI.addr + 4]
13762 // loop:
13763 //    t4L = phi(t1L, t3L / loop)
13764 //    t4H = phi(t1H, t3H / loop)
13765 //    t2L = OP MI.val.lo, t4L
13766 //    t2H = OP MI.val.hi, t4H
13767 //    EAX = t4L
13768 //    EDX = t4H
13769 //    EBX = t2L
13770 //    ECX = t2H
13771 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13772 //    t3L = EAX
13773 //    t3H = EDX
13774 //    JNE loop
13775 // sink:
13776 //    dstL = t3L
13777 //    dstH = t3H
13778 //    ...
13779 MachineBasicBlock *
13780 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13781                                            MachineBasicBlock *MBB) const {
13782   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13783   DebugLoc DL = MI->getDebugLoc();
13784
13785   MachineFunction *MF = MBB->getParent();
13786   MachineRegisterInfo &MRI = MF->getRegInfo();
13787
13788   const BasicBlock *BB = MBB->getBasicBlock();
13789   MachineFunction::iterator I = MBB;
13790   ++I;
13791
13792   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13793          "Unexpected number of operands");
13794
13795   assert(MI->hasOneMemOperand() &&
13796          "Expected atomic-load-op32 to have one memoperand");
13797
13798   // Memory Reference
13799   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13800   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13801
13802   unsigned DstLoReg, DstHiReg;
13803   unsigned SrcLoReg, SrcHiReg;
13804   unsigned MemOpndSlot;
13805
13806   unsigned CurOp = 0;
13807
13808   DstLoReg = MI->getOperand(CurOp++).getReg();
13809   DstHiReg = MI->getOperand(CurOp++).getReg();
13810   MemOpndSlot = CurOp;
13811   CurOp += X86::AddrNumOperands;
13812   SrcLoReg = MI->getOperand(CurOp++).getReg();
13813   SrcHiReg = MI->getOperand(CurOp++).getReg();
13814
13815   const TargetRegisterClass *RC = &X86::GR32RegClass;
13816   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13817
13818   unsigned t1L = MRI.createVirtualRegister(RC);
13819   unsigned t1H = MRI.createVirtualRegister(RC);
13820   unsigned t2L = MRI.createVirtualRegister(RC);
13821   unsigned t2H = MRI.createVirtualRegister(RC);
13822   unsigned t3L = MRI.createVirtualRegister(RC);
13823   unsigned t3H = MRI.createVirtualRegister(RC);
13824   unsigned t4L = MRI.createVirtualRegister(RC);
13825   unsigned t4H = MRI.createVirtualRegister(RC);
13826
13827   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13828   unsigned LOADOpc = X86::MOV32rm;
13829
13830   // For the atomic load-arith operator, we generate
13831   //
13832   //  thisMBB:
13833   //    t1L = LOAD [MI.addr + 0]
13834   //    t1H = LOAD [MI.addr + 4]
13835   //  mainMBB:
13836   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13837   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13838   //    t2L = OP MI.val.lo, t4L
13839   //    t2H = OP MI.val.hi, t4H
13840   //    EBX = t2L
13841   //    ECX = t2H
13842   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13843   //    t3L = EAX
13844   //    t3H = EDX
13845   //    JNE loop
13846   //  sinkMBB:
13847   //    dstL = t3L
13848   //    dstH = t3H
13849
13850   MachineBasicBlock *thisMBB = MBB;
13851   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13852   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13853   MF->insert(I, mainMBB);
13854   MF->insert(I, sinkMBB);
13855
13856   MachineInstrBuilder MIB;
13857
13858   // Transfer the remainder of BB and its successor edges to sinkMBB.
13859   sinkMBB->splice(sinkMBB->begin(), MBB,
13860                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13861   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13862
13863   // thisMBB:
13864   // Lo
13865   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13866   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13867     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13868     if (NewMO.isReg())
13869       NewMO.setIsKill(false);
13870     MIB.addOperand(NewMO);
13871   }
13872   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13873     unsigned flags = (*MMOI)->getFlags();
13874     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13875     MachineMemOperand *MMO =
13876       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13877                                (*MMOI)->getSize(),
13878                                (*MMOI)->getBaseAlignment(),
13879                                (*MMOI)->getTBAAInfo(),
13880                                (*MMOI)->getRanges());
13881     MIB.addMemOperand(MMO);
13882   };
13883   MachineInstr *LowMI = MIB;
13884
13885   // Hi
13886   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13887   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13888     if (i == X86::AddrDisp) {
13889       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13890     } else {
13891       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13892       if (NewMO.isReg())
13893         NewMO.setIsKill(false);
13894       MIB.addOperand(NewMO);
13895     }
13896   }
13897   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13898
13899   thisMBB->addSuccessor(mainMBB);
13900
13901   // mainMBB:
13902   MachineBasicBlock *origMainMBB = mainMBB;
13903
13904   // Add PHIs.
13905   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13906                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13907   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13908                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13909
13910   unsigned Opc = MI->getOpcode();
13911   switch (Opc) {
13912   default:
13913     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13914   case X86::ATOMAND6432:
13915   case X86::ATOMOR6432:
13916   case X86::ATOMXOR6432:
13917   case X86::ATOMADD6432:
13918   case X86::ATOMSUB6432: {
13919     unsigned HiOpc;
13920     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13921     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13922       .addReg(SrcLoReg);
13923     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13924       .addReg(SrcHiReg);
13925     break;
13926   }
13927   case X86::ATOMNAND6432: {
13928     unsigned HiOpc, NOTOpc;
13929     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13930     unsigned TmpL = MRI.createVirtualRegister(RC);
13931     unsigned TmpH = MRI.createVirtualRegister(RC);
13932     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13933       .addReg(t4L);
13934     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13935       .addReg(t4H);
13936     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13937     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13938     break;
13939   }
13940   case X86::ATOMMAX6432:
13941   case X86::ATOMMIN6432:
13942   case X86::ATOMUMAX6432:
13943   case X86::ATOMUMIN6432: {
13944     unsigned HiOpc;
13945     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13946     unsigned cL = MRI.createVirtualRegister(RC8);
13947     unsigned cH = MRI.createVirtualRegister(RC8);
13948     unsigned cL32 = MRI.createVirtualRegister(RC);
13949     unsigned cH32 = MRI.createVirtualRegister(RC);
13950     unsigned cc = MRI.createVirtualRegister(RC);
13951     // cl := cmp src_lo, lo
13952     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13953       .addReg(SrcLoReg).addReg(t4L);
13954     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13955     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13956     // ch := cmp src_hi, hi
13957     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13958       .addReg(SrcHiReg).addReg(t4H);
13959     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13960     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13961     // cc := if (src_hi == hi) ? cl : ch;
13962     if (Subtarget->hasCMov()) {
13963       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13964         .addReg(cH32).addReg(cL32);
13965     } else {
13966       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13967               .addReg(cH32).addReg(cL32)
13968               .addImm(X86::COND_E);
13969       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13970     }
13971     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13972     if (Subtarget->hasCMov()) {
13973       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13974         .addReg(SrcLoReg).addReg(t4L);
13975       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13976         .addReg(SrcHiReg).addReg(t4H);
13977     } else {
13978       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13979               .addReg(SrcLoReg).addReg(t4L)
13980               .addImm(X86::COND_NE);
13981       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13982       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13983       // 2nd CMOV lowering.
13984       mainMBB->addLiveIn(X86::EFLAGS);
13985       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13986               .addReg(SrcHiReg).addReg(t4H)
13987               .addImm(X86::COND_NE);
13988       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13989       // Replace the original PHI node as mainMBB is changed after CMOV
13990       // lowering.
13991       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13992         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13993       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13994         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13995       PhiL->eraseFromParent();
13996       PhiH->eraseFromParent();
13997     }
13998     break;
13999   }
14000   case X86::ATOMSWAP6432: {
14001     unsigned HiOpc;
14002     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14003     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14004     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14005     break;
14006   }
14007   }
14008
14009   // Copy EDX:EAX back from HiReg:LoReg
14010   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14011   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14012   // Copy ECX:EBX from t1H:t1L
14013   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14014   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14015
14016   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14017   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14018     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14019     if (NewMO.isReg())
14020       NewMO.setIsKill(false);
14021     MIB.addOperand(NewMO);
14022   }
14023   MIB.setMemRefs(MMOBegin, MMOEnd);
14024
14025   // Copy EDX:EAX back to t3H:t3L
14026   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14027   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14028
14029   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14030
14031   mainMBB->addSuccessor(origMainMBB);
14032   mainMBB->addSuccessor(sinkMBB);
14033
14034   // sinkMBB:
14035   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14036           TII->get(TargetOpcode::COPY), DstLoReg)
14037     .addReg(t3L);
14038   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14039           TII->get(TargetOpcode::COPY), DstHiReg)
14040     .addReg(t3H);
14041
14042   MI->eraseFromParent();
14043   return sinkMBB;
14044 }
14045
14046 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14047 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14048 // in the .td file.
14049 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14050                                        const TargetInstrInfo *TII) {
14051   unsigned Opc;
14052   switch (MI->getOpcode()) {
14053   default: llvm_unreachable("illegal opcode!");
14054   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14055   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14056   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14057   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14058   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14059   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14060   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14061   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14062   }
14063
14064   DebugLoc dl = MI->getDebugLoc();
14065   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14066
14067   unsigned NumArgs = MI->getNumOperands();
14068   for (unsigned i = 1; i < NumArgs; ++i) {
14069     MachineOperand &Op = MI->getOperand(i);
14070     if (!(Op.isReg() && Op.isImplicit()))
14071       MIB.addOperand(Op);
14072   }
14073   if (MI->hasOneMemOperand())
14074     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14075
14076   BuildMI(*BB, MI, dl,
14077     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14078     .addReg(X86::XMM0);
14079
14080   MI->eraseFromParent();
14081   return BB;
14082 }
14083
14084 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14085 // defs in an instruction pattern
14086 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14087                                        const TargetInstrInfo *TII) {
14088   unsigned Opc;
14089   switch (MI->getOpcode()) {
14090   default: llvm_unreachable("illegal opcode!");
14091   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14092   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14093   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14094   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14095   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14096   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14097   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14098   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14099   }
14100
14101   DebugLoc dl = MI->getDebugLoc();
14102   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14103
14104   unsigned NumArgs = MI->getNumOperands(); // remove the results
14105   for (unsigned i = 1; i < NumArgs; ++i) {
14106     MachineOperand &Op = MI->getOperand(i);
14107     if (!(Op.isReg() && Op.isImplicit()))
14108       MIB.addOperand(Op);
14109   }
14110   if (MI->hasOneMemOperand())
14111     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14112
14113   BuildMI(*BB, MI, dl,
14114     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14115     .addReg(X86::ECX);
14116
14117   MI->eraseFromParent();
14118   return BB;
14119 }
14120
14121 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14122                                        const TargetInstrInfo *TII,
14123                                        const X86Subtarget* Subtarget) {
14124   DebugLoc dl = MI->getDebugLoc();
14125
14126   // Address into RAX/EAX, other two args into ECX, EDX.
14127   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14128   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14129   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14130   for (int i = 0; i < X86::AddrNumOperands; ++i)
14131     MIB.addOperand(MI->getOperand(i));
14132
14133   unsigned ValOps = X86::AddrNumOperands;
14134   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14135     .addReg(MI->getOperand(ValOps).getReg());
14136   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14137     .addReg(MI->getOperand(ValOps+1).getReg());
14138
14139   // The instruction doesn't actually take any operands though.
14140   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14141
14142   MI->eraseFromParent(); // The pseudo is gone now.
14143   return BB;
14144 }
14145
14146 MachineBasicBlock *
14147 X86TargetLowering::EmitVAARG64WithCustomInserter(
14148                    MachineInstr *MI,
14149                    MachineBasicBlock *MBB) const {
14150   // Emit va_arg instruction on X86-64.
14151
14152   // Operands to this pseudo-instruction:
14153   // 0  ) Output        : destination address (reg)
14154   // 1-5) Input         : va_list address (addr, i64mem)
14155   // 6  ) ArgSize       : Size (in bytes) of vararg type
14156   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14157   // 8  ) Align         : Alignment of type
14158   // 9  ) EFLAGS (implicit-def)
14159
14160   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14161   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14162
14163   unsigned DestReg = MI->getOperand(0).getReg();
14164   MachineOperand &Base = MI->getOperand(1);
14165   MachineOperand &Scale = MI->getOperand(2);
14166   MachineOperand &Index = MI->getOperand(3);
14167   MachineOperand &Disp = MI->getOperand(4);
14168   MachineOperand &Segment = MI->getOperand(5);
14169   unsigned ArgSize = MI->getOperand(6).getImm();
14170   unsigned ArgMode = MI->getOperand(7).getImm();
14171   unsigned Align = MI->getOperand(8).getImm();
14172
14173   // Memory Reference
14174   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14175   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14176   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14177
14178   // Machine Information
14179   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14180   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14181   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14182   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14183   DebugLoc DL = MI->getDebugLoc();
14184
14185   // struct va_list {
14186   //   i32   gp_offset
14187   //   i32   fp_offset
14188   //   i64   overflow_area (address)
14189   //   i64   reg_save_area (address)
14190   // }
14191   // sizeof(va_list) = 24
14192   // alignment(va_list) = 8
14193
14194   unsigned TotalNumIntRegs = 6;
14195   unsigned TotalNumXMMRegs = 8;
14196   bool UseGPOffset = (ArgMode == 1);
14197   bool UseFPOffset = (ArgMode == 2);
14198   unsigned MaxOffset = TotalNumIntRegs * 8 +
14199                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14200
14201   /* Align ArgSize to a multiple of 8 */
14202   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14203   bool NeedsAlign = (Align > 8);
14204
14205   MachineBasicBlock *thisMBB = MBB;
14206   MachineBasicBlock *overflowMBB;
14207   MachineBasicBlock *offsetMBB;
14208   MachineBasicBlock *endMBB;
14209
14210   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14211   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14212   unsigned OffsetReg = 0;
14213
14214   if (!UseGPOffset && !UseFPOffset) {
14215     // If we only pull from the overflow region, we don't create a branch.
14216     // We don't need to alter control flow.
14217     OffsetDestReg = 0; // unused
14218     OverflowDestReg = DestReg;
14219
14220     offsetMBB = NULL;
14221     overflowMBB = thisMBB;
14222     endMBB = thisMBB;
14223   } else {
14224     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14225     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14226     // If not, pull from overflow_area. (branch to overflowMBB)
14227     //
14228     //       thisMBB
14229     //         |     .
14230     //         |        .
14231     //     offsetMBB   overflowMBB
14232     //         |        .
14233     //         |     .
14234     //        endMBB
14235
14236     // Registers for the PHI in endMBB
14237     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14238     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14239
14240     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14241     MachineFunction *MF = MBB->getParent();
14242     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14243     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14244     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14245
14246     MachineFunction::iterator MBBIter = MBB;
14247     ++MBBIter;
14248
14249     // Insert the new basic blocks
14250     MF->insert(MBBIter, offsetMBB);
14251     MF->insert(MBBIter, overflowMBB);
14252     MF->insert(MBBIter, endMBB);
14253
14254     // Transfer the remainder of MBB and its successor edges to endMBB.
14255     endMBB->splice(endMBB->begin(), thisMBB,
14256                     llvm::next(MachineBasicBlock::iterator(MI)),
14257                     thisMBB->end());
14258     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14259
14260     // Make offsetMBB and overflowMBB successors of thisMBB
14261     thisMBB->addSuccessor(offsetMBB);
14262     thisMBB->addSuccessor(overflowMBB);
14263
14264     // endMBB is a successor of both offsetMBB and overflowMBB
14265     offsetMBB->addSuccessor(endMBB);
14266     overflowMBB->addSuccessor(endMBB);
14267
14268     // Load the offset value into a register
14269     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14270     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14271       .addOperand(Base)
14272       .addOperand(Scale)
14273       .addOperand(Index)
14274       .addDisp(Disp, UseFPOffset ? 4 : 0)
14275       .addOperand(Segment)
14276       .setMemRefs(MMOBegin, MMOEnd);
14277
14278     // Check if there is enough room left to pull this argument.
14279     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14280       .addReg(OffsetReg)
14281       .addImm(MaxOffset + 8 - ArgSizeA8);
14282
14283     // Branch to "overflowMBB" if offset >= max
14284     // Fall through to "offsetMBB" otherwise
14285     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14286       .addMBB(overflowMBB);
14287   }
14288
14289   // In offsetMBB, emit code to use the reg_save_area.
14290   if (offsetMBB) {
14291     assert(OffsetReg != 0);
14292
14293     // Read the reg_save_area address.
14294     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14295     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14296       .addOperand(Base)
14297       .addOperand(Scale)
14298       .addOperand(Index)
14299       .addDisp(Disp, 16)
14300       .addOperand(Segment)
14301       .setMemRefs(MMOBegin, MMOEnd);
14302
14303     // Zero-extend the offset
14304     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14305       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14306         .addImm(0)
14307         .addReg(OffsetReg)
14308         .addImm(X86::sub_32bit);
14309
14310     // Add the offset to the reg_save_area to get the final address.
14311     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14312       .addReg(OffsetReg64)
14313       .addReg(RegSaveReg);
14314
14315     // Compute the offset for the next argument
14316     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14317     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14318       .addReg(OffsetReg)
14319       .addImm(UseFPOffset ? 16 : 8);
14320
14321     // Store it back into the va_list.
14322     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14323       .addOperand(Base)
14324       .addOperand(Scale)
14325       .addOperand(Index)
14326       .addDisp(Disp, UseFPOffset ? 4 : 0)
14327       .addOperand(Segment)
14328       .addReg(NextOffsetReg)
14329       .setMemRefs(MMOBegin, MMOEnd);
14330
14331     // Jump to endMBB
14332     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14333       .addMBB(endMBB);
14334   }
14335
14336   //
14337   // Emit code to use overflow area
14338   //
14339
14340   // Load the overflow_area address into a register.
14341   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14342   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14343     .addOperand(Base)
14344     .addOperand(Scale)
14345     .addOperand(Index)
14346     .addDisp(Disp, 8)
14347     .addOperand(Segment)
14348     .setMemRefs(MMOBegin, MMOEnd);
14349
14350   // If we need to align it, do so. Otherwise, just copy the address
14351   // to OverflowDestReg.
14352   if (NeedsAlign) {
14353     // Align the overflow address
14354     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14355     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14356
14357     // aligned_addr = (addr + (align-1)) & ~(align-1)
14358     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14359       .addReg(OverflowAddrReg)
14360       .addImm(Align-1);
14361
14362     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14363       .addReg(TmpReg)
14364       .addImm(~(uint64_t)(Align-1));
14365   } else {
14366     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14367       .addReg(OverflowAddrReg);
14368   }
14369
14370   // Compute the next overflow address after this argument.
14371   // (the overflow address should be kept 8-byte aligned)
14372   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14373   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14374     .addReg(OverflowDestReg)
14375     .addImm(ArgSizeA8);
14376
14377   // Store the new overflow address.
14378   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14379     .addOperand(Base)
14380     .addOperand(Scale)
14381     .addOperand(Index)
14382     .addDisp(Disp, 8)
14383     .addOperand(Segment)
14384     .addReg(NextAddrReg)
14385     .setMemRefs(MMOBegin, MMOEnd);
14386
14387   // If we branched, emit the PHI to the front of endMBB.
14388   if (offsetMBB) {
14389     BuildMI(*endMBB, endMBB->begin(), DL,
14390             TII->get(X86::PHI), DestReg)
14391       .addReg(OffsetDestReg).addMBB(offsetMBB)
14392       .addReg(OverflowDestReg).addMBB(overflowMBB);
14393   }
14394
14395   // Erase the pseudo instruction
14396   MI->eraseFromParent();
14397
14398   return endMBB;
14399 }
14400
14401 MachineBasicBlock *
14402 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14403                                                  MachineInstr *MI,
14404                                                  MachineBasicBlock *MBB) const {
14405   // Emit code to save XMM registers to the stack. The ABI says that the
14406   // number of registers to save is given in %al, so it's theoretically
14407   // possible to do an indirect jump trick to avoid saving all of them,
14408   // however this code takes a simpler approach and just executes all
14409   // of the stores if %al is non-zero. It's less code, and it's probably
14410   // easier on the hardware branch predictor, and stores aren't all that
14411   // expensive anyway.
14412
14413   // Create the new basic blocks. One block contains all the XMM stores,
14414   // and one block is the final destination regardless of whether any
14415   // stores were performed.
14416   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14417   MachineFunction *F = MBB->getParent();
14418   MachineFunction::iterator MBBIter = MBB;
14419   ++MBBIter;
14420   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14421   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14422   F->insert(MBBIter, XMMSaveMBB);
14423   F->insert(MBBIter, EndMBB);
14424
14425   // Transfer the remainder of MBB and its successor edges to EndMBB.
14426   EndMBB->splice(EndMBB->begin(), MBB,
14427                  llvm::next(MachineBasicBlock::iterator(MI)),
14428                  MBB->end());
14429   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14430
14431   // The original block will now fall through to the XMM save block.
14432   MBB->addSuccessor(XMMSaveMBB);
14433   // The XMMSaveMBB will fall through to the end block.
14434   XMMSaveMBB->addSuccessor(EndMBB);
14435
14436   // Now add the instructions.
14437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14438   DebugLoc DL = MI->getDebugLoc();
14439
14440   unsigned CountReg = MI->getOperand(0).getReg();
14441   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14442   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14443
14444   if (!Subtarget->isTargetWin64()) {
14445     // If %al is 0, branch around the XMM save block.
14446     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14447     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14448     MBB->addSuccessor(EndMBB);
14449   }
14450
14451   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14452   // In the XMM save block, save all the XMM argument registers.
14453   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14454     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14455     MachineMemOperand *MMO =
14456       F->getMachineMemOperand(
14457           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14458         MachineMemOperand::MOStore,
14459         /*Size=*/16, /*Align=*/16);
14460     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14461       .addFrameIndex(RegSaveFrameIndex)
14462       .addImm(/*Scale=*/1)
14463       .addReg(/*IndexReg=*/0)
14464       .addImm(/*Disp=*/Offset)
14465       .addReg(/*Segment=*/0)
14466       .addReg(MI->getOperand(i).getReg())
14467       .addMemOperand(MMO);
14468   }
14469
14470   MI->eraseFromParent();   // The pseudo instruction is gone now.
14471
14472   return EndMBB;
14473 }
14474
14475 // The EFLAGS operand of SelectItr might be missing a kill marker
14476 // because there were multiple uses of EFLAGS, and ISel didn't know
14477 // which to mark. Figure out whether SelectItr should have had a
14478 // kill marker, and set it if it should. Returns the correct kill
14479 // marker value.
14480 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14481                                      MachineBasicBlock* BB,
14482                                      const TargetRegisterInfo* TRI) {
14483   // Scan forward through BB for a use/def of EFLAGS.
14484   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14485   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14486     const MachineInstr& mi = *miI;
14487     if (mi.readsRegister(X86::EFLAGS))
14488       return false;
14489     if (mi.definesRegister(X86::EFLAGS))
14490       break; // Should have kill-flag - update below.
14491   }
14492
14493   // If we hit the end of the block, check whether EFLAGS is live into a
14494   // successor.
14495   if (miI == BB->end()) {
14496     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14497                                           sEnd = BB->succ_end();
14498          sItr != sEnd; ++sItr) {
14499       MachineBasicBlock* succ = *sItr;
14500       if (succ->isLiveIn(X86::EFLAGS))
14501         return false;
14502     }
14503   }
14504
14505   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14506   // out. SelectMI should have a kill flag on EFLAGS.
14507   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14508   return true;
14509 }
14510
14511 MachineBasicBlock *
14512 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14513                                      MachineBasicBlock *BB) const {
14514   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14515   DebugLoc DL = MI->getDebugLoc();
14516
14517   // To "insert" a SELECT_CC instruction, we actually have to insert the
14518   // diamond control-flow pattern.  The incoming instruction knows the
14519   // destination vreg to set, the condition code register to branch on, the
14520   // true/false values to select between, and a branch opcode to use.
14521   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14522   MachineFunction::iterator It = BB;
14523   ++It;
14524
14525   //  thisMBB:
14526   //  ...
14527   //   TrueVal = ...
14528   //   cmpTY ccX, r1, r2
14529   //   bCC copy1MBB
14530   //   fallthrough --> copy0MBB
14531   MachineBasicBlock *thisMBB = BB;
14532   MachineFunction *F = BB->getParent();
14533   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14534   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14535   F->insert(It, copy0MBB);
14536   F->insert(It, sinkMBB);
14537
14538   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14539   // live into the sink and copy blocks.
14540   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14541   if (!MI->killsRegister(X86::EFLAGS) &&
14542       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14543     copy0MBB->addLiveIn(X86::EFLAGS);
14544     sinkMBB->addLiveIn(X86::EFLAGS);
14545   }
14546
14547   // Transfer the remainder of BB and its successor edges to sinkMBB.
14548   sinkMBB->splice(sinkMBB->begin(), BB,
14549                   llvm::next(MachineBasicBlock::iterator(MI)),
14550                   BB->end());
14551   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14552
14553   // Add the true and fallthrough blocks as its successors.
14554   BB->addSuccessor(copy0MBB);
14555   BB->addSuccessor(sinkMBB);
14556
14557   // Create the conditional branch instruction.
14558   unsigned Opc =
14559     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14560   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14561
14562   //  copy0MBB:
14563   //   %FalseValue = ...
14564   //   # fallthrough to sinkMBB
14565   copy0MBB->addSuccessor(sinkMBB);
14566
14567   //  sinkMBB:
14568   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14569   //  ...
14570   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14571           TII->get(X86::PHI), MI->getOperand(0).getReg())
14572     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14573     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14574
14575   MI->eraseFromParent();   // The pseudo instruction is gone now.
14576   return sinkMBB;
14577 }
14578
14579 MachineBasicBlock *
14580 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14581                                         bool Is64Bit) const {
14582   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14583   DebugLoc DL = MI->getDebugLoc();
14584   MachineFunction *MF = BB->getParent();
14585   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14586
14587   assert(getTargetMachine().Options.EnableSegmentedStacks);
14588
14589   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14590   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14591
14592   // BB:
14593   //  ... [Till the alloca]
14594   // If stacklet is not large enough, jump to mallocMBB
14595   //
14596   // bumpMBB:
14597   //  Allocate by subtracting from RSP
14598   //  Jump to continueMBB
14599   //
14600   // mallocMBB:
14601   //  Allocate by call to runtime
14602   //
14603   // continueMBB:
14604   //  ...
14605   //  [rest of original BB]
14606   //
14607
14608   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14609   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14610   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14611
14612   MachineRegisterInfo &MRI = MF->getRegInfo();
14613   const TargetRegisterClass *AddrRegClass =
14614     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14615
14616   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14617     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14618     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14619     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14620     sizeVReg = MI->getOperand(1).getReg(),
14621     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14622
14623   MachineFunction::iterator MBBIter = BB;
14624   ++MBBIter;
14625
14626   MF->insert(MBBIter, bumpMBB);
14627   MF->insert(MBBIter, mallocMBB);
14628   MF->insert(MBBIter, continueMBB);
14629
14630   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14631                       (MachineBasicBlock::iterator(MI)), BB->end());
14632   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14633
14634   // Add code to the main basic block to check if the stack limit has been hit,
14635   // and if so, jump to mallocMBB otherwise to bumpMBB.
14636   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14637   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14638     .addReg(tmpSPVReg).addReg(sizeVReg);
14639   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14640     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14641     .addReg(SPLimitVReg);
14642   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14643
14644   // bumpMBB simply decreases the stack pointer, since we know the current
14645   // stacklet has enough space.
14646   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14647     .addReg(SPLimitVReg);
14648   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14649     .addReg(SPLimitVReg);
14650   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14651
14652   // Calls into a routine in libgcc to allocate more space from the heap.
14653   const uint32_t *RegMask =
14654     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14655   if (Is64Bit) {
14656     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14657       .addReg(sizeVReg);
14658     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14659       .addExternalSymbol("__morestack_allocate_stack_space")
14660       .addRegMask(RegMask)
14661       .addReg(X86::RDI, RegState::Implicit)
14662       .addReg(X86::RAX, RegState::ImplicitDefine);
14663   } else {
14664     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14665       .addImm(12);
14666     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14667     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14668       .addExternalSymbol("__morestack_allocate_stack_space")
14669       .addRegMask(RegMask)
14670       .addReg(X86::EAX, RegState::ImplicitDefine);
14671   }
14672
14673   if (!Is64Bit)
14674     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14675       .addImm(16);
14676
14677   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14678     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14679   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14680
14681   // Set up the CFG correctly.
14682   BB->addSuccessor(bumpMBB);
14683   BB->addSuccessor(mallocMBB);
14684   mallocMBB->addSuccessor(continueMBB);
14685   bumpMBB->addSuccessor(continueMBB);
14686
14687   // Take care of the PHI nodes.
14688   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14689           MI->getOperand(0).getReg())
14690     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14691     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14692
14693   // Delete the original pseudo instruction.
14694   MI->eraseFromParent();
14695
14696   // And we're done.
14697   return continueMBB;
14698 }
14699
14700 MachineBasicBlock *
14701 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14702                                           MachineBasicBlock *BB) const {
14703   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14704   DebugLoc DL = MI->getDebugLoc();
14705
14706   assert(!Subtarget->isTargetEnvMacho());
14707
14708   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14709   // non-trivial part is impdef of ESP.
14710
14711   if (Subtarget->isTargetWin64()) {
14712     if (Subtarget->isTargetCygMing()) {
14713       // ___chkstk(Mingw64):
14714       // Clobbers R10, R11, RAX and EFLAGS.
14715       // Updates RSP.
14716       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14717         .addExternalSymbol("___chkstk")
14718         .addReg(X86::RAX, RegState::Implicit)
14719         .addReg(X86::RSP, RegState::Implicit)
14720         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14721         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14722         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14723     } else {
14724       // __chkstk(MSVCRT): does not update stack pointer.
14725       // Clobbers R10, R11 and EFLAGS.
14726       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14727         .addExternalSymbol("__chkstk")
14728         .addReg(X86::RAX, RegState::Implicit)
14729         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14730       // RAX has the offset to be subtracted from RSP.
14731       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14732         .addReg(X86::RSP)
14733         .addReg(X86::RAX);
14734     }
14735   } else {
14736     const char *StackProbeSymbol =
14737       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14738
14739     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14740       .addExternalSymbol(StackProbeSymbol)
14741       .addReg(X86::EAX, RegState::Implicit)
14742       .addReg(X86::ESP, RegState::Implicit)
14743       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14744       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14745       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14746   }
14747
14748   MI->eraseFromParent();   // The pseudo instruction is gone now.
14749   return BB;
14750 }
14751
14752 MachineBasicBlock *
14753 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14754                                       MachineBasicBlock *BB) const {
14755   // This is pretty easy.  We're taking the value that we received from
14756   // our load from the relocation, sticking it in either RDI (x86-64)
14757   // or EAX and doing an indirect call.  The return value will then
14758   // be in the normal return register.
14759   const X86InstrInfo *TII
14760     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14761   DebugLoc DL = MI->getDebugLoc();
14762   MachineFunction *F = BB->getParent();
14763
14764   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14765   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14766
14767   // Get a register mask for the lowered call.
14768   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14769   // proper register mask.
14770   const uint32_t *RegMask =
14771     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14772   if (Subtarget->is64Bit()) {
14773     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14774                                       TII->get(X86::MOV64rm), X86::RDI)
14775     .addReg(X86::RIP)
14776     .addImm(0).addReg(0)
14777     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14778                       MI->getOperand(3).getTargetFlags())
14779     .addReg(0);
14780     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14781     addDirectMem(MIB, X86::RDI);
14782     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14783   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14784     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14785                                       TII->get(X86::MOV32rm), X86::EAX)
14786     .addReg(0)
14787     .addImm(0).addReg(0)
14788     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14789                       MI->getOperand(3).getTargetFlags())
14790     .addReg(0);
14791     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14792     addDirectMem(MIB, X86::EAX);
14793     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14794   } else {
14795     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14796                                       TII->get(X86::MOV32rm), X86::EAX)
14797     .addReg(TII->getGlobalBaseReg(F))
14798     .addImm(0).addReg(0)
14799     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14800                       MI->getOperand(3).getTargetFlags())
14801     .addReg(0);
14802     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14803     addDirectMem(MIB, X86::EAX);
14804     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14805   }
14806
14807   MI->eraseFromParent(); // The pseudo instruction is gone now.
14808   return BB;
14809 }
14810
14811 MachineBasicBlock *
14812 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14813                                     MachineBasicBlock *MBB) const {
14814   DebugLoc DL = MI->getDebugLoc();
14815   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14816
14817   MachineFunction *MF = MBB->getParent();
14818   MachineRegisterInfo &MRI = MF->getRegInfo();
14819
14820   const BasicBlock *BB = MBB->getBasicBlock();
14821   MachineFunction::iterator I = MBB;
14822   ++I;
14823
14824   // Memory Reference
14825   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14826   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14827
14828   unsigned DstReg;
14829   unsigned MemOpndSlot = 0;
14830
14831   unsigned CurOp = 0;
14832
14833   DstReg = MI->getOperand(CurOp++).getReg();
14834   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14835   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14836   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14837   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14838
14839   MemOpndSlot = CurOp;
14840
14841   MVT PVT = getPointerTy();
14842   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14843          "Invalid Pointer Size!");
14844
14845   // For v = setjmp(buf), we generate
14846   //
14847   // thisMBB:
14848   //  buf[LabelOffset] = restoreMBB
14849   //  SjLjSetup restoreMBB
14850   //
14851   // mainMBB:
14852   //  v_main = 0
14853   //
14854   // sinkMBB:
14855   //  v = phi(main, restore)
14856   //
14857   // restoreMBB:
14858   //  v_restore = 1
14859
14860   MachineBasicBlock *thisMBB = MBB;
14861   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14862   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14863   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14864   MF->insert(I, mainMBB);
14865   MF->insert(I, sinkMBB);
14866   MF->push_back(restoreMBB);
14867
14868   MachineInstrBuilder MIB;
14869
14870   // Transfer the remainder of BB and its successor edges to sinkMBB.
14871   sinkMBB->splice(sinkMBB->begin(), MBB,
14872                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14873   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14874
14875   // thisMBB:
14876   unsigned PtrStoreOpc = 0;
14877   unsigned LabelReg = 0;
14878   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14879   Reloc::Model RM = getTargetMachine().getRelocationModel();
14880   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14881                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14882
14883   // Prepare IP either in reg or imm.
14884   if (!UseImmLabel) {
14885     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14886     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14887     LabelReg = MRI.createVirtualRegister(PtrRC);
14888     if (Subtarget->is64Bit()) {
14889       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14890               .addReg(X86::RIP)
14891               .addImm(0)
14892               .addReg(0)
14893               .addMBB(restoreMBB)
14894               .addReg(0);
14895     } else {
14896       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14897       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14898               .addReg(XII->getGlobalBaseReg(MF))
14899               .addImm(0)
14900               .addReg(0)
14901               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14902               .addReg(0);
14903     }
14904   } else
14905     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14906   // Store IP
14907   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14908   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14909     if (i == X86::AddrDisp)
14910       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14911     else
14912       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14913   }
14914   if (!UseImmLabel)
14915     MIB.addReg(LabelReg);
14916   else
14917     MIB.addMBB(restoreMBB);
14918   MIB.setMemRefs(MMOBegin, MMOEnd);
14919   // Setup
14920   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14921           .addMBB(restoreMBB);
14922
14923   const X86RegisterInfo *RegInfo =
14924     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14925   MIB.addRegMask(RegInfo->getNoPreservedMask());
14926   thisMBB->addSuccessor(mainMBB);
14927   thisMBB->addSuccessor(restoreMBB);
14928
14929   // mainMBB:
14930   //  EAX = 0
14931   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14932   mainMBB->addSuccessor(sinkMBB);
14933
14934   // sinkMBB:
14935   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14936           TII->get(X86::PHI), DstReg)
14937     .addReg(mainDstReg).addMBB(mainMBB)
14938     .addReg(restoreDstReg).addMBB(restoreMBB);
14939
14940   // restoreMBB:
14941   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14942   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14943   restoreMBB->addSuccessor(sinkMBB);
14944
14945   MI->eraseFromParent();
14946   return sinkMBB;
14947 }
14948
14949 MachineBasicBlock *
14950 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14951                                      MachineBasicBlock *MBB) const {
14952   DebugLoc DL = MI->getDebugLoc();
14953   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14954
14955   MachineFunction *MF = MBB->getParent();
14956   MachineRegisterInfo &MRI = MF->getRegInfo();
14957
14958   // Memory Reference
14959   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14960   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14961
14962   MVT PVT = getPointerTy();
14963   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14964          "Invalid Pointer Size!");
14965
14966   const TargetRegisterClass *RC =
14967     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14968   unsigned Tmp = MRI.createVirtualRegister(RC);
14969   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14970   const X86RegisterInfo *RegInfo =
14971     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14972   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14973   unsigned SP = RegInfo->getStackRegister();
14974
14975   MachineInstrBuilder MIB;
14976
14977   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14978   const int64_t SPOffset = 2 * PVT.getStoreSize();
14979
14980   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14981   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14982
14983   // Reload FP
14984   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14985   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14986     MIB.addOperand(MI->getOperand(i));
14987   MIB.setMemRefs(MMOBegin, MMOEnd);
14988   // Reload IP
14989   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14990   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14991     if (i == X86::AddrDisp)
14992       MIB.addDisp(MI->getOperand(i), LabelOffset);
14993     else
14994       MIB.addOperand(MI->getOperand(i));
14995   }
14996   MIB.setMemRefs(MMOBegin, MMOEnd);
14997   // Reload SP
14998   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14999   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15000     if (i == X86::AddrDisp)
15001       MIB.addDisp(MI->getOperand(i), SPOffset);
15002     else
15003       MIB.addOperand(MI->getOperand(i));
15004   }
15005   MIB.setMemRefs(MMOBegin, MMOEnd);
15006   // Jump
15007   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15008
15009   MI->eraseFromParent();
15010   return MBB;
15011 }
15012
15013 MachineBasicBlock *
15014 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15015                                                MachineBasicBlock *BB) const {
15016   switch (MI->getOpcode()) {
15017   default: llvm_unreachable("Unexpected instr type to insert");
15018   case X86::TAILJMPd64:
15019   case X86::TAILJMPr64:
15020   case X86::TAILJMPm64:
15021     llvm_unreachable("TAILJMP64 would not be touched here.");
15022   case X86::TCRETURNdi64:
15023   case X86::TCRETURNri64:
15024   case X86::TCRETURNmi64:
15025     return BB;
15026   case X86::WIN_ALLOCA:
15027     return EmitLoweredWinAlloca(MI, BB);
15028   case X86::SEG_ALLOCA_32:
15029     return EmitLoweredSegAlloca(MI, BB, false);
15030   case X86::SEG_ALLOCA_64:
15031     return EmitLoweredSegAlloca(MI, BB, true);
15032   case X86::TLSCall_32:
15033   case X86::TLSCall_64:
15034     return EmitLoweredTLSCall(MI, BB);
15035   case X86::CMOV_GR8:
15036   case X86::CMOV_FR32:
15037   case X86::CMOV_FR64:
15038   case X86::CMOV_V4F32:
15039   case X86::CMOV_V2F64:
15040   case X86::CMOV_V2I64:
15041   case X86::CMOV_V8F32:
15042   case X86::CMOV_V4F64:
15043   case X86::CMOV_V4I64:
15044   case X86::CMOV_GR16:
15045   case X86::CMOV_GR32:
15046   case X86::CMOV_RFP32:
15047   case X86::CMOV_RFP64:
15048   case X86::CMOV_RFP80:
15049     return EmitLoweredSelect(MI, BB);
15050
15051   case X86::FP32_TO_INT16_IN_MEM:
15052   case X86::FP32_TO_INT32_IN_MEM:
15053   case X86::FP32_TO_INT64_IN_MEM:
15054   case X86::FP64_TO_INT16_IN_MEM:
15055   case X86::FP64_TO_INT32_IN_MEM:
15056   case X86::FP64_TO_INT64_IN_MEM:
15057   case X86::FP80_TO_INT16_IN_MEM:
15058   case X86::FP80_TO_INT32_IN_MEM:
15059   case X86::FP80_TO_INT64_IN_MEM: {
15060     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15061     DebugLoc DL = MI->getDebugLoc();
15062
15063     // Change the floating point control register to use "round towards zero"
15064     // mode when truncating to an integer value.
15065     MachineFunction *F = BB->getParent();
15066     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15067     addFrameReference(BuildMI(*BB, MI, DL,
15068                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15069
15070     // Load the old value of the high byte of the control word...
15071     unsigned OldCW =
15072       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15073     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15074                       CWFrameIdx);
15075
15076     // Set the high part to be round to zero...
15077     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15078       .addImm(0xC7F);
15079
15080     // Reload the modified control word now...
15081     addFrameReference(BuildMI(*BB, MI, DL,
15082                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15083
15084     // Restore the memory image of control word to original value
15085     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15086       .addReg(OldCW);
15087
15088     // Get the X86 opcode to use.
15089     unsigned Opc;
15090     switch (MI->getOpcode()) {
15091     default: llvm_unreachable("illegal opcode!");
15092     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15093     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15094     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15095     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15096     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15097     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15098     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15099     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15100     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15101     }
15102
15103     X86AddressMode AM;
15104     MachineOperand &Op = MI->getOperand(0);
15105     if (Op.isReg()) {
15106       AM.BaseType = X86AddressMode::RegBase;
15107       AM.Base.Reg = Op.getReg();
15108     } else {
15109       AM.BaseType = X86AddressMode::FrameIndexBase;
15110       AM.Base.FrameIndex = Op.getIndex();
15111     }
15112     Op = MI->getOperand(1);
15113     if (Op.isImm())
15114       AM.Scale = Op.getImm();
15115     Op = MI->getOperand(2);
15116     if (Op.isImm())
15117       AM.IndexReg = Op.getImm();
15118     Op = MI->getOperand(3);
15119     if (Op.isGlobal()) {
15120       AM.GV = Op.getGlobal();
15121     } else {
15122       AM.Disp = Op.getImm();
15123     }
15124     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15125                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15126
15127     // Reload the original control word now.
15128     addFrameReference(BuildMI(*BB, MI, DL,
15129                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15130
15131     MI->eraseFromParent();   // The pseudo instruction is gone now.
15132     return BB;
15133   }
15134     // String/text processing lowering.
15135   case X86::PCMPISTRM128REG:
15136   case X86::VPCMPISTRM128REG:
15137   case X86::PCMPISTRM128MEM:
15138   case X86::VPCMPISTRM128MEM:
15139   case X86::PCMPESTRM128REG:
15140   case X86::VPCMPESTRM128REG:
15141   case X86::PCMPESTRM128MEM:
15142   case X86::VPCMPESTRM128MEM:
15143     assert(Subtarget->hasSSE42() &&
15144            "Target must have SSE4.2 or AVX features enabled");
15145     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15146
15147   // String/text processing lowering.
15148   case X86::PCMPISTRIREG:
15149   case X86::VPCMPISTRIREG:
15150   case X86::PCMPISTRIMEM:
15151   case X86::VPCMPISTRIMEM:
15152   case X86::PCMPESTRIREG:
15153   case X86::VPCMPESTRIREG:
15154   case X86::PCMPESTRIMEM:
15155   case X86::VPCMPESTRIMEM:
15156     assert(Subtarget->hasSSE42() &&
15157            "Target must have SSE4.2 or AVX features enabled");
15158     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15159
15160   // Thread synchronization.
15161   case X86::MONITOR:
15162     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15163
15164   // xbegin
15165   case X86::XBEGIN:
15166     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15167
15168   // Atomic Lowering.
15169   case X86::ATOMAND8:
15170   case X86::ATOMAND16:
15171   case X86::ATOMAND32:
15172   case X86::ATOMAND64:
15173     // Fall through
15174   case X86::ATOMOR8:
15175   case X86::ATOMOR16:
15176   case X86::ATOMOR32:
15177   case X86::ATOMOR64:
15178     // Fall through
15179   case X86::ATOMXOR16:
15180   case X86::ATOMXOR8:
15181   case X86::ATOMXOR32:
15182   case X86::ATOMXOR64:
15183     // Fall through
15184   case X86::ATOMNAND8:
15185   case X86::ATOMNAND16:
15186   case X86::ATOMNAND32:
15187   case X86::ATOMNAND64:
15188     // Fall through
15189   case X86::ATOMMAX8:
15190   case X86::ATOMMAX16:
15191   case X86::ATOMMAX32:
15192   case X86::ATOMMAX64:
15193     // Fall through
15194   case X86::ATOMMIN8:
15195   case X86::ATOMMIN16:
15196   case X86::ATOMMIN32:
15197   case X86::ATOMMIN64:
15198     // Fall through
15199   case X86::ATOMUMAX8:
15200   case X86::ATOMUMAX16:
15201   case X86::ATOMUMAX32:
15202   case X86::ATOMUMAX64:
15203     // Fall through
15204   case X86::ATOMUMIN8:
15205   case X86::ATOMUMIN16:
15206   case X86::ATOMUMIN32:
15207   case X86::ATOMUMIN64:
15208     return EmitAtomicLoadArith(MI, BB);
15209
15210   // This group does 64-bit operations on a 32-bit host.
15211   case X86::ATOMAND6432:
15212   case X86::ATOMOR6432:
15213   case X86::ATOMXOR6432:
15214   case X86::ATOMNAND6432:
15215   case X86::ATOMADD6432:
15216   case X86::ATOMSUB6432:
15217   case X86::ATOMMAX6432:
15218   case X86::ATOMMIN6432:
15219   case X86::ATOMUMAX6432:
15220   case X86::ATOMUMIN6432:
15221   case X86::ATOMSWAP6432:
15222     return EmitAtomicLoadArith6432(MI, BB);
15223
15224   case X86::VASTART_SAVE_XMM_REGS:
15225     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15226
15227   case X86::VAARG_64:
15228     return EmitVAARG64WithCustomInserter(MI, BB);
15229
15230   case X86::EH_SjLj_SetJmp32:
15231   case X86::EH_SjLj_SetJmp64:
15232     return emitEHSjLjSetJmp(MI, BB);
15233
15234   case X86::EH_SjLj_LongJmp32:
15235   case X86::EH_SjLj_LongJmp64:
15236     return emitEHSjLjLongJmp(MI, BB);
15237   }
15238 }
15239
15240 //===----------------------------------------------------------------------===//
15241 //                           X86 Optimization Hooks
15242 //===----------------------------------------------------------------------===//
15243
15244 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15245                                                        APInt &KnownZero,
15246                                                        APInt &KnownOne,
15247                                                        const SelectionDAG &DAG,
15248                                                        unsigned Depth) const {
15249   unsigned BitWidth = KnownZero.getBitWidth();
15250   unsigned Opc = Op.getOpcode();
15251   assert((Opc >= ISD::BUILTIN_OP_END ||
15252           Opc == ISD::INTRINSIC_WO_CHAIN ||
15253           Opc == ISD::INTRINSIC_W_CHAIN ||
15254           Opc == ISD::INTRINSIC_VOID) &&
15255          "Should use MaskedValueIsZero if you don't know whether Op"
15256          " is a target node!");
15257
15258   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15259   switch (Opc) {
15260   default: break;
15261   case X86ISD::ADD:
15262   case X86ISD::SUB:
15263   case X86ISD::ADC:
15264   case X86ISD::SBB:
15265   case X86ISD::SMUL:
15266   case X86ISD::UMUL:
15267   case X86ISD::INC:
15268   case X86ISD::DEC:
15269   case X86ISD::OR:
15270   case X86ISD::XOR:
15271   case X86ISD::AND:
15272     // These nodes' second result is a boolean.
15273     if (Op.getResNo() == 0)
15274       break;
15275     // Fallthrough
15276   case X86ISD::SETCC:
15277     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15278     break;
15279   case ISD::INTRINSIC_WO_CHAIN: {
15280     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15281     unsigned NumLoBits = 0;
15282     switch (IntId) {
15283     default: break;
15284     case Intrinsic::x86_sse_movmsk_ps:
15285     case Intrinsic::x86_avx_movmsk_ps_256:
15286     case Intrinsic::x86_sse2_movmsk_pd:
15287     case Intrinsic::x86_avx_movmsk_pd_256:
15288     case Intrinsic::x86_mmx_pmovmskb:
15289     case Intrinsic::x86_sse2_pmovmskb_128:
15290     case Intrinsic::x86_avx2_pmovmskb: {
15291       // High bits of movmskp{s|d}, pmovmskb are known zero.
15292       switch (IntId) {
15293         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15294         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15295         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15296         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15297         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15298         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15299         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15300         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15301       }
15302       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15303       break;
15304     }
15305     }
15306     break;
15307   }
15308   }
15309 }
15310
15311 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15312                                                          unsigned Depth) const {
15313   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15314   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15315     return Op.getValueType().getScalarType().getSizeInBits();
15316
15317   // Fallback case.
15318   return 1;
15319 }
15320
15321 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15322 /// node is a GlobalAddress + offset.
15323 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15324                                        const GlobalValue* &GA,
15325                                        int64_t &Offset) const {
15326   if (N->getOpcode() == X86ISD::Wrapper) {
15327     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15328       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15329       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15330       return true;
15331     }
15332   }
15333   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15334 }
15335
15336 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15337 /// same as extracting the high 128-bit part of 256-bit vector and then
15338 /// inserting the result into the low part of a new 256-bit vector
15339 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15340   EVT VT = SVOp->getValueType(0);
15341   unsigned NumElems = VT.getVectorNumElements();
15342
15343   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15344   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15345     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15346         SVOp->getMaskElt(j) >= 0)
15347       return false;
15348
15349   return true;
15350 }
15351
15352 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15353 /// same as extracting the low 128-bit part of 256-bit vector and then
15354 /// inserting the result into the high part of a new 256-bit vector
15355 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15356   EVT VT = SVOp->getValueType(0);
15357   unsigned NumElems = VT.getVectorNumElements();
15358
15359   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15360   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15361     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15362         SVOp->getMaskElt(j) >= 0)
15363       return false;
15364
15365   return true;
15366 }
15367
15368 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15369 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15370                                         TargetLowering::DAGCombinerInfo &DCI,
15371                                         const X86Subtarget* Subtarget) {
15372   SDLoc dl(N);
15373   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15374   SDValue V1 = SVOp->getOperand(0);
15375   SDValue V2 = SVOp->getOperand(1);
15376   EVT VT = SVOp->getValueType(0);
15377   unsigned NumElems = VT.getVectorNumElements();
15378
15379   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15380       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15381     //
15382     //                   0,0,0,...
15383     //                      |
15384     //    V      UNDEF    BUILD_VECTOR    UNDEF
15385     //     \      /           \           /
15386     //  CONCAT_VECTOR         CONCAT_VECTOR
15387     //         \                  /
15388     //          \                /
15389     //          RESULT: V + zero extended
15390     //
15391     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15392         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15393         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15394       return SDValue();
15395
15396     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15397       return SDValue();
15398
15399     // To match the shuffle mask, the first half of the mask should
15400     // be exactly the first vector, and all the rest a splat with the
15401     // first element of the second one.
15402     for (unsigned i = 0; i != NumElems/2; ++i)
15403       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15404           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15405         return SDValue();
15406
15407     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15408     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15409       if (Ld->hasNUsesOfValue(1, 0)) {
15410         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15411         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15412         SDValue ResNode =
15413           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15414                                   array_lengthof(Ops),
15415                                   Ld->getMemoryVT(),
15416                                   Ld->getPointerInfo(),
15417                                   Ld->getAlignment(),
15418                                   false/*isVolatile*/, true/*ReadMem*/,
15419                                   false/*WriteMem*/);
15420
15421         // Make sure the newly-created LOAD is in the same position as Ld in
15422         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15423         // and update uses of Ld's output chain to use the TokenFactor.
15424         if (Ld->hasAnyUseOfValue(1)) {
15425           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15426                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15427           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15428           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15429                                  SDValue(ResNode.getNode(), 1));
15430         }
15431
15432         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15433       }
15434     }
15435
15436     // Emit a zeroed vector and insert the desired subvector on its
15437     // first half.
15438     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15439     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15440     return DCI.CombineTo(N, InsV);
15441   }
15442
15443   //===--------------------------------------------------------------------===//
15444   // Combine some shuffles into subvector extracts and inserts:
15445   //
15446
15447   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15448   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15449     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15450     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15451     return DCI.CombineTo(N, InsV);
15452   }
15453
15454   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15455   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15456     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15457     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15458     return DCI.CombineTo(N, InsV);
15459   }
15460
15461   return SDValue();
15462 }
15463
15464 /// PerformShuffleCombine - Performs several different shuffle combines.
15465 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15466                                      TargetLowering::DAGCombinerInfo &DCI,
15467                                      const X86Subtarget *Subtarget) {
15468   SDLoc dl(N);
15469   EVT VT = N->getValueType(0);
15470
15471   // Don't create instructions with illegal types after legalize types has run.
15472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15473   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15474     return SDValue();
15475
15476   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15477   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15478       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15479     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15480
15481   // Only handle 128 wide vector from here on.
15482   if (!VT.is128BitVector())
15483     return SDValue();
15484
15485   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15486   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15487   // consecutive, non-overlapping, and in the right order.
15488   SmallVector<SDValue, 16> Elts;
15489   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15490     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15491
15492   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15493 }
15494
15495 /// PerformTruncateCombine - Converts truncate operation to
15496 /// a sequence of vector shuffle operations.
15497 /// It is possible when we truncate 256-bit vector to 128-bit vector
15498 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15499                                       TargetLowering::DAGCombinerInfo &DCI,
15500                                       const X86Subtarget *Subtarget)  {
15501   return SDValue();
15502 }
15503
15504 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15505 /// specific shuffle of a load can be folded into a single element load.
15506 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15507 /// shuffles have been customed lowered so we need to handle those here.
15508 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15509                                          TargetLowering::DAGCombinerInfo &DCI) {
15510   if (DCI.isBeforeLegalizeOps())
15511     return SDValue();
15512
15513   SDValue InVec = N->getOperand(0);
15514   SDValue EltNo = N->getOperand(1);
15515
15516   if (!isa<ConstantSDNode>(EltNo))
15517     return SDValue();
15518
15519   EVT VT = InVec.getValueType();
15520
15521   bool HasShuffleIntoBitcast = false;
15522   if (InVec.getOpcode() == ISD::BITCAST) {
15523     // Don't duplicate a load with other uses.
15524     if (!InVec.hasOneUse())
15525       return SDValue();
15526     EVT BCVT = InVec.getOperand(0).getValueType();
15527     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15528       return SDValue();
15529     InVec = InVec.getOperand(0);
15530     HasShuffleIntoBitcast = true;
15531   }
15532
15533   if (!isTargetShuffle(InVec.getOpcode()))
15534     return SDValue();
15535
15536   // Don't duplicate a load with other uses.
15537   if (!InVec.hasOneUse())
15538     return SDValue();
15539
15540   SmallVector<int, 16> ShuffleMask;
15541   bool UnaryShuffle;
15542   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15543                             UnaryShuffle))
15544     return SDValue();
15545
15546   // Select the input vector, guarding against out of range extract vector.
15547   unsigned NumElems = VT.getVectorNumElements();
15548   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15549   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15550   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15551                                          : InVec.getOperand(1);
15552
15553   // If inputs to shuffle are the same for both ops, then allow 2 uses
15554   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15555
15556   if (LdNode.getOpcode() == ISD::BITCAST) {
15557     // Don't duplicate a load with other uses.
15558     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15559       return SDValue();
15560
15561     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15562     LdNode = LdNode.getOperand(0);
15563   }
15564
15565   if (!ISD::isNormalLoad(LdNode.getNode()))
15566     return SDValue();
15567
15568   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15569
15570   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15571     return SDValue();
15572
15573   if (HasShuffleIntoBitcast) {
15574     // If there's a bitcast before the shuffle, check if the load type and
15575     // alignment is valid.
15576     unsigned Align = LN0->getAlignment();
15577     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15578     unsigned NewAlign = TLI.getDataLayout()->
15579       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15580
15581     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15582       return SDValue();
15583   }
15584
15585   // All checks match so transform back to vector_shuffle so that DAG combiner
15586   // can finish the job
15587   SDLoc dl(N);
15588
15589   // Create shuffle node taking into account the case that its a unary shuffle
15590   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15591   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15592                                  InVec.getOperand(0), Shuffle,
15593                                  &ShuffleMask[0]);
15594   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15595   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15596                      EltNo);
15597 }
15598
15599 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15600 /// generation and convert it from being a bunch of shuffles and extracts
15601 /// to a simple store and scalar loads to extract the elements.
15602 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15603                                          TargetLowering::DAGCombinerInfo &DCI) {
15604   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15605   if (NewOp.getNode())
15606     return NewOp;
15607
15608   SDValue InputVector = N->getOperand(0);
15609   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15610   // from mmx to v2i32 has a single usage.
15611   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15612       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15613       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15614     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15615                        N->getValueType(0),
15616                        InputVector.getNode()->getOperand(0));
15617
15618   // Only operate on vectors of 4 elements, where the alternative shuffling
15619   // gets to be more expensive.
15620   if (InputVector.getValueType() != MVT::v4i32)
15621     return SDValue();
15622
15623   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15624   // single use which is a sign-extend or zero-extend, and all elements are
15625   // used.
15626   SmallVector<SDNode *, 4> Uses;
15627   unsigned ExtractedElements = 0;
15628   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15629        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15630     if (UI.getUse().getResNo() != InputVector.getResNo())
15631       return SDValue();
15632
15633     SDNode *Extract = *UI;
15634     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15635       return SDValue();
15636
15637     if (Extract->getValueType(0) != MVT::i32)
15638       return SDValue();
15639     if (!Extract->hasOneUse())
15640       return SDValue();
15641     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15642         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15643       return SDValue();
15644     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15645       return SDValue();
15646
15647     // Record which element was extracted.
15648     ExtractedElements |=
15649       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15650
15651     Uses.push_back(Extract);
15652   }
15653
15654   // If not all the elements were used, this may not be worthwhile.
15655   if (ExtractedElements != 15)
15656     return SDValue();
15657
15658   // Ok, we've now decided to do the transformation.
15659   SDLoc dl(InputVector);
15660
15661   // Store the value to a temporary stack slot.
15662   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15663   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15664                             MachinePointerInfo(), false, false, 0);
15665
15666   // Replace each use (extract) with a load of the appropriate element.
15667   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15668        UE = Uses.end(); UI != UE; ++UI) {
15669     SDNode *Extract = *UI;
15670
15671     // cOMpute the element's address.
15672     SDValue Idx = Extract->getOperand(1);
15673     unsigned EltSize =
15674         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15675     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15676     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15677     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15678
15679     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15680                                      StackPtr, OffsetVal);
15681
15682     // Load the scalar.
15683     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15684                                      ScalarAddr, MachinePointerInfo(),
15685                                      false, false, false, 0);
15686
15687     // Replace the exact with the load.
15688     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15689   }
15690
15691   // The replacement was made in place; don't return anything.
15692   return SDValue();
15693 }
15694
15695 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15696 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15697                                    SDValue RHS, SelectionDAG &DAG,
15698                                    const X86Subtarget *Subtarget) {
15699   if (!VT.isVector())
15700     return 0;
15701
15702   switch (VT.getSimpleVT().SimpleTy) {
15703   default: return 0;
15704   case MVT::v32i8:
15705   case MVT::v16i16:
15706   case MVT::v8i32:
15707     if (!Subtarget->hasAVX2())
15708       return 0;
15709   case MVT::v16i8:
15710   case MVT::v8i16:
15711   case MVT::v4i32:
15712     if (!Subtarget->hasSSE2())
15713       return 0;
15714   }
15715
15716   // SSE2 has only a small subset of the operations.
15717   bool hasUnsigned = Subtarget->hasSSE41() ||
15718                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15719   bool hasSigned = Subtarget->hasSSE41() ||
15720                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15721
15722   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15723
15724   // Check for x CC y ? x : y.
15725   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15726       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15727     switch (CC) {
15728     default: break;
15729     case ISD::SETULT:
15730     case ISD::SETULE:
15731       return hasUnsigned ? X86ISD::UMIN : 0;
15732     case ISD::SETUGT:
15733     case ISD::SETUGE:
15734       return hasUnsigned ? X86ISD::UMAX : 0;
15735     case ISD::SETLT:
15736     case ISD::SETLE:
15737       return hasSigned ? X86ISD::SMIN : 0;
15738     case ISD::SETGT:
15739     case ISD::SETGE:
15740       return hasSigned ? X86ISD::SMAX : 0;
15741     }
15742   // Check for x CC y ? y : x -- a min/max with reversed arms.
15743   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15744              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15745     switch (CC) {
15746     default: break;
15747     case ISD::SETULT:
15748     case ISD::SETULE:
15749       return hasUnsigned ? X86ISD::UMAX : 0;
15750     case ISD::SETUGT:
15751     case ISD::SETUGE:
15752       return hasUnsigned ? X86ISD::UMIN : 0;
15753     case ISD::SETLT:
15754     case ISD::SETLE:
15755       return hasSigned ? X86ISD::SMAX : 0;
15756     case ISD::SETGT:
15757     case ISD::SETGE:
15758       return hasSigned ? X86ISD::SMIN : 0;
15759     }
15760   }
15761
15762   return 0;
15763 }
15764
15765 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15766 /// nodes.
15767 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15768                                     TargetLowering::DAGCombinerInfo &DCI,
15769                                     const X86Subtarget *Subtarget) {
15770   SDLoc DL(N);
15771   SDValue Cond = N->getOperand(0);
15772   // Get the LHS/RHS of the select.
15773   SDValue LHS = N->getOperand(1);
15774   SDValue RHS = N->getOperand(2);
15775   EVT VT = LHS.getValueType();
15776
15777   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15778   // instructions match the semantics of the common C idiom x<y?x:y but not
15779   // x<=y?x:y, because of how they handle negative zero (which can be
15780   // ignored in unsafe-math mode).
15781   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15782       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15783       (Subtarget->hasSSE2() ||
15784        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15785     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15786
15787     unsigned Opcode = 0;
15788     // Check for x CC y ? x : y.
15789     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15790         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15791       switch (CC) {
15792       default: break;
15793       case ISD::SETULT:
15794         // Converting this to a min would handle NaNs incorrectly, and swapping
15795         // the operands would cause it to handle comparisons between positive
15796         // and negative zero incorrectly.
15797         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15798           if (!DAG.getTarget().Options.UnsafeFPMath &&
15799               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15800             break;
15801           std::swap(LHS, RHS);
15802         }
15803         Opcode = X86ISD::FMIN;
15804         break;
15805       case ISD::SETOLE:
15806         // Converting this to a min would handle comparisons between positive
15807         // and negative zero incorrectly.
15808         if (!DAG.getTarget().Options.UnsafeFPMath &&
15809             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15810           break;
15811         Opcode = X86ISD::FMIN;
15812         break;
15813       case ISD::SETULE:
15814         // Converting this to a min would handle both negative zeros and NaNs
15815         // incorrectly, but we can swap the operands to fix both.
15816         std::swap(LHS, RHS);
15817       case ISD::SETOLT:
15818       case ISD::SETLT:
15819       case ISD::SETLE:
15820         Opcode = X86ISD::FMIN;
15821         break;
15822
15823       case ISD::SETOGE:
15824         // Converting this to a max would handle comparisons between positive
15825         // and negative zero incorrectly.
15826         if (!DAG.getTarget().Options.UnsafeFPMath &&
15827             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15828           break;
15829         Opcode = X86ISD::FMAX;
15830         break;
15831       case ISD::SETUGT:
15832         // Converting this to a max would handle NaNs incorrectly, and swapping
15833         // the operands would cause it to handle comparisons between positive
15834         // and negative zero incorrectly.
15835         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15836           if (!DAG.getTarget().Options.UnsafeFPMath &&
15837               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15838             break;
15839           std::swap(LHS, RHS);
15840         }
15841         Opcode = X86ISD::FMAX;
15842         break;
15843       case ISD::SETUGE:
15844         // Converting this to a max would handle both negative zeros and NaNs
15845         // incorrectly, but we can swap the operands to fix both.
15846         std::swap(LHS, RHS);
15847       case ISD::SETOGT:
15848       case ISD::SETGT:
15849       case ISD::SETGE:
15850         Opcode = X86ISD::FMAX;
15851         break;
15852       }
15853     // Check for x CC y ? y : x -- a min/max with reversed arms.
15854     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15855                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15856       switch (CC) {
15857       default: break;
15858       case ISD::SETOGE:
15859         // Converting this to a min would handle comparisons between positive
15860         // and negative zero incorrectly, and swapping the operands would
15861         // cause it to handle NaNs incorrectly.
15862         if (!DAG.getTarget().Options.UnsafeFPMath &&
15863             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15864           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15865             break;
15866           std::swap(LHS, RHS);
15867         }
15868         Opcode = X86ISD::FMIN;
15869         break;
15870       case ISD::SETUGT:
15871         // Converting this to a min would handle NaNs incorrectly.
15872         if (!DAG.getTarget().Options.UnsafeFPMath &&
15873             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15874           break;
15875         Opcode = X86ISD::FMIN;
15876         break;
15877       case ISD::SETUGE:
15878         // Converting this to a min would handle both negative zeros and NaNs
15879         // incorrectly, but we can swap the operands to fix both.
15880         std::swap(LHS, RHS);
15881       case ISD::SETOGT:
15882       case ISD::SETGT:
15883       case ISD::SETGE:
15884         Opcode = X86ISD::FMIN;
15885         break;
15886
15887       case ISD::SETULT:
15888         // Converting this to a max would handle NaNs incorrectly.
15889         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15890           break;
15891         Opcode = X86ISD::FMAX;
15892         break;
15893       case ISD::SETOLE:
15894         // Converting this to a max would handle comparisons between positive
15895         // and negative zero incorrectly, and swapping the operands would
15896         // cause it to handle NaNs incorrectly.
15897         if (!DAG.getTarget().Options.UnsafeFPMath &&
15898             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15899           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15900             break;
15901           std::swap(LHS, RHS);
15902         }
15903         Opcode = X86ISD::FMAX;
15904         break;
15905       case ISD::SETULE:
15906         // Converting this to a max would handle both negative zeros and NaNs
15907         // incorrectly, but we can swap the operands to fix both.
15908         std::swap(LHS, RHS);
15909       case ISD::SETOLT:
15910       case ISD::SETLT:
15911       case ISD::SETLE:
15912         Opcode = X86ISD::FMAX;
15913         break;
15914       }
15915     }
15916
15917     if (Opcode)
15918       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15919   }
15920
15921   // If this is a select between two integer constants, try to do some
15922   // optimizations.
15923   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15924     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15925       // Don't do this for crazy integer types.
15926       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15927         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15928         // so that TrueC (the true value) is larger than FalseC.
15929         bool NeedsCondInvert = false;
15930
15931         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15932             // Efficiently invertible.
15933             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15934              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15935               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15936           NeedsCondInvert = true;
15937           std::swap(TrueC, FalseC);
15938         }
15939
15940         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15941         if (FalseC->getAPIntValue() == 0 &&
15942             TrueC->getAPIntValue().isPowerOf2()) {
15943           if (NeedsCondInvert) // Invert the condition if needed.
15944             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15945                                DAG.getConstant(1, Cond.getValueType()));
15946
15947           // Zero extend the condition if needed.
15948           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15949
15950           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15951           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15952                              DAG.getConstant(ShAmt, MVT::i8));
15953         }
15954
15955         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15956         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15957           if (NeedsCondInvert) // Invert the condition if needed.
15958             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15959                                DAG.getConstant(1, Cond.getValueType()));
15960
15961           // Zero extend the condition if needed.
15962           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15963                              FalseC->getValueType(0), Cond);
15964           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15965                              SDValue(FalseC, 0));
15966         }
15967
15968         // Optimize cases that will turn into an LEA instruction.  This requires
15969         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15970         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15971           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15972           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15973
15974           bool isFastMultiplier = false;
15975           if (Diff < 10) {
15976             switch ((unsigned char)Diff) {
15977               default: break;
15978               case 1:  // result = add base, cond
15979               case 2:  // result = lea base(    , cond*2)
15980               case 3:  // result = lea base(cond, cond*2)
15981               case 4:  // result = lea base(    , cond*4)
15982               case 5:  // result = lea base(cond, cond*4)
15983               case 8:  // result = lea base(    , cond*8)
15984               case 9:  // result = lea base(cond, cond*8)
15985                 isFastMultiplier = true;
15986                 break;
15987             }
15988           }
15989
15990           if (isFastMultiplier) {
15991             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15992             if (NeedsCondInvert) // Invert the condition if needed.
15993               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15994                                  DAG.getConstant(1, Cond.getValueType()));
15995
15996             // Zero extend the condition if needed.
15997             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15998                                Cond);
15999             // Scale the condition by the difference.
16000             if (Diff != 1)
16001               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16002                                  DAG.getConstant(Diff, Cond.getValueType()));
16003
16004             // Add the base if non-zero.
16005             if (FalseC->getAPIntValue() != 0)
16006               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16007                                  SDValue(FalseC, 0));
16008             return Cond;
16009           }
16010         }
16011       }
16012   }
16013
16014   // Canonicalize max and min:
16015   // (x > y) ? x : y -> (x >= y) ? x : y
16016   // (x < y) ? x : y -> (x <= y) ? x : y
16017   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16018   // the need for an extra compare
16019   // against zero. e.g.
16020   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16021   // subl   %esi, %edi
16022   // testl  %edi, %edi
16023   // movl   $0, %eax
16024   // cmovgl %edi, %eax
16025   // =>
16026   // xorl   %eax, %eax
16027   // subl   %esi, $edi
16028   // cmovsl %eax, %edi
16029   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16030       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16031       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16032     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16033     switch (CC) {
16034     default: break;
16035     case ISD::SETLT:
16036     case ISD::SETGT: {
16037       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16038       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16039                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16040       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16041     }
16042     }
16043   }
16044
16045   // Match VSELECTs into subs with unsigned saturation.
16046   if (!DCI.isBeforeLegalize() &&
16047       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16048       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16049       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16050        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16051     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16052
16053     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16054     // left side invert the predicate to simplify logic below.
16055     SDValue Other;
16056     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16057       Other = RHS;
16058       CC = ISD::getSetCCInverse(CC, true);
16059     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16060       Other = LHS;
16061     }
16062
16063     if (Other.getNode() && Other->getNumOperands() == 2 &&
16064         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16065       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16066       SDValue CondRHS = Cond->getOperand(1);
16067
16068       // Look for a general sub with unsigned saturation first.
16069       // x >= y ? x-y : 0 --> subus x, y
16070       // x >  y ? x-y : 0 --> subus x, y
16071       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16072           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16073         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16074
16075       // If the RHS is a constant we have to reverse the const canonicalization.
16076       // x > C-1 ? x+-C : 0 --> subus x, C
16077       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16078           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16079         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16080         if (CondRHS.getConstantOperandVal(0) == -A-1)
16081           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16082                              DAG.getConstant(-A, VT));
16083       }
16084
16085       // Another special case: If C was a sign bit, the sub has been
16086       // canonicalized into a xor.
16087       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16088       //        it's safe to decanonicalize the xor?
16089       // x s< 0 ? x^C : 0 --> subus x, C
16090       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16091           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16092           isSplatVector(OpRHS.getNode())) {
16093         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16094         if (A.isSignBit())
16095           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16096       }
16097     }
16098   }
16099
16100   // Try to match a min/max vector operation.
16101   if (!DCI.isBeforeLegalize() &&
16102       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16103     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16104       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16105
16106   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16107   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16108       Cond.getOpcode() == ISD::SETCC) {
16109
16110     assert(Cond.getValueType().isVector() &&
16111            "vector select expects a vector selector!");
16112
16113     EVT IntVT = Cond.getValueType();
16114     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16115     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16116
16117     if (!TValIsAllOnes && !FValIsAllZeros) {
16118       // Try invert the condition if true value is not all 1s and false value
16119       // is not all 0s.
16120       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16121       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16122
16123       if (TValIsAllZeros || FValIsAllOnes) {
16124         SDValue CC = Cond.getOperand(2);
16125         ISD::CondCode NewCC =
16126           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16127                                Cond.getOperand(0).getValueType().isInteger());
16128         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16129         std::swap(LHS, RHS);
16130         TValIsAllOnes = FValIsAllOnes;
16131         FValIsAllZeros = TValIsAllZeros;
16132       }
16133     }
16134
16135     if (TValIsAllOnes || FValIsAllZeros) {
16136       SDValue Ret;
16137
16138       if (TValIsAllOnes && FValIsAllZeros)
16139         Ret = Cond;
16140       else if (TValIsAllOnes)
16141         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16142                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16143       else if (FValIsAllZeros)
16144         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16145                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16146
16147       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16148     }
16149   }
16150
16151   // If we know that this node is legal then we know that it is going to be
16152   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16153   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16154   // to simplify previous instructions.
16155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16156   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16157       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16158     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16159
16160     // Don't optimize vector selects that map to mask-registers.
16161     if (BitWidth == 1)
16162       return SDValue();
16163
16164     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16165     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16166
16167     APInt KnownZero, KnownOne;
16168     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16169                                           DCI.isBeforeLegalizeOps());
16170     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16171         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16172       DCI.CommitTargetLoweringOpt(TLO);
16173   }
16174
16175   return SDValue();
16176 }
16177
16178 // Check whether a boolean test is testing a boolean value generated by
16179 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16180 // code.
16181 //
16182 // Simplify the following patterns:
16183 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16184 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16185 // to (Op EFLAGS Cond)
16186 //
16187 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16188 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16189 // to (Op EFLAGS !Cond)
16190 //
16191 // where Op could be BRCOND or CMOV.
16192 //
16193 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16194   // Quit if not CMP and SUB with its value result used.
16195   if (Cmp.getOpcode() != X86ISD::CMP &&
16196       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16197       return SDValue();
16198
16199   // Quit if not used as a boolean value.
16200   if (CC != X86::COND_E && CC != X86::COND_NE)
16201     return SDValue();
16202
16203   // Check CMP operands. One of them should be 0 or 1 and the other should be
16204   // an SetCC or extended from it.
16205   SDValue Op1 = Cmp.getOperand(0);
16206   SDValue Op2 = Cmp.getOperand(1);
16207
16208   SDValue SetCC;
16209   const ConstantSDNode* C = 0;
16210   bool needOppositeCond = (CC == X86::COND_E);
16211   bool checkAgainstTrue = false; // Is it a comparison against 1?
16212
16213   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16214     SetCC = Op2;
16215   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16216     SetCC = Op1;
16217   else // Quit if all operands are not constants.
16218     return SDValue();
16219
16220   if (C->getZExtValue() == 1) {
16221     needOppositeCond = !needOppositeCond;
16222     checkAgainstTrue = true;
16223   } else if (C->getZExtValue() != 0)
16224     // Quit if the constant is neither 0 or 1.
16225     return SDValue();
16226
16227   bool truncatedToBoolWithAnd = false;
16228   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16229   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16230          SetCC.getOpcode() == ISD::TRUNCATE ||
16231          SetCC.getOpcode() == ISD::AND) {
16232     if (SetCC.getOpcode() == ISD::AND) {
16233       int OpIdx = -1;
16234       ConstantSDNode *CS;
16235       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16236           CS->getZExtValue() == 1)
16237         OpIdx = 1;
16238       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16239           CS->getZExtValue() == 1)
16240         OpIdx = 0;
16241       if (OpIdx == -1)
16242         break;
16243       SetCC = SetCC.getOperand(OpIdx);
16244       truncatedToBoolWithAnd = true;
16245     } else
16246       SetCC = SetCC.getOperand(0);
16247   }
16248
16249   switch (SetCC.getOpcode()) {
16250   case X86ISD::SETCC_CARRY:
16251     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16252     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16253     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16254     // truncated to i1 using 'and'.
16255     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16256       break;
16257     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16258            "Invalid use of SETCC_CARRY!");
16259     // FALL THROUGH
16260   case X86ISD::SETCC:
16261     // Set the condition code or opposite one if necessary.
16262     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16263     if (needOppositeCond)
16264       CC = X86::GetOppositeBranchCondition(CC);
16265     return SetCC.getOperand(1);
16266   case X86ISD::CMOV: {
16267     // Check whether false/true value has canonical one, i.e. 0 or 1.
16268     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16269     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16270     // Quit if true value is not a constant.
16271     if (!TVal)
16272       return SDValue();
16273     // Quit if false value is not a constant.
16274     if (!FVal) {
16275       SDValue Op = SetCC.getOperand(0);
16276       // Skip 'zext' or 'trunc' node.
16277       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16278           Op.getOpcode() == ISD::TRUNCATE)
16279         Op = Op.getOperand(0);
16280       // A special case for rdrand/rdseed, where 0 is set if false cond is
16281       // found.
16282       if ((Op.getOpcode() != X86ISD::RDRAND &&
16283            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16284         return SDValue();
16285     }
16286     // Quit if false value is not the constant 0 or 1.
16287     bool FValIsFalse = true;
16288     if (FVal && FVal->getZExtValue() != 0) {
16289       if (FVal->getZExtValue() != 1)
16290         return SDValue();
16291       // If FVal is 1, opposite cond is needed.
16292       needOppositeCond = !needOppositeCond;
16293       FValIsFalse = false;
16294     }
16295     // Quit if TVal is not the constant opposite of FVal.
16296     if (FValIsFalse && TVal->getZExtValue() != 1)
16297       return SDValue();
16298     if (!FValIsFalse && TVal->getZExtValue() != 0)
16299       return SDValue();
16300     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16301     if (needOppositeCond)
16302       CC = X86::GetOppositeBranchCondition(CC);
16303     return SetCC.getOperand(3);
16304   }
16305   }
16306
16307   return SDValue();
16308 }
16309
16310 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16311 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16312                                   TargetLowering::DAGCombinerInfo &DCI,
16313                                   const X86Subtarget *Subtarget) {
16314   SDLoc DL(N);
16315
16316   // If the flag operand isn't dead, don't touch this CMOV.
16317   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16318     return SDValue();
16319
16320   SDValue FalseOp = N->getOperand(0);
16321   SDValue TrueOp = N->getOperand(1);
16322   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16323   SDValue Cond = N->getOperand(3);
16324
16325   if (CC == X86::COND_E || CC == X86::COND_NE) {
16326     switch (Cond.getOpcode()) {
16327     default: break;
16328     case X86ISD::BSR:
16329     case X86ISD::BSF:
16330       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16331       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16332         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16333     }
16334   }
16335
16336   SDValue Flags;
16337
16338   Flags = checkBoolTestSetCCCombine(Cond, CC);
16339   if (Flags.getNode() &&
16340       // Extra check as FCMOV only supports a subset of X86 cond.
16341       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16342     SDValue Ops[] = { FalseOp, TrueOp,
16343                       DAG.getConstant(CC, MVT::i8), Flags };
16344     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16345                        Ops, array_lengthof(Ops));
16346   }
16347
16348   // If this is a select between two integer constants, try to do some
16349   // optimizations.  Note that the operands are ordered the opposite of SELECT
16350   // operands.
16351   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16352     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16353       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16354       // larger than FalseC (the false value).
16355       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16356         CC = X86::GetOppositeBranchCondition(CC);
16357         std::swap(TrueC, FalseC);
16358         std::swap(TrueOp, FalseOp);
16359       }
16360
16361       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16362       // This is efficient for any integer data type (including i8/i16) and
16363       // shift amount.
16364       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16365         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16366                            DAG.getConstant(CC, MVT::i8), Cond);
16367
16368         // Zero extend the condition if needed.
16369         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16370
16371         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16372         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16373                            DAG.getConstant(ShAmt, MVT::i8));
16374         if (N->getNumValues() == 2)  // Dead flag value?
16375           return DCI.CombineTo(N, Cond, SDValue());
16376         return Cond;
16377       }
16378
16379       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16380       // for any integer data type, including i8/i16.
16381       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16382         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16383                            DAG.getConstant(CC, MVT::i8), Cond);
16384
16385         // Zero extend the condition if needed.
16386         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16387                            FalseC->getValueType(0), Cond);
16388         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16389                            SDValue(FalseC, 0));
16390
16391         if (N->getNumValues() == 2)  // Dead flag value?
16392           return DCI.CombineTo(N, Cond, SDValue());
16393         return Cond;
16394       }
16395
16396       // Optimize cases that will turn into an LEA instruction.  This requires
16397       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16398       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16399         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16400         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16401
16402         bool isFastMultiplier = false;
16403         if (Diff < 10) {
16404           switch ((unsigned char)Diff) {
16405           default: break;
16406           case 1:  // result = add base, cond
16407           case 2:  // result = lea base(    , cond*2)
16408           case 3:  // result = lea base(cond, cond*2)
16409           case 4:  // result = lea base(    , cond*4)
16410           case 5:  // result = lea base(cond, cond*4)
16411           case 8:  // result = lea base(    , cond*8)
16412           case 9:  // result = lea base(cond, cond*8)
16413             isFastMultiplier = true;
16414             break;
16415           }
16416         }
16417
16418         if (isFastMultiplier) {
16419           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16420           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16421                              DAG.getConstant(CC, MVT::i8), Cond);
16422           // Zero extend the condition if needed.
16423           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16424                              Cond);
16425           // Scale the condition by the difference.
16426           if (Diff != 1)
16427             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16428                                DAG.getConstant(Diff, Cond.getValueType()));
16429
16430           // Add the base if non-zero.
16431           if (FalseC->getAPIntValue() != 0)
16432             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16433                                SDValue(FalseC, 0));
16434           if (N->getNumValues() == 2)  // Dead flag value?
16435             return DCI.CombineTo(N, Cond, SDValue());
16436           return Cond;
16437         }
16438       }
16439     }
16440   }
16441
16442   // Handle these cases:
16443   //   (select (x != c), e, c) -> select (x != c), e, x),
16444   //   (select (x == c), c, e) -> select (x == c), x, e)
16445   // where the c is an integer constant, and the "select" is the combination
16446   // of CMOV and CMP.
16447   //
16448   // The rationale for this change is that the conditional-move from a constant
16449   // needs two instructions, however, conditional-move from a register needs
16450   // only one instruction.
16451   //
16452   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16453   //  some instruction-combining opportunities. This opt needs to be
16454   //  postponed as late as possible.
16455   //
16456   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16457     // the DCI.xxxx conditions are provided to postpone the optimization as
16458     // late as possible.
16459
16460     ConstantSDNode *CmpAgainst = 0;
16461     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16462         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16463         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16464
16465       if (CC == X86::COND_NE &&
16466           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16467         CC = X86::GetOppositeBranchCondition(CC);
16468         std::swap(TrueOp, FalseOp);
16469       }
16470
16471       if (CC == X86::COND_E &&
16472           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16473         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16474                           DAG.getConstant(CC, MVT::i8), Cond };
16475         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16476                            array_lengthof(Ops));
16477       }
16478     }
16479   }
16480
16481   return SDValue();
16482 }
16483
16484 /// PerformMulCombine - Optimize a single multiply with constant into two
16485 /// in order to implement it with two cheaper instructions, e.g.
16486 /// LEA + SHL, LEA + LEA.
16487 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16488                                  TargetLowering::DAGCombinerInfo &DCI) {
16489   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16490     return SDValue();
16491
16492   EVT VT = N->getValueType(0);
16493   if (VT != MVT::i64)
16494     return SDValue();
16495
16496   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16497   if (!C)
16498     return SDValue();
16499   uint64_t MulAmt = C->getZExtValue();
16500   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16501     return SDValue();
16502
16503   uint64_t MulAmt1 = 0;
16504   uint64_t MulAmt2 = 0;
16505   if ((MulAmt % 9) == 0) {
16506     MulAmt1 = 9;
16507     MulAmt2 = MulAmt / 9;
16508   } else if ((MulAmt % 5) == 0) {
16509     MulAmt1 = 5;
16510     MulAmt2 = MulAmt / 5;
16511   } else if ((MulAmt % 3) == 0) {
16512     MulAmt1 = 3;
16513     MulAmt2 = MulAmt / 3;
16514   }
16515   if (MulAmt2 &&
16516       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16517     SDLoc DL(N);
16518
16519     if (isPowerOf2_64(MulAmt2) &&
16520         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16521       // If second multiplifer is pow2, issue it first. We want the multiply by
16522       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16523       // is an add.
16524       std::swap(MulAmt1, MulAmt2);
16525
16526     SDValue NewMul;
16527     if (isPowerOf2_64(MulAmt1))
16528       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16529                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16530     else
16531       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16532                            DAG.getConstant(MulAmt1, VT));
16533
16534     if (isPowerOf2_64(MulAmt2))
16535       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16536                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16537     else
16538       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16539                            DAG.getConstant(MulAmt2, VT));
16540
16541     // Do not add new nodes to DAG combiner worklist.
16542     DCI.CombineTo(N, NewMul, false);
16543   }
16544   return SDValue();
16545 }
16546
16547 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16548   SDValue N0 = N->getOperand(0);
16549   SDValue N1 = N->getOperand(1);
16550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16551   EVT VT = N0.getValueType();
16552
16553   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16554   // since the result of setcc_c is all zero's or all ones.
16555   if (VT.isInteger() && !VT.isVector() &&
16556       N1C && N0.getOpcode() == ISD::AND &&
16557       N0.getOperand(1).getOpcode() == ISD::Constant) {
16558     SDValue N00 = N0.getOperand(0);
16559     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16560         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16561           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16562          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16563       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16564       APInt ShAmt = N1C->getAPIntValue();
16565       Mask = Mask.shl(ShAmt);
16566       if (Mask != 0)
16567         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16568                            N00, DAG.getConstant(Mask, VT));
16569     }
16570   }
16571
16572   // Hardware support for vector shifts is sparse which makes us scalarize the
16573   // vector operations in many cases. Also, on sandybridge ADD is faster than
16574   // shl.
16575   // (shl V, 1) -> add V,V
16576   if (isSplatVector(N1.getNode())) {
16577     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16578     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16579     // We shift all of the values by one. In many cases we do not have
16580     // hardware support for this operation. This is better expressed as an ADD
16581     // of two values.
16582     if (N1C && (1 == N1C->getZExtValue())) {
16583       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16584     }
16585   }
16586
16587   return SDValue();
16588 }
16589
16590 /// \brief Returns a vector of 0s if the node in input is a vector logical
16591 /// shift by a constant amount which is known to be bigger than or equal 
16592 /// to the vector element size in bits.
16593 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16594                                       const X86Subtarget *Subtarget) {
16595   EVT VT = N->getValueType(0);
16596
16597   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16598       (!Subtarget->hasInt256() ||
16599        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16600     return SDValue();
16601
16602   SDValue Amt = N->getOperand(1);
16603   SDLoc DL(N);
16604   if (isSplatVector(Amt.getNode())) {
16605     SDValue SclrAmt = Amt->getOperand(0);
16606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16607       APInt ShiftAmt = C->getAPIntValue();
16608       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16609
16610       // SSE2/AVX2 logical shifts always return a vector of 0s
16611       // if the shift amount is bigger than or equal to 
16612       // the element size. The constant shift amount will be
16613       // encoded as a 8-bit immediate.
16614       if (ShiftAmt.trunc(8).uge(MaxAmount))
16615         return getZeroVector(VT, Subtarget, DAG, DL);
16616     }
16617   }
16618
16619   return SDValue();
16620 }
16621
16622 /// PerformShiftCombine - Combine shifts.
16623 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16624                                    TargetLowering::DAGCombinerInfo &DCI,
16625                                    const X86Subtarget *Subtarget) {
16626   if (N->getOpcode() == ISD::SHL) {
16627     SDValue V = PerformSHLCombine(N, DAG);
16628     if (V.getNode()) return V;
16629   }
16630
16631   if (N->getOpcode() != ISD::SRA) {
16632     // Try to fold this logical shift into a zero vector.
16633     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16634     if (V.getNode()) return V;
16635   }
16636
16637   return SDValue();
16638 }
16639
16640 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16641 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16642 // and friends.  Likewise for OR -> CMPNEQSS.
16643 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16644                             TargetLowering::DAGCombinerInfo &DCI,
16645                             const X86Subtarget *Subtarget) {
16646   unsigned opcode;
16647
16648   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16649   // we're requiring SSE2 for both.
16650   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16651     SDValue N0 = N->getOperand(0);
16652     SDValue N1 = N->getOperand(1);
16653     SDValue CMP0 = N0->getOperand(1);
16654     SDValue CMP1 = N1->getOperand(1);
16655     SDLoc DL(N);
16656
16657     // The SETCCs should both refer to the same CMP.
16658     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16659       return SDValue();
16660
16661     SDValue CMP00 = CMP0->getOperand(0);
16662     SDValue CMP01 = CMP0->getOperand(1);
16663     EVT     VT    = CMP00.getValueType();
16664
16665     if (VT == MVT::f32 || VT == MVT::f64) {
16666       bool ExpectingFlags = false;
16667       // Check for any users that want flags:
16668       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16669            !ExpectingFlags && UI != UE; ++UI)
16670         switch (UI->getOpcode()) {
16671         default:
16672         case ISD::BR_CC:
16673         case ISD::BRCOND:
16674         case ISD::SELECT:
16675           ExpectingFlags = true;
16676           break;
16677         case ISD::CopyToReg:
16678         case ISD::SIGN_EXTEND:
16679         case ISD::ZERO_EXTEND:
16680         case ISD::ANY_EXTEND:
16681           break;
16682         }
16683
16684       if (!ExpectingFlags) {
16685         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16686         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16687
16688         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16689           X86::CondCode tmp = cc0;
16690           cc0 = cc1;
16691           cc1 = tmp;
16692         }
16693
16694         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16695             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16696           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16697           X86ISD::NodeType NTOperator = is64BitFP ?
16698             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16699           // FIXME: need symbolic constants for these magic numbers.
16700           // See X86ATTInstPrinter.cpp:printSSECC().
16701           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16702           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16703                                               DAG.getConstant(x86cc, MVT::i8));
16704           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16705                                               OnesOrZeroesF);
16706           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16707                                       DAG.getConstant(1, MVT::i32));
16708           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16709           return OneBitOfTruth;
16710         }
16711       }
16712     }
16713   }
16714   return SDValue();
16715 }
16716
16717 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16718 /// so it can be folded inside ANDNP.
16719 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16720   EVT VT = N->getValueType(0);
16721
16722   // Match direct AllOnes for 128 and 256-bit vectors
16723   if (ISD::isBuildVectorAllOnes(N))
16724     return true;
16725
16726   // Look through a bit convert.
16727   if (N->getOpcode() == ISD::BITCAST)
16728     N = N->getOperand(0).getNode();
16729
16730   // Sometimes the operand may come from a insert_subvector building a 256-bit
16731   // allones vector
16732   if (VT.is256BitVector() &&
16733       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16734     SDValue V1 = N->getOperand(0);
16735     SDValue V2 = N->getOperand(1);
16736
16737     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16738         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16739         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16740         ISD::isBuildVectorAllOnes(V2.getNode()))
16741       return true;
16742   }
16743
16744   return false;
16745 }
16746
16747 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16748 // register. In most cases we actually compare or select YMM-sized registers
16749 // and mixing the two types creates horrible code. This method optimizes
16750 // some of the transition sequences.
16751 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16752                                  TargetLowering::DAGCombinerInfo &DCI,
16753                                  const X86Subtarget *Subtarget) {
16754   EVT VT = N->getValueType(0);
16755   if (!VT.is256BitVector())
16756     return SDValue();
16757
16758   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16759           N->getOpcode() == ISD::ZERO_EXTEND ||
16760           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16761
16762   SDValue Narrow = N->getOperand(0);
16763   EVT NarrowVT = Narrow->getValueType(0);
16764   if (!NarrowVT.is128BitVector())
16765     return SDValue();
16766
16767   if (Narrow->getOpcode() != ISD::XOR &&
16768       Narrow->getOpcode() != ISD::AND &&
16769       Narrow->getOpcode() != ISD::OR)
16770     return SDValue();
16771
16772   SDValue N0  = Narrow->getOperand(0);
16773   SDValue N1  = Narrow->getOperand(1);
16774   SDLoc DL(Narrow);
16775
16776   // The Left side has to be a trunc.
16777   if (N0.getOpcode() != ISD::TRUNCATE)
16778     return SDValue();
16779
16780   // The type of the truncated inputs.
16781   EVT WideVT = N0->getOperand(0)->getValueType(0);
16782   if (WideVT != VT)
16783     return SDValue();
16784
16785   // The right side has to be a 'trunc' or a constant vector.
16786   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16787   bool RHSConst = (isSplatVector(N1.getNode()) &&
16788                    isa<ConstantSDNode>(N1->getOperand(0)));
16789   if (!RHSTrunc && !RHSConst)
16790     return SDValue();
16791
16792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16793
16794   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16795     return SDValue();
16796
16797   // Set N0 and N1 to hold the inputs to the new wide operation.
16798   N0 = N0->getOperand(0);
16799   if (RHSConst) {
16800     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16801                      N1->getOperand(0));
16802     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16803     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16804   } else if (RHSTrunc) {
16805     N1 = N1->getOperand(0);
16806   }
16807
16808   // Generate the wide operation.
16809   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16810   unsigned Opcode = N->getOpcode();
16811   switch (Opcode) {
16812   case ISD::ANY_EXTEND:
16813     return Op;
16814   case ISD::ZERO_EXTEND: {
16815     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16816     APInt Mask = APInt::getAllOnesValue(InBits);
16817     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16818     return DAG.getNode(ISD::AND, DL, VT,
16819                        Op, DAG.getConstant(Mask, VT));
16820   }
16821   case ISD::SIGN_EXTEND:
16822     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16823                        Op, DAG.getValueType(NarrowVT));
16824   default:
16825     llvm_unreachable("Unexpected opcode");
16826   }
16827 }
16828
16829 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16830                                  TargetLowering::DAGCombinerInfo &DCI,
16831                                  const X86Subtarget *Subtarget) {
16832   EVT VT = N->getValueType(0);
16833   if (DCI.isBeforeLegalizeOps())
16834     return SDValue();
16835
16836   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16837   if (R.getNode())
16838     return R;
16839
16840   // Create BLSI, and BLSR instructions
16841   // BLSI is X & (-X)
16842   // BLSR is X & (X-1)
16843   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16844     SDValue N0 = N->getOperand(0);
16845     SDValue N1 = N->getOperand(1);
16846     SDLoc DL(N);
16847
16848     // Check LHS for neg
16849     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16850         isZero(N0.getOperand(0)))
16851       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16852
16853     // Check RHS for neg
16854     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16855         isZero(N1.getOperand(0)))
16856       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16857
16858     // Check LHS for X-1
16859     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16860         isAllOnes(N0.getOperand(1)))
16861       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16862
16863     // Check RHS for X-1
16864     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16865         isAllOnes(N1.getOperand(1)))
16866       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16867
16868     return SDValue();
16869   }
16870
16871   // Want to form ANDNP nodes:
16872   // 1) In the hopes of then easily combining them with OR and AND nodes
16873   //    to form PBLEND/PSIGN.
16874   // 2) To match ANDN packed intrinsics
16875   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16876     return SDValue();
16877
16878   SDValue N0 = N->getOperand(0);
16879   SDValue N1 = N->getOperand(1);
16880   SDLoc DL(N);
16881
16882   // Check LHS for vnot
16883   if (N0.getOpcode() == ISD::XOR &&
16884       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16885       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16886     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16887
16888   // Check RHS for vnot
16889   if (N1.getOpcode() == ISD::XOR &&
16890       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16891       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16892     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16893
16894   return SDValue();
16895 }
16896
16897 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16898                                 TargetLowering::DAGCombinerInfo &DCI,
16899                                 const X86Subtarget *Subtarget) {
16900   EVT VT = N->getValueType(0);
16901   if (DCI.isBeforeLegalizeOps())
16902     return SDValue();
16903
16904   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16905   if (R.getNode())
16906     return R;
16907
16908   SDValue N0 = N->getOperand(0);
16909   SDValue N1 = N->getOperand(1);
16910
16911   // look for psign/blend
16912   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16913     if (!Subtarget->hasSSSE3() ||
16914         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16915       return SDValue();
16916
16917     // Canonicalize pandn to RHS
16918     if (N0.getOpcode() == X86ISD::ANDNP)
16919       std::swap(N0, N1);
16920     // or (and (m, y), (pandn m, x))
16921     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16922       SDValue Mask = N1.getOperand(0);
16923       SDValue X    = N1.getOperand(1);
16924       SDValue Y;
16925       if (N0.getOperand(0) == Mask)
16926         Y = N0.getOperand(1);
16927       if (N0.getOperand(1) == Mask)
16928         Y = N0.getOperand(0);
16929
16930       // Check to see if the mask appeared in both the AND and ANDNP and
16931       if (!Y.getNode())
16932         return SDValue();
16933
16934       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16935       // Look through mask bitcast.
16936       if (Mask.getOpcode() == ISD::BITCAST)
16937         Mask = Mask.getOperand(0);
16938       if (X.getOpcode() == ISD::BITCAST)
16939         X = X.getOperand(0);
16940       if (Y.getOpcode() == ISD::BITCAST)
16941         Y = Y.getOperand(0);
16942
16943       EVT MaskVT = Mask.getValueType();
16944
16945       // Validate that the Mask operand is a vector sra node.
16946       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16947       // there is no psrai.b
16948       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16949       unsigned SraAmt = ~0;
16950       if (Mask.getOpcode() == ISD::SRA) {
16951         SDValue Amt = Mask.getOperand(1);
16952         if (isSplatVector(Amt.getNode())) {
16953           SDValue SclrAmt = Amt->getOperand(0);
16954           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16955             SraAmt = C->getZExtValue();
16956         }
16957       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16958         SDValue SraC = Mask.getOperand(1);
16959         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16960       }
16961       if ((SraAmt + 1) != EltBits)
16962         return SDValue();
16963
16964       SDLoc DL(N);
16965
16966       // Now we know we at least have a plendvb with the mask val.  See if
16967       // we can form a psignb/w/d.
16968       // psign = x.type == y.type == mask.type && y = sub(0, x);
16969       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16970           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16971           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16972         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16973                "Unsupported VT for PSIGN");
16974         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16975         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16976       }
16977       // PBLENDVB only available on SSE 4.1
16978       if (!Subtarget->hasSSE41())
16979         return SDValue();
16980
16981       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16982
16983       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16984       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16985       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16986       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16987       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16988     }
16989   }
16990
16991   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16992     return SDValue();
16993
16994   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16995   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16996     std::swap(N0, N1);
16997   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16998     return SDValue();
16999   if (!N0.hasOneUse() || !N1.hasOneUse())
17000     return SDValue();
17001
17002   SDValue ShAmt0 = N0.getOperand(1);
17003   if (ShAmt0.getValueType() != MVT::i8)
17004     return SDValue();
17005   SDValue ShAmt1 = N1.getOperand(1);
17006   if (ShAmt1.getValueType() != MVT::i8)
17007     return SDValue();
17008   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17009     ShAmt0 = ShAmt0.getOperand(0);
17010   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17011     ShAmt1 = ShAmt1.getOperand(0);
17012
17013   SDLoc DL(N);
17014   unsigned Opc = X86ISD::SHLD;
17015   SDValue Op0 = N0.getOperand(0);
17016   SDValue Op1 = N1.getOperand(0);
17017   if (ShAmt0.getOpcode() == ISD::SUB) {
17018     Opc = X86ISD::SHRD;
17019     std::swap(Op0, Op1);
17020     std::swap(ShAmt0, ShAmt1);
17021   }
17022
17023   unsigned Bits = VT.getSizeInBits();
17024   if (ShAmt1.getOpcode() == ISD::SUB) {
17025     SDValue Sum = ShAmt1.getOperand(0);
17026     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17027       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17028       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17029         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17030       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17031         return DAG.getNode(Opc, DL, VT,
17032                            Op0, Op1,
17033                            DAG.getNode(ISD::TRUNCATE, DL,
17034                                        MVT::i8, ShAmt0));
17035     }
17036   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17037     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17038     if (ShAmt0C &&
17039         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17040       return DAG.getNode(Opc, DL, VT,
17041                          N0.getOperand(0), N1.getOperand(0),
17042                          DAG.getNode(ISD::TRUNCATE, DL,
17043                                        MVT::i8, ShAmt0));
17044   }
17045
17046   return SDValue();
17047 }
17048
17049 // Generate NEG and CMOV for integer abs.
17050 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17051   EVT VT = N->getValueType(0);
17052
17053   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17054   // 8-bit integer abs to NEG and CMOV.
17055   if (VT.isInteger() && VT.getSizeInBits() == 8)
17056     return SDValue();
17057
17058   SDValue N0 = N->getOperand(0);
17059   SDValue N1 = N->getOperand(1);
17060   SDLoc DL(N);
17061
17062   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17063   // and change it to SUB and CMOV.
17064   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17065       N0.getOpcode() == ISD::ADD &&
17066       N0.getOperand(1) == N1 &&
17067       N1.getOpcode() == ISD::SRA &&
17068       N1.getOperand(0) == N0.getOperand(0))
17069     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17070       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17071         // Generate SUB & CMOV.
17072         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17073                                   DAG.getConstant(0, VT), N0.getOperand(0));
17074
17075         SDValue Ops[] = { N0.getOperand(0), Neg,
17076                           DAG.getConstant(X86::COND_GE, MVT::i8),
17077                           SDValue(Neg.getNode(), 1) };
17078         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17079                            Ops, array_lengthof(Ops));
17080       }
17081   return SDValue();
17082 }
17083
17084 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17085 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17086                                  TargetLowering::DAGCombinerInfo &DCI,
17087                                  const X86Subtarget *Subtarget) {
17088   EVT VT = N->getValueType(0);
17089   if (DCI.isBeforeLegalizeOps())
17090     return SDValue();
17091
17092   if (Subtarget->hasCMov()) {
17093     SDValue RV = performIntegerAbsCombine(N, DAG);
17094     if (RV.getNode())
17095       return RV;
17096   }
17097
17098   // Try forming BMI if it is available.
17099   if (!Subtarget->hasBMI())
17100     return SDValue();
17101
17102   if (VT != MVT::i32 && VT != MVT::i64)
17103     return SDValue();
17104
17105   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17106
17107   // Create BLSMSK instructions by finding X ^ (X-1)
17108   SDValue N0 = N->getOperand(0);
17109   SDValue N1 = N->getOperand(1);
17110   SDLoc DL(N);
17111
17112   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17113       isAllOnes(N0.getOperand(1)))
17114     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17115
17116   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17117       isAllOnes(N1.getOperand(1)))
17118     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17119
17120   return SDValue();
17121 }
17122
17123 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17124 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17125                                   TargetLowering::DAGCombinerInfo &DCI,
17126                                   const X86Subtarget *Subtarget) {
17127   LoadSDNode *Ld = cast<LoadSDNode>(N);
17128   EVT RegVT = Ld->getValueType(0);
17129   EVT MemVT = Ld->getMemoryVT();
17130   SDLoc dl(Ld);
17131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17132   unsigned RegSz = RegVT.getSizeInBits();
17133
17134   // On Sandybridge unaligned 256bit loads are inefficient.
17135   ISD::LoadExtType Ext = Ld->getExtensionType();
17136   unsigned Alignment = Ld->getAlignment();
17137   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17138   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17139       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17140     unsigned NumElems = RegVT.getVectorNumElements();
17141     if (NumElems < 2)
17142       return SDValue();
17143
17144     SDValue Ptr = Ld->getBasePtr();
17145     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17146
17147     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17148                                   NumElems/2);
17149     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17150                                 Ld->getPointerInfo(), Ld->isVolatile(),
17151                                 Ld->isNonTemporal(), Ld->isInvariant(),
17152                                 Alignment);
17153     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17154     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17155                                 Ld->getPointerInfo(), Ld->isVolatile(),
17156                                 Ld->isNonTemporal(), Ld->isInvariant(),
17157                                 std::min(16U, Alignment));
17158     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17159                              Load1.getValue(1),
17160                              Load2.getValue(1));
17161
17162     SDValue NewVec = DAG.getUNDEF(RegVT);
17163     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17164     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17165     return DCI.CombineTo(N, NewVec, TF, true);
17166   }
17167
17168   // If this is a vector EXT Load then attempt to optimize it using a
17169   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17170   // expansion is still better than scalar code.
17171   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17172   // emit a shuffle and a arithmetic shift.
17173   // TODO: It is possible to support ZExt by zeroing the undef values
17174   // during the shuffle phase or after the shuffle.
17175   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17176       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17177     assert(MemVT != RegVT && "Cannot extend to the same type");
17178     assert(MemVT.isVector() && "Must load a vector from memory");
17179
17180     unsigned NumElems = RegVT.getVectorNumElements();
17181     unsigned MemSz = MemVT.getSizeInBits();
17182     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17183
17184     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17185       return SDValue();
17186
17187     // All sizes must be a power of two.
17188     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17189       return SDValue();
17190
17191     // Attempt to load the original value using scalar loads.
17192     // Find the largest scalar type that divides the total loaded size.
17193     MVT SclrLoadTy = MVT::i8;
17194     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17195          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17196       MVT Tp = (MVT::SimpleValueType)tp;
17197       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17198         SclrLoadTy = Tp;
17199       }
17200     }
17201
17202     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17203     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17204         (64 <= MemSz))
17205       SclrLoadTy = MVT::f64;
17206
17207     // Calculate the number of scalar loads that we need to perform
17208     // in order to load our vector from memory.
17209     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17210     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17211       return SDValue();
17212
17213     unsigned loadRegZize = RegSz;
17214     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17215       loadRegZize /= 2;
17216
17217     // Represent our vector as a sequence of elements which are the
17218     // largest scalar that we can load.
17219     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17220       loadRegZize/SclrLoadTy.getSizeInBits());
17221
17222     // Represent the data using the same element type that is stored in
17223     // memory. In practice, we ''widen'' MemVT.
17224     EVT WideVecVT =
17225           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17226                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17227
17228     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17229       "Invalid vector type");
17230
17231     // We can't shuffle using an illegal type.
17232     if (!TLI.isTypeLegal(WideVecVT))
17233       return SDValue();
17234
17235     SmallVector<SDValue, 8> Chains;
17236     SDValue Ptr = Ld->getBasePtr();
17237     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17238                                         TLI.getPointerTy());
17239     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17240
17241     for (unsigned i = 0; i < NumLoads; ++i) {
17242       // Perform a single load.
17243       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17244                                        Ptr, Ld->getPointerInfo(),
17245                                        Ld->isVolatile(), Ld->isNonTemporal(),
17246                                        Ld->isInvariant(), Ld->getAlignment());
17247       Chains.push_back(ScalarLoad.getValue(1));
17248       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17249       // another round of DAGCombining.
17250       if (i == 0)
17251         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17252       else
17253         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17254                           ScalarLoad, DAG.getIntPtrConstant(i));
17255
17256       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17257     }
17258
17259     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17260                                Chains.size());
17261
17262     // Bitcast the loaded value to a vector of the original element type, in
17263     // the size of the target vector type.
17264     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17265     unsigned SizeRatio = RegSz/MemSz;
17266
17267     if (Ext == ISD::SEXTLOAD) {
17268       // If we have SSE4.1 we can directly emit a VSEXT node.
17269       if (Subtarget->hasSSE41()) {
17270         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17271         return DCI.CombineTo(N, Sext, TF, true);
17272       }
17273
17274       // Otherwise we'll shuffle the small elements in the high bits of the
17275       // larger type and perform an arithmetic shift. If the shift is not legal
17276       // it's better to scalarize.
17277       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17278         return SDValue();
17279
17280       // Redistribute the loaded elements into the different locations.
17281       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17282       for (unsigned i = 0; i != NumElems; ++i)
17283         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17284
17285       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17286                                            DAG.getUNDEF(WideVecVT),
17287                                            &ShuffleVec[0]);
17288
17289       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17290
17291       // Build the arithmetic shift.
17292       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17293                      MemVT.getVectorElementType().getSizeInBits();
17294       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17295                           DAG.getConstant(Amt, RegVT));
17296
17297       return DCI.CombineTo(N, Shuff, TF, true);
17298     }
17299
17300     // Redistribute the loaded elements into the different locations.
17301     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17302     for (unsigned i = 0; i != NumElems; ++i)
17303       ShuffleVec[i*SizeRatio] = i;
17304
17305     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17306                                          DAG.getUNDEF(WideVecVT),
17307                                          &ShuffleVec[0]);
17308
17309     // Bitcast to the requested type.
17310     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17311     // Replace the original load with the new sequence
17312     // and return the new chain.
17313     return DCI.CombineTo(N, Shuff, TF, true);
17314   }
17315
17316   return SDValue();
17317 }
17318
17319 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17320 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17321                                    const X86Subtarget *Subtarget) {
17322   StoreSDNode *St = cast<StoreSDNode>(N);
17323   EVT VT = St->getValue().getValueType();
17324   EVT StVT = St->getMemoryVT();
17325   SDLoc dl(St);
17326   SDValue StoredVal = St->getOperand(1);
17327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17328
17329   // If we are saving a concatenation of two XMM registers, perform two stores.
17330   // On Sandy Bridge, 256-bit memory operations are executed by two
17331   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17332   // memory  operation.
17333   unsigned Alignment = St->getAlignment();
17334   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17335   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17336       StVT == VT && !IsAligned) {
17337     unsigned NumElems = VT.getVectorNumElements();
17338     if (NumElems < 2)
17339       return SDValue();
17340
17341     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17342     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17343
17344     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17345     SDValue Ptr0 = St->getBasePtr();
17346     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17347
17348     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17349                                 St->getPointerInfo(), St->isVolatile(),
17350                                 St->isNonTemporal(), Alignment);
17351     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17352                                 St->getPointerInfo(), St->isVolatile(),
17353                                 St->isNonTemporal(),
17354                                 std::min(16U, Alignment));
17355     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17356   }
17357
17358   // Optimize trunc store (of multiple scalars) to shuffle and store.
17359   // First, pack all of the elements in one place. Next, store to memory
17360   // in fewer chunks.
17361   if (St->isTruncatingStore() && VT.isVector()) {
17362     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17363     unsigned NumElems = VT.getVectorNumElements();
17364     assert(StVT != VT && "Cannot truncate to the same type");
17365     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17366     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17367
17368     // From, To sizes and ElemCount must be pow of two
17369     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17370     // We are going to use the original vector elt for storing.
17371     // Accumulated smaller vector elements must be a multiple of the store size.
17372     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17373
17374     unsigned SizeRatio  = FromSz / ToSz;
17375
17376     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17377
17378     // Create a type on which we perform the shuffle
17379     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17380             StVT.getScalarType(), NumElems*SizeRatio);
17381
17382     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17383
17384     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17385     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17386     for (unsigned i = 0; i != NumElems; ++i)
17387       ShuffleVec[i] = i * SizeRatio;
17388
17389     // Can't shuffle using an illegal type.
17390     if (!TLI.isTypeLegal(WideVecVT))
17391       return SDValue();
17392
17393     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17394                                          DAG.getUNDEF(WideVecVT),
17395                                          &ShuffleVec[0]);
17396     // At this point all of the data is stored at the bottom of the
17397     // register. We now need to save it to mem.
17398
17399     // Find the largest store unit
17400     MVT StoreType = MVT::i8;
17401     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17402          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17403       MVT Tp = (MVT::SimpleValueType)tp;
17404       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17405         StoreType = Tp;
17406     }
17407
17408     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17409     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17410         (64 <= NumElems * ToSz))
17411       StoreType = MVT::f64;
17412
17413     // Bitcast the original vector into a vector of store-size units
17414     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17415             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17416     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17417     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17418     SmallVector<SDValue, 8> Chains;
17419     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17420                                         TLI.getPointerTy());
17421     SDValue Ptr = St->getBasePtr();
17422
17423     // Perform one or more big stores into memory.
17424     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17425       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17426                                    StoreType, ShuffWide,
17427                                    DAG.getIntPtrConstant(i));
17428       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17429                                 St->getPointerInfo(), St->isVolatile(),
17430                                 St->isNonTemporal(), St->getAlignment());
17431       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17432       Chains.push_back(Ch);
17433     }
17434
17435     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17436                                Chains.size());
17437   }
17438
17439   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17440   // the FP state in cases where an emms may be missing.
17441   // A preferable solution to the general problem is to figure out the right
17442   // places to insert EMMS.  This qualifies as a quick hack.
17443
17444   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17445   if (VT.getSizeInBits() != 64)
17446     return SDValue();
17447
17448   const Function *F = DAG.getMachineFunction().getFunction();
17449   bool NoImplicitFloatOps = F->getAttributes().
17450     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17451   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17452                      && Subtarget->hasSSE2();
17453   if ((VT.isVector() ||
17454        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17455       isa<LoadSDNode>(St->getValue()) &&
17456       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17457       St->getChain().hasOneUse() && !St->isVolatile()) {
17458     SDNode* LdVal = St->getValue().getNode();
17459     LoadSDNode *Ld = 0;
17460     int TokenFactorIndex = -1;
17461     SmallVector<SDValue, 8> Ops;
17462     SDNode* ChainVal = St->getChain().getNode();
17463     // Must be a store of a load.  We currently handle two cases:  the load
17464     // is a direct child, and it's under an intervening TokenFactor.  It is
17465     // possible to dig deeper under nested TokenFactors.
17466     if (ChainVal == LdVal)
17467       Ld = cast<LoadSDNode>(St->getChain());
17468     else if (St->getValue().hasOneUse() &&
17469              ChainVal->getOpcode() == ISD::TokenFactor) {
17470       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17471         if (ChainVal->getOperand(i).getNode() == LdVal) {
17472           TokenFactorIndex = i;
17473           Ld = cast<LoadSDNode>(St->getValue());
17474         } else
17475           Ops.push_back(ChainVal->getOperand(i));
17476       }
17477     }
17478
17479     if (!Ld || !ISD::isNormalLoad(Ld))
17480       return SDValue();
17481
17482     // If this is not the MMX case, i.e. we are just turning i64 load/store
17483     // into f64 load/store, avoid the transformation if there are multiple
17484     // uses of the loaded value.
17485     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17486       return SDValue();
17487
17488     SDLoc LdDL(Ld);
17489     SDLoc StDL(N);
17490     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17491     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17492     // pair instead.
17493     if (Subtarget->is64Bit() || F64IsLegal) {
17494       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17495       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17496                                   Ld->getPointerInfo(), Ld->isVolatile(),
17497                                   Ld->isNonTemporal(), Ld->isInvariant(),
17498                                   Ld->getAlignment());
17499       SDValue NewChain = NewLd.getValue(1);
17500       if (TokenFactorIndex != -1) {
17501         Ops.push_back(NewChain);
17502         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17503                                Ops.size());
17504       }
17505       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17506                           St->getPointerInfo(),
17507                           St->isVolatile(), St->isNonTemporal(),
17508                           St->getAlignment());
17509     }
17510
17511     // Otherwise, lower to two pairs of 32-bit loads / stores.
17512     SDValue LoAddr = Ld->getBasePtr();
17513     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17514                                  DAG.getConstant(4, MVT::i32));
17515
17516     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17517                                Ld->getPointerInfo(),
17518                                Ld->isVolatile(), Ld->isNonTemporal(),
17519                                Ld->isInvariant(), Ld->getAlignment());
17520     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17521                                Ld->getPointerInfo().getWithOffset(4),
17522                                Ld->isVolatile(), Ld->isNonTemporal(),
17523                                Ld->isInvariant(),
17524                                MinAlign(Ld->getAlignment(), 4));
17525
17526     SDValue NewChain = LoLd.getValue(1);
17527     if (TokenFactorIndex != -1) {
17528       Ops.push_back(LoLd);
17529       Ops.push_back(HiLd);
17530       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17531                              Ops.size());
17532     }
17533
17534     LoAddr = St->getBasePtr();
17535     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17536                          DAG.getConstant(4, MVT::i32));
17537
17538     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17539                                 St->getPointerInfo(),
17540                                 St->isVolatile(), St->isNonTemporal(),
17541                                 St->getAlignment());
17542     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17543                                 St->getPointerInfo().getWithOffset(4),
17544                                 St->isVolatile(),
17545                                 St->isNonTemporal(),
17546                                 MinAlign(St->getAlignment(), 4));
17547     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17548   }
17549   return SDValue();
17550 }
17551
17552 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17553 /// and return the operands for the horizontal operation in LHS and RHS.  A
17554 /// horizontal operation performs the binary operation on successive elements
17555 /// of its first operand, then on successive elements of its second operand,
17556 /// returning the resulting values in a vector.  For example, if
17557 ///   A = < float a0, float a1, float a2, float a3 >
17558 /// and
17559 ///   B = < float b0, float b1, float b2, float b3 >
17560 /// then the result of doing a horizontal operation on A and B is
17561 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17562 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17563 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17564 /// set to A, RHS to B, and the routine returns 'true'.
17565 /// Note that the binary operation should have the property that if one of the
17566 /// operands is UNDEF then the result is UNDEF.
17567 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17568   // Look for the following pattern: if
17569   //   A = < float a0, float a1, float a2, float a3 >
17570   //   B = < float b0, float b1, float b2, float b3 >
17571   // and
17572   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17573   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17574   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17575   // which is A horizontal-op B.
17576
17577   // At least one of the operands should be a vector shuffle.
17578   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17579       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17580     return false;
17581
17582   EVT VT = LHS.getValueType();
17583
17584   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17585          "Unsupported vector type for horizontal add/sub");
17586
17587   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17588   // operate independently on 128-bit lanes.
17589   unsigned NumElts = VT.getVectorNumElements();
17590   unsigned NumLanes = VT.getSizeInBits()/128;
17591   unsigned NumLaneElts = NumElts / NumLanes;
17592   assert((NumLaneElts % 2 == 0) &&
17593          "Vector type should have an even number of elements in each lane");
17594   unsigned HalfLaneElts = NumLaneElts/2;
17595
17596   // View LHS in the form
17597   //   LHS = VECTOR_SHUFFLE A, B, LMask
17598   // If LHS is not a shuffle then pretend it is the shuffle
17599   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17600   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17601   // type VT.
17602   SDValue A, B;
17603   SmallVector<int, 16> LMask(NumElts);
17604   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17605     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17606       A = LHS.getOperand(0);
17607     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17608       B = LHS.getOperand(1);
17609     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17610     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17611   } else {
17612     if (LHS.getOpcode() != ISD::UNDEF)
17613       A = LHS;
17614     for (unsigned i = 0; i != NumElts; ++i)
17615       LMask[i] = i;
17616   }
17617
17618   // Likewise, view RHS in the form
17619   //   RHS = VECTOR_SHUFFLE C, D, RMask
17620   SDValue C, D;
17621   SmallVector<int, 16> RMask(NumElts);
17622   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17623     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17624       C = RHS.getOperand(0);
17625     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17626       D = RHS.getOperand(1);
17627     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17628     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17629   } else {
17630     if (RHS.getOpcode() != ISD::UNDEF)
17631       C = RHS;
17632     for (unsigned i = 0; i != NumElts; ++i)
17633       RMask[i] = i;
17634   }
17635
17636   // Check that the shuffles are both shuffling the same vectors.
17637   if (!(A == C && B == D) && !(A == D && B == C))
17638     return false;
17639
17640   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17641   if (!A.getNode() && !B.getNode())
17642     return false;
17643
17644   // If A and B occur in reverse order in RHS, then "swap" them (which means
17645   // rewriting the mask).
17646   if (A != C)
17647     CommuteVectorShuffleMask(RMask, NumElts);
17648
17649   // At this point LHS and RHS are equivalent to
17650   //   LHS = VECTOR_SHUFFLE A, B, LMask
17651   //   RHS = VECTOR_SHUFFLE A, B, RMask
17652   // Check that the masks correspond to performing a horizontal operation.
17653   for (unsigned i = 0; i != NumElts; ++i) {
17654     int LIdx = LMask[i], RIdx = RMask[i];
17655
17656     // Ignore any UNDEF components.
17657     if (LIdx < 0 || RIdx < 0 ||
17658         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17659         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17660       continue;
17661
17662     // Check that successive elements are being operated on.  If not, this is
17663     // not a horizontal operation.
17664     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17665     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17666     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17667     if (!(LIdx == Index && RIdx == Index + 1) &&
17668         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17669       return false;
17670   }
17671
17672   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17673   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17674   return true;
17675 }
17676
17677 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17678 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17679                                   const X86Subtarget *Subtarget) {
17680   EVT VT = N->getValueType(0);
17681   SDValue LHS = N->getOperand(0);
17682   SDValue RHS = N->getOperand(1);
17683
17684   // Try to synthesize horizontal adds from adds of shuffles.
17685   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17686        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17687       isHorizontalBinOp(LHS, RHS, true))
17688     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17689   return SDValue();
17690 }
17691
17692 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17693 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17694                                   const X86Subtarget *Subtarget) {
17695   EVT VT = N->getValueType(0);
17696   SDValue LHS = N->getOperand(0);
17697   SDValue RHS = N->getOperand(1);
17698
17699   // Try to synthesize horizontal subs from subs of shuffles.
17700   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17701        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17702       isHorizontalBinOp(LHS, RHS, false))
17703     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17704   return SDValue();
17705 }
17706
17707 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17708 /// X86ISD::FXOR nodes.
17709 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17710   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17711   // F[X]OR(0.0, x) -> x
17712   // F[X]OR(x, 0.0) -> x
17713   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17714     if (C->getValueAPF().isPosZero())
17715       return N->getOperand(1);
17716   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17717     if (C->getValueAPF().isPosZero())
17718       return N->getOperand(0);
17719   return SDValue();
17720 }
17721
17722 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17723 /// X86ISD::FMAX nodes.
17724 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17725   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17726
17727   // Only perform optimizations if UnsafeMath is used.
17728   if (!DAG.getTarget().Options.UnsafeFPMath)
17729     return SDValue();
17730
17731   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17732   // into FMINC and FMAXC, which are Commutative operations.
17733   unsigned NewOp = 0;
17734   switch (N->getOpcode()) {
17735     default: llvm_unreachable("unknown opcode");
17736     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17737     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17738   }
17739
17740   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17741                      N->getOperand(0), N->getOperand(1));
17742 }
17743
17744 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17745 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17746   // FAND(0.0, x) -> 0.0
17747   // FAND(x, 0.0) -> 0.0
17748   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17749     if (C->getValueAPF().isPosZero())
17750       return N->getOperand(0);
17751   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17752     if (C->getValueAPF().isPosZero())
17753       return N->getOperand(1);
17754   return SDValue();
17755 }
17756
17757 static SDValue PerformBTCombine(SDNode *N,
17758                                 SelectionDAG &DAG,
17759                                 TargetLowering::DAGCombinerInfo &DCI) {
17760   // BT ignores high bits in the bit index operand.
17761   SDValue Op1 = N->getOperand(1);
17762   if (Op1.hasOneUse()) {
17763     unsigned BitWidth = Op1.getValueSizeInBits();
17764     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17765     APInt KnownZero, KnownOne;
17766     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17767                                           !DCI.isBeforeLegalizeOps());
17768     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17769     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17770         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17771       DCI.CommitTargetLoweringOpt(TLO);
17772   }
17773   return SDValue();
17774 }
17775
17776 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17777   SDValue Op = N->getOperand(0);
17778   if (Op.getOpcode() == ISD::BITCAST)
17779     Op = Op.getOperand(0);
17780   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17781   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17782       VT.getVectorElementType().getSizeInBits() ==
17783       OpVT.getVectorElementType().getSizeInBits()) {
17784     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17785   }
17786   return SDValue();
17787 }
17788
17789 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17790                                                const X86Subtarget *Subtarget) {
17791   EVT VT = N->getValueType(0);
17792   if (!VT.isVector())
17793     return SDValue();
17794
17795   SDValue N0 = N->getOperand(0);
17796   SDValue N1 = N->getOperand(1);
17797   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17798   SDLoc dl(N);
17799
17800   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17801   // both SSE and AVX2 since there is no sign-extended shift right
17802   // operation on a vector with 64-bit elements.
17803   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17804   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17805   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17806       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17807     SDValue N00 = N0.getOperand(0);
17808
17809     // EXTLOAD has a better solution on AVX2,
17810     // it may be replaced with X86ISD::VSEXT node.
17811     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17812       if (!ISD::isNormalLoad(N00.getNode()))
17813         return SDValue();
17814
17815     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17816         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17817                                   N00, N1);
17818       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17819     }
17820   }
17821   return SDValue();
17822 }
17823
17824 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17825                                   TargetLowering::DAGCombinerInfo &DCI,
17826                                   const X86Subtarget *Subtarget) {
17827   if (!DCI.isBeforeLegalizeOps())
17828     return SDValue();
17829
17830   if (!Subtarget->hasFp256())
17831     return SDValue();
17832
17833   EVT VT = N->getValueType(0);
17834   if (VT.isVector() && VT.getSizeInBits() == 256) {
17835     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17836     if (R.getNode())
17837       return R;
17838   }
17839
17840   return SDValue();
17841 }
17842
17843 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17844                                  const X86Subtarget* Subtarget) {
17845   SDLoc dl(N);
17846   EVT VT = N->getValueType(0);
17847
17848   // Let legalize expand this if it isn't a legal type yet.
17849   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17850     return SDValue();
17851
17852   EVT ScalarVT = VT.getScalarType();
17853   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17854       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17855     return SDValue();
17856
17857   SDValue A = N->getOperand(0);
17858   SDValue B = N->getOperand(1);
17859   SDValue C = N->getOperand(2);
17860
17861   bool NegA = (A.getOpcode() == ISD::FNEG);
17862   bool NegB = (B.getOpcode() == ISD::FNEG);
17863   bool NegC = (C.getOpcode() == ISD::FNEG);
17864
17865   // Negative multiplication when NegA xor NegB
17866   bool NegMul = (NegA != NegB);
17867   if (NegA)
17868     A = A.getOperand(0);
17869   if (NegB)
17870     B = B.getOperand(0);
17871   if (NegC)
17872     C = C.getOperand(0);
17873
17874   unsigned Opcode;
17875   if (!NegMul)
17876     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17877   else
17878     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17879
17880   return DAG.getNode(Opcode, dl, VT, A, B, C);
17881 }
17882
17883 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17884                                   TargetLowering::DAGCombinerInfo &DCI,
17885                                   const X86Subtarget *Subtarget) {
17886   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17887   //           (and (i32 x86isd::setcc_carry), 1)
17888   // This eliminates the zext. This transformation is necessary because
17889   // ISD::SETCC is always legalized to i8.
17890   SDLoc dl(N);
17891   SDValue N0 = N->getOperand(0);
17892   EVT VT = N->getValueType(0);
17893
17894   if (N0.getOpcode() == ISD::AND &&
17895       N0.hasOneUse() &&
17896       N0.getOperand(0).hasOneUse()) {
17897     SDValue N00 = N0.getOperand(0);
17898     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17899       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17900       if (!C || C->getZExtValue() != 1)
17901         return SDValue();
17902       return DAG.getNode(ISD::AND, dl, VT,
17903                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17904                                      N00.getOperand(0), N00.getOperand(1)),
17905                          DAG.getConstant(1, VT));
17906     }
17907   }
17908
17909   if (VT.is256BitVector()) {
17910     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17911     if (R.getNode())
17912       return R;
17913   }
17914
17915   return SDValue();
17916 }
17917
17918 // Optimize x == -y --> x+y == 0
17919 //          x != -y --> x+y != 0
17920 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17921   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17922   SDValue LHS = N->getOperand(0);
17923   SDValue RHS = N->getOperand(1);
17924
17925   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17926     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17927       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17928         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17929                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17930         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17931                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17932       }
17933   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17935       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17936         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17937                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17938         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17939                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17940       }
17941   return SDValue();
17942 }
17943
17944 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17945 // as "sbb reg,reg", since it can be extended without zext and produces
17946 // an all-ones bit which is more useful than 0/1 in some cases.
17947 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17948   return DAG.getNode(ISD::AND, DL, MVT::i8,
17949                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17950                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17951                      DAG.getConstant(1, MVT::i8));
17952 }
17953
17954 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17955 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17956                                    TargetLowering::DAGCombinerInfo &DCI,
17957                                    const X86Subtarget *Subtarget) {
17958   SDLoc DL(N);
17959   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17960   SDValue EFLAGS = N->getOperand(1);
17961
17962   if (CC == X86::COND_A) {
17963     // Try to convert COND_A into COND_B in an attempt to facilitate
17964     // materializing "setb reg".
17965     //
17966     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17967     // cannot take an immediate as its first operand.
17968     //
17969     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17970         EFLAGS.getValueType().isInteger() &&
17971         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17972       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17973                                    EFLAGS.getNode()->getVTList(),
17974                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17975       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17976       return MaterializeSETB(DL, NewEFLAGS, DAG);
17977     }
17978   }
17979
17980   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17981   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17982   // cases.
17983   if (CC == X86::COND_B)
17984     return MaterializeSETB(DL, EFLAGS, DAG);
17985
17986   SDValue Flags;
17987
17988   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17989   if (Flags.getNode()) {
17990     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17991     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17992   }
17993
17994   return SDValue();
17995 }
17996
17997 // Optimize branch condition evaluation.
17998 //
17999 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18000                                     TargetLowering::DAGCombinerInfo &DCI,
18001                                     const X86Subtarget *Subtarget) {
18002   SDLoc DL(N);
18003   SDValue Chain = N->getOperand(0);
18004   SDValue Dest = N->getOperand(1);
18005   SDValue EFLAGS = N->getOperand(3);
18006   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18007
18008   SDValue Flags;
18009
18010   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18011   if (Flags.getNode()) {
18012     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18013     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18014                        Flags);
18015   }
18016
18017   return SDValue();
18018 }
18019
18020 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18021                                         const X86TargetLowering *XTLI) {
18022   SDValue Op0 = N->getOperand(0);
18023   EVT InVT = Op0->getValueType(0);
18024
18025   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18026   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18027     SDLoc dl(N);
18028     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18029     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18030     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18031   }
18032
18033   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18034   // a 32-bit target where SSE doesn't support i64->FP operations.
18035   if (Op0.getOpcode() == ISD::LOAD) {
18036     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18037     EVT VT = Ld->getValueType(0);
18038     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18039         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18040         !XTLI->getSubtarget()->is64Bit() &&
18041         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18042       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18043                                           Ld->getChain(), Op0, DAG);
18044       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18045       return FILDChain;
18046     }
18047   }
18048   return SDValue();
18049 }
18050
18051 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18052 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18053                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18054   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18055   // the result is either zero or one (depending on the input carry bit).
18056   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18057   if (X86::isZeroNode(N->getOperand(0)) &&
18058       X86::isZeroNode(N->getOperand(1)) &&
18059       // We don't have a good way to replace an EFLAGS use, so only do this when
18060       // dead right now.
18061       SDValue(N, 1).use_empty()) {
18062     SDLoc DL(N);
18063     EVT VT = N->getValueType(0);
18064     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18065     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18066                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18067                                            DAG.getConstant(X86::COND_B,MVT::i8),
18068                                            N->getOperand(2)),
18069                                DAG.getConstant(1, VT));
18070     return DCI.CombineTo(N, Res1, CarryOut);
18071   }
18072
18073   return SDValue();
18074 }
18075
18076 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18077 //      (add Y, (setne X, 0)) -> sbb -1, Y
18078 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18079 //      (sub (setne X, 0), Y) -> adc -1, Y
18080 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18081   SDLoc DL(N);
18082
18083   // Look through ZExts.
18084   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18085   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18086     return SDValue();
18087
18088   SDValue SetCC = Ext.getOperand(0);
18089   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18090     return SDValue();
18091
18092   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18093   if (CC != X86::COND_E && CC != X86::COND_NE)
18094     return SDValue();
18095
18096   SDValue Cmp = SetCC.getOperand(1);
18097   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18098       !X86::isZeroNode(Cmp.getOperand(1)) ||
18099       !Cmp.getOperand(0).getValueType().isInteger())
18100     return SDValue();
18101
18102   SDValue CmpOp0 = Cmp.getOperand(0);
18103   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18104                                DAG.getConstant(1, CmpOp0.getValueType()));
18105
18106   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18107   if (CC == X86::COND_NE)
18108     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18109                        DL, OtherVal.getValueType(), OtherVal,
18110                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18111   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18112                      DL, OtherVal.getValueType(), OtherVal,
18113                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18114 }
18115
18116 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18117 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18118                                  const X86Subtarget *Subtarget) {
18119   EVT VT = N->getValueType(0);
18120   SDValue Op0 = N->getOperand(0);
18121   SDValue Op1 = N->getOperand(1);
18122
18123   // Try to synthesize horizontal adds from adds of shuffles.
18124   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18125        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18126       isHorizontalBinOp(Op0, Op1, true))
18127     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18128
18129   return OptimizeConditionalInDecrement(N, DAG);
18130 }
18131
18132 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18133                                  const X86Subtarget *Subtarget) {
18134   SDValue Op0 = N->getOperand(0);
18135   SDValue Op1 = N->getOperand(1);
18136
18137   // X86 can't encode an immediate LHS of a sub. See if we can push the
18138   // negation into a preceding instruction.
18139   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18140     // If the RHS of the sub is a XOR with one use and a constant, invert the
18141     // immediate. Then add one to the LHS of the sub so we can turn
18142     // X-Y -> X+~Y+1, saving one register.
18143     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18144         isa<ConstantSDNode>(Op1.getOperand(1))) {
18145       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18146       EVT VT = Op0.getValueType();
18147       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18148                                    Op1.getOperand(0),
18149                                    DAG.getConstant(~XorC, VT));
18150       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18151                          DAG.getConstant(C->getAPIntValue()+1, VT));
18152     }
18153   }
18154
18155   // Try to synthesize horizontal adds from adds of shuffles.
18156   EVT VT = N->getValueType(0);
18157   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18158        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18159       isHorizontalBinOp(Op0, Op1, true))
18160     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18161
18162   return OptimizeConditionalInDecrement(N, DAG);
18163 }
18164
18165 /// performVZEXTCombine - Performs build vector combines
18166 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18167                                         TargetLowering::DAGCombinerInfo &DCI,
18168                                         const X86Subtarget *Subtarget) {
18169   // (vzext (bitcast (vzext (x)) -> (vzext x)
18170   SDValue In = N->getOperand(0);
18171   while (In.getOpcode() == ISD::BITCAST)
18172     In = In.getOperand(0);
18173
18174   if (In.getOpcode() != X86ISD::VZEXT)
18175     return SDValue();
18176
18177   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18178                      In.getOperand(0));
18179 }
18180
18181 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18182                                              DAGCombinerInfo &DCI) const {
18183   SelectionDAG &DAG = DCI.DAG;
18184   switch (N->getOpcode()) {
18185   default: break;
18186   case ISD::EXTRACT_VECTOR_ELT:
18187     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18188   case ISD::VSELECT:
18189   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18190   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18191   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18192   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18193   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18194   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18195   case ISD::SHL:
18196   case ISD::SRA:
18197   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18198   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18199   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18200   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18201   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18202   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18203   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18204   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18205   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18206   case X86ISD::FXOR:
18207   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18208   case X86ISD::FMIN:
18209   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18210   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18211   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18212   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18213   case ISD::ANY_EXTEND:
18214   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18215   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18216   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18217   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18218   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18219   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18220   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18221   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18222   case X86ISD::SHUFP:       // Handle all target specific shuffles
18223   case X86ISD::PALIGNR:
18224   case X86ISD::UNPCKH:
18225   case X86ISD::UNPCKL:
18226   case X86ISD::MOVHLPS:
18227   case X86ISD::MOVLHPS:
18228   case X86ISD::PSHUFD:
18229   case X86ISD::PSHUFHW:
18230   case X86ISD::PSHUFLW:
18231   case X86ISD::MOVSS:
18232   case X86ISD::MOVSD:
18233   case X86ISD::VPERMILP:
18234   case X86ISD::VPERM2X128:
18235   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18236   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18237   }
18238
18239   return SDValue();
18240 }
18241
18242 /// isTypeDesirableForOp - Return true if the target has native support for
18243 /// the specified value type and it is 'desirable' to use the type for the
18244 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18245 /// instruction encodings are longer and some i16 instructions are slow.
18246 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18247   if (!isTypeLegal(VT))
18248     return false;
18249   if (VT != MVT::i16)
18250     return true;
18251
18252   switch (Opc) {
18253   default:
18254     return true;
18255   case ISD::LOAD:
18256   case ISD::SIGN_EXTEND:
18257   case ISD::ZERO_EXTEND:
18258   case ISD::ANY_EXTEND:
18259   case ISD::SHL:
18260   case ISD::SRL:
18261   case ISD::SUB:
18262   case ISD::ADD:
18263   case ISD::MUL:
18264   case ISD::AND:
18265   case ISD::OR:
18266   case ISD::XOR:
18267     return false;
18268   }
18269 }
18270
18271 /// IsDesirableToPromoteOp - This method query the target whether it is
18272 /// beneficial for dag combiner to promote the specified node. If true, it
18273 /// should return the desired promotion type by reference.
18274 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18275   EVT VT = Op.getValueType();
18276   if (VT != MVT::i16)
18277     return false;
18278
18279   bool Promote = false;
18280   bool Commute = false;
18281   switch (Op.getOpcode()) {
18282   default: break;
18283   case ISD::LOAD: {
18284     LoadSDNode *LD = cast<LoadSDNode>(Op);
18285     // If the non-extending load has a single use and it's not live out, then it
18286     // might be folded.
18287     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18288                                                      Op.hasOneUse()*/) {
18289       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18290              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18291         // The only case where we'd want to promote LOAD (rather then it being
18292         // promoted as an operand is when it's only use is liveout.
18293         if (UI->getOpcode() != ISD::CopyToReg)
18294           return false;
18295       }
18296     }
18297     Promote = true;
18298     break;
18299   }
18300   case ISD::SIGN_EXTEND:
18301   case ISD::ZERO_EXTEND:
18302   case ISD::ANY_EXTEND:
18303     Promote = true;
18304     break;
18305   case ISD::SHL:
18306   case ISD::SRL: {
18307     SDValue N0 = Op.getOperand(0);
18308     // Look out for (store (shl (load), x)).
18309     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18310       return false;
18311     Promote = true;
18312     break;
18313   }
18314   case ISD::ADD:
18315   case ISD::MUL:
18316   case ISD::AND:
18317   case ISD::OR:
18318   case ISD::XOR:
18319     Commute = true;
18320     // fallthrough
18321   case ISD::SUB: {
18322     SDValue N0 = Op.getOperand(0);
18323     SDValue N1 = Op.getOperand(1);
18324     if (!Commute && MayFoldLoad(N1))
18325       return false;
18326     // Avoid disabling potential load folding opportunities.
18327     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18328       return false;
18329     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18330       return false;
18331     Promote = true;
18332   }
18333   }
18334
18335   PVT = MVT::i32;
18336   return Promote;
18337 }
18338
18339 //===----------------------------------------------------------------------===//
18340 //                           X86 Inline Assembly Support
18341 //===----------------------------------------------------------------------===//
18342
18343 namespace {
18344   // Helper to match a string separated by whitespace.
18345   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18346     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18347
18348     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18349       StringRef piece(*args[i]);
18350       if (!s.startswith(piece)) // Check if the piece matches.
18351         return false;
18352
18353       s = s.substr(piece.size());
18354       StringRef::size_type pos = s.find_first_not_of(" \t");
18355       if (pos == 0) // We matched a prefix.
18356         return false;
18357
18358       s = s.substr(pos);
18359     }
18360
18361     return s.empty();
18362   }
18363   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18364 }
18365
18366 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18367   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18368
18369   std::string AsmStr = IA->getAsmString();
18370
18371   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18372   if (!Ty || Ty->getBitWidth() % 16 != 0)
18373     return false;
18374
18375   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18376   SmallVector<StringRef, 4> AsmPieces;
18377   SplitString(AsmStr, AsmPieces, ";\n");
18378
18379   switch (AsmPieces.size()) {
18380   default: return false;
18381   case 1:
18382     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18383     // we will turn this bswap into something that will be lowered to logical
18384     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18385     // lower so don't worry about this.
18386     // bswap $0
18387     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18388         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18389         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18390         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18391         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18392         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18393       // No need to check constraints, nothing other than the equivalent of
18394       // "=r,0" would be valid here.
18395       return IntrinsicLowering::LowerToByteSwap(CI);
18396     }
18397
18398     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18399     if (CI->getType()->isIntegerTy(16) &&
18400         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18401         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18402          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18403       AsmPieces.clear();
18404       const std::string &ConstraintsStr = IA->getConstraintString();
18405       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18406       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18407       if (AsmPieces.size() == 4 &&
18408           AsmPieces[0] == "~{cc}" &&
18409           AsmPieces[1] == "~{dirflag}" &&
18410           AsmPieces[2] == "~{flags}" &&
18411           AsmPieces[3] == "~{fpsr}")
18412       return IntrinsicLowering::LowerToByteSwap(CI);
18413     }
18414     break;
18415   case 3:
18416     if (CI->getType()->isIntegerTy(32) &&
18417         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18418         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18419         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18420         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18421       AsmPieces.clear();
18422       const std::string &ConstraintsStr = IA->getConstraintString();
18423       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18424       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18425       if (AsmPieces.size() == 4 &&
18426           AsmPieces[0] == "~{cc}" &&
18427           AsmPieces[1] == "~{dirflag}" &&
18428           AsmPieces[2] == "~{flags}" &&
18429           AsmPieces[3] == "~{fpsr}")
18430         return IntrinsicLowering::LowerToByteSwap(CI);
18431     }
18432
18433     if (CI->getType()->isIntegerTy(64)) {
18434       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18435       if (Constraints.size() >= 2 &&
18436           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18437           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18438         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18439         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18440             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18441             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18442           return IntrinsicLowering::LowerToByteSwap(CI);
18443       }
18444     }
18445     break;
18446   }
18447   return false;
18448 }
18449
18450 /// getConstraintType - Given a constraint letter, return the type of
18451 /// constraint it is for this target.
18452 X86TargetLowering::ConstraintType
18453 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18454   if (Constraint.size() == 1) {
18455     switch (Constraint[0]) {
18456     case 'R':
18457     case 'q':
18458     case 'Q':
18459     case 'f':
18460     case 't':
18461     case 'u':
18462     case 'y':
18463     case 'x':
18464     case 'Y':
18465     case 'l':
18466       return C_RegisterClass;
18467     case 'a':
18468     case 'b':
18469     case 'c':
18470     case 'd':
18471     case 'S':
18472     case 'D':
18473     case 'A':
18474       return C_Register;
18475     case 'I':
18476     case 'J':
18477     case 'K':
18478     case 'L':
18479     case 'M':
18480     case 'N':
18481     case 'G':
18482     case 'C':
18483     case 'e':
18484     case 'Z':
18485       return C_Other;
18486     default:
18487       break;
18488     }
18489   }
18490   return TargetLowering::getConstraintType(Constraint);
18491 }
18492
18493 /// Examine constraint type and operand type and determine a weight value.
18494 /// This object must already have been set up with the operand type
18495 /// and the current alternative constraint selected.
18496 TargetLowering::ConstraintWeight
18497   X86TargetLowering::getSingleConstraintMatchWeight(
18498     AsmOperandInfo &info, const char *constraint) const {
18499   ConstraintWeight weight = CW_Invalid;
18500   Value *CallOperandVal = info.CallOperandVal;
18501     // If we don't have a value, we can't do a match,
18502     // but allow it at the lowest weight.
18503   if (CallOperandVal == NULL)
18504     return CW_Default;
18505   Type *type = CallOperandVal->getType();
18506   // Look at the constraint type.
18507   switch (*constraint) {
18508   default:
18509     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18510   case 'R':
18511   case 'q':
18512   case 'Q':
18513   case 'a':
18514   case 'b':
18515   case 'c':
18516   case 'd':
18517   case 'S':
18518   case 'D':
18519   case 'A':
18520     if (CallOperandVal->getType()->isIntegerTy())
18521       weight = CW_SpecificReg;
18522     break;
18523   case 'f':
18524   case 't':
18525   case 'u':
18526     if (type->isFloatingPointTy())
18527       weight = CW_SpecificReg;
18528     break;
18529   case 'y':
18530     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18531       weight = CW_SpecificReg;
18532     break;
18533   case 'x':
18534   case 'Y':
18535     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18536         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18537       weight = CW_Register;
18538     break;
18539   case 'I':
18540     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18541       if (C->getZExtValue() <= 31)
18542         weight = CW_Constant;
18543     }
18544     break;
18545   case 'J':
18546     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18547       if (C->getZExtValue() <= 63)
18548         weight = CW_Constant;
18549     }
18550     break;
18551   case 'K':
18552     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18553       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18554         weight = CW_Constant;
18555     }
18556     break;
18557   case 'L':
18558     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18559       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18560         weight = CW_Constant;
18561     }
18562     break;
18563   case 'M':
18564     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18565       if (C->getZExtValue() <= 3)
18566         weight = CW_Constant;
18567     }
18568     break;
18569   case 'N':
18570     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18571       if (C->getZExtValue() <= 0xff)
18572         weight = CW_Constant;
18573     }
18574     break;
18575   case 'G':
18576   case 'C':
18577     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18578       weight = CW_Constant;
18579     }
18580     break;
18581   case 'e':
18582     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18583       if ((C->getSExtValue() >= -0x80000000LL) &&
18584           (C->getSExtValue() <= 0x7fffffffLL))
18585         weight = CW_Constant;
18586     }
18587     break;
18588   case 'Z':
18589     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18590       if (C->getZExtValue() <= 0xffffffff)
18591         weight = CW_Constant;
18592     }
18593     break;
18594   }
18595   return weight;
18596 }
18597
18598 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18599 /// with another that has more specific requirements based on the type of the
18600 /// corresponding operand.
18601 const char *X86TargetLowering::
18602 LowerXConstraint(EVT ConstraintVT) const {
18603   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18604   // 'f' like normal targets.
18605   if (ConstraintVT.isFloatingPoint()) {
18606     if (Subtarget->hasSSE2())
18607       return "Y";
18608     if (Subtarget->hasSSE1())
18609       return "x";
18610   }
18611
18612   return TargetLowering::LowerXConstraint(ConstraintVT);
18613 }
18614
18615 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18616 /// vector.  If it is invalid, don't add anything to Ops.
18617 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18618                                                      std::string &Constraint,
18619                                                      std::vector<SDValue>&Ops,
18620                                                      SelectionDAG &DAG) const {
18621   SDValue Result(0, 0);
18622
18623   // Only support length 1 constraints for now.
18624   if (Constraint.length() > 1) return;
18625
18626   char ConstraintLetter = Constraint[0];
18627   switch (ConstraintLetter) {
18628   default: break;
18629   case 'I':
18630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18631       if (C->getZExtValue() <= 31) {
18632         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18633         break;
18634       }
18635     }
18636     return;
18637   case 'J':
18638     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18639       if (C->getZExtValue() <= 63) {
18640         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18641         break;
18642       }
18643     }
18644     return;
18645   case 'K':
18646     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18647       if (isInt<8>(C->getSExtValue())) {
18648         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18649         break;
18650       }
18651     }
18652     return;
18653   case 'N':
18654     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18655       if (C->getZExtValue() <= 255) {
18656         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18657         break;
18658       }
18659     }
18660     return;
18661   case 'e': {
18662     // 32-bit signed value
18663     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18664       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18665                                            C->getSExtValue())) {
18666         // Widen to 64 bits here to get it sign extended.
18667         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18668         break;
18669       }
18670     // FIXME gcc accepts some relocatable values here too, but only in certain
18671     // memory models; it's complicated.
18672     }
18673     return;
18674   }
18675   case 'Z': {
18676     // 32-bit unsigned value
18677     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18678       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18679                                            C->getZExtValue())) {
18680         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18681         break;
18682       }
18683     }
18684     // FIXME gcc accepts some relocatable values here too, but only in certain
18685     // memory models; it's complicated.
18686     return;
18687   }
18688   case 'i': {
18689     // Literal immediates are always ok.
18690     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18691       // Widen to 64 bits here to get it sign extended.
18692       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18693       break;
18694     }
18695
18696     // In any sort of PIC mode addresses need to be computed at runtime by
18697     // adding in a register or some sort of table lookup.  These can't
18698     // be used as immediates.
18699     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18700       return;
18701
18702     // If we are in non-pic codegen mode, we allow the address of a global (with
18703     // an optional displacement) to be used with 'i'.
18704     GlobalAddressSDNode *GA = 0;
18705     int64_t Offset = 0;
18706
18707     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18708     while (1) {
18709       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18710         Offset += GA->getOffset();
18711         break;
18712       } else if (Op.getOpcode() == ISD::ADD) {
18713         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18714           Offset += C->getZExtValue();
18715           Op = Op.getOperand(0);
18716           continue;
18717         }
18718       } else if (Op.getOpcode() == ISD::SUB) {
18719         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18720           Offset += -C->getZExtValue();
18721           Op = Op.getOperand(0);
18722           continue;
18723         }
18724       }
18725
18726       // Otherwise, this isn't something we can handle, reject it.
18727       return;
18728     }
18729
18730     const GlobalValue *GV = GA->getGlobal();
18731     // If we require an extra load to get this address, as in PIC mode, we
18732     // can't accept it.
18733     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18734                                                         getTargetMachine())))
18735       return;
18736
18737     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18738                                         GA->getValueType(0), Offset);
18739     break;
18740   }
18741   }
18742
18743   if (Result.getNode()) {
18744     Ops.push_back(Result);
18745     return;
18746   }
18747   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18748 }
18749
18750 std::pair<unsigned, const TargetRegisterClass*>
18751 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18752                                                 MVT VT) const {
18753   // First, see if this is a constraint that directly corresponds to an LLVM
18754   // register class.
18755   if (Constraint.size() == 1) {
18756     // GCC Constraint Letters
18757     switch (Constraint[0]) {
18758     default: break;
18759       // TODO: Slight differences here in allocation order and leaving
18760       // RIP in the class. Do they matter any more here than they do
18761       // in the normal allocation?
18762     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18763       if (Subtarget->is64Bit()) {
18764         if (VT == MVT::i32 || VT == MVT::f32)
18765           return std::make_pair(0U, &X86::GR32RegClass);
18766         if (VT == MVT::i16)
18767           return std::make_pair(0U, &X86::GR16RegClass);
18768         if (VT == MVT::i8 || VT == MVT::i1)
18769           return std::make_pair(0U, &X86::GR8RegClass);
18770         if (VT == MVT::i64 || VT == MVT::f64)
18771           return std::make_pair(0U, &X86::GR64RegClass);
18772         break;
18773       }
18774       // 32-bit fallthrough
18775     case 'Q':   // Q_REGS
18776       if (VT == MVT::i32 || VT == MVT::f32)
18777         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18778       if (VT == MVT::i16)
18779         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18780       if (VT == MVT::i8 || VT == MVT::i1)
18781         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18782       if (VT == MVT::i64)
18783         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18784       break;
18785     case 'r':   // GENERAL_REGS
18786     case 'l':   // INDEX_REGS
18787       if (VT == MVT::i8 || VT == MVT::i1)
18788         return std::make_pair(0U, &X86::GR8RegClass);
18789       if (VT == MVT::i16)
18790         return std::make_pair(0U, &X86::GR16RegClass);
18791       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18792         return std::make_pair(0U, &X86::GR32RegClass);
18793       return std::make_pair(0U, &X86::GR64RegClass);
18794     case 'R':   // LEGACY_REGS
18795       if (VT == MVT::i8 || VT == MVT::i1)
18796         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18797       if (VT == MVT::i16)
18798         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18799       if (VT == MVT::i32 || !Subtarget->is64Bit())
18800         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18801       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18802     case 'f':  // FP Stack registers.
18803       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18804       // value to the correct fpstack register class.
18805       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18806         return std::make_pair(0U, &X86::RFP32RegClass);
18807       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18808         return std::make_pair(0U, &X86::RFP64RegClass);
18809       return std::make_pair(0U, &X86::RFP80RegClass);
18810     case 'y':   // MMX_REGS if MMX allowed.
18811       if (!Subtarget->hasMMX()) break;
18812       return std::make_pair(0U, &X86::VR64RegClass);
18813     case 'Y':   // SSE_REGS if SSE2 allowed
18814       if (!Subtarget->hasSSE2()) break;
18815       // FALL THROUGH.
18816     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18817       if (!Subtarget->hasSSE1()) break;
18818
18819       switch (VT.SimpleTy) {
18820       default: break;
18821       // Scalar SSE types.
18822       case MVT::f32:
18823       case MVT::i32:
18824         return std::make_pair(0U, &X86::FR32RegClass);
18825       case MVT::f64:
18826       case MVT::i64:
18827         return std::make_pair(0U, &X86::FR64RegClass);
18828       // Vector types.
18829       case MVT::v16i8:
18830       case MVT::v8i16:
18831       case MVT::v4i32:
18832       case MVT::v2i64:
18833       case MVT::v4f32:
18834       case MVT::v2f64:
18835         return std::make_pair(0U, &X86::VR128RegClass);
18836       // AVX types.
18837       case MVT::v32i8:
18838       case MVT::v16i16:
18839       case MVT::v8i32:
18840       case MVT::v4i64:
18841       case MVT::v8f32:
18842       case MVT::v4f64:
18843         return std::make_pair(0U, &X86::VR256RegClass);
18844       case MVT::v8f64:
18845       case MVT::v16f32:
18846       case MVT::v16i32:
18847       case MVT::v8i64:
18848         return std::make_pair(0U, &X86::VR512RegClass);
18849       }
18850       break;
18851     }
18852   }
18853
18854   // Use the default implementation in TargetLowering to convert the register
18855   // constraint into a member of a register class.
18856   std::pair<unsigned, const TargetRegisterClass*> Res;
18857   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18858
18859   // Not found as a standard register?
18860   if (Res.second == 0) {
18861     // Map st(0) -> st(7) -> ST0
18862     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18863         tolower(Constraint[1]) == 's' &&
18864         tolower(Constraint[2]) == 't' &&
18865         Constraint[3] == '(' &&
18866         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18867         Constraint[5] == ')' &&
18868         Constraint[6] == '}') {
18869
18870       Res.first = X86::ST0+Constraint[4]-'0';
18871       Res.second = &X86::RFP80RegClass;
18872       return Res;
18873     }
18874
18875     // GCC allows "st(0)" to be called just plain "st".
18876     if (StringRef("{st}").equals_lower(Constraint)) {
18877       Res.first = X86::ST0;
18878       Res.second = &X86::RFP80RegClass;
18879       return Res;
18880     }
18881
18882     // flags -> EFLAGS
18883     if (StringRef("{flags}").equals_lower(Constraint)) {
18884       Res.first = X86::EFLAGS;
18885       Res.second = &X86::CCRRegClass;
18886       return Res;
18887     }
18888
18889     // 'A' means EAX + EDX.
18890     if (Constraint == "A") {
18891       Res.first = X86::EAX;
18892       Res.second = &X86::GR32_ADRegClass;
18893       return Res;
18894     }
18895     return Res;
18896   }
18897
18898   // Otherwise, check to see if this is a register class of the wrong value
18899   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18900   // turn into {ax},{dx}.
18901   if (Res.second->hasType(VT))
18902     return Res;   // Correct type already, nothing to do.
18903
18904   // All of the single-register GCC register classes map their values onto
18905   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18906   // really want an 8-bit or 32-bit register, map to the appropriate register
18907   // class and return the appropriate register.
18908   if (Res.second == &X86::GR16RegClass) {
18909     if (VT == MVT::i8 || VT == MVT::i1) {
18910       unsigned DestReg = 0;
18911       switch (Res.first) {
18912       default: break;
18913       case X86::AX: DestReg = X86::AL; break;
18914       case X86::DX: DestReg = X86::DL; break;
18915       case X86::CX: DestReg = X86::CL; break;
18916       case X86::BX: DestReg = X86::BL; break;
18917       }
18918       if (DestReg) {
18919         Res.first = DestReg;
18920         Res.second = &X86::GR8RegClass;
18921       }
18922     } else if (VT == MVT::i32 || VT == MVT::f32) {
18923       unsigned DestReg = 0;
18924       switch (Res.first) {
18925       default: break;
18926       case X86::AX: DestReg = X86::EAX; break;
18927       case X86::DX: DestReg = X86::EDX; break;
18928       case X86::CX: DestReg = X86::ECX; break;
18929       case X86::BX: DestReg = X86::EBX; break;
18930       case X86::SI: DestReg = X86::ESI; break;
18931       case X86::DI: DestReg = X86::EDI; break;
18932       case X86::BP: DestReg = X86::EBP; break;
18933       case X86::SP: DestReg = X86::ESP; break;
18934       }
18935       if (DestReg) {
18936         Res.first = DestReg;
18937         Res.second = &X86::GR32RegClass;
18938       }
18939     } else if (VT == MVT::i64 || VT == MVT::f64) {
18940       unsigned DestReg = 0;
18941       switch (Res.first) {
18942       default: break;
18943       case X86::AX: DestReg = X86::RAX; break;
18944       case X86::DX: DestReg = X86::RDX; break;
18945       case X86::CX: DestReg = X86::RCX; break;
18946       case X86::BX: DestReg = X86::RBX; break;
18947       case X86::SI: DestReg = X86::RSI; break;
18948       case X86::DI: DestReg = X86::RDI; break;
18949       case X86::BP: DestReg = X86::RBP; break;
18950       case X86::SP: DestReg = X86::RSP; break;
18951       }
18952       if (DestReg) {
18953         Res.first = DestReg;
18954         Res.second = &X86::GR64RegClass;
18955       }
18956     }
18957   } else if (Res.second == &X86::FR32RegClass ||
18958              Res.second == &X86::FR64RegClass ||
18959              Res.second == &X86::VR128RegClass ||
18960              Res.second == &X86::VR256RegClass ||
18961              Res.second == &X86::FR32XRegClass ||
18962              Res.second == &X86::FR64XRegClass ||
18963              Res.second == &X86::VR128XRegClass ||
18964              Res.second == &X86::VR256XRegClass ||
18965              Res.second == &X86::VR512RegClass) {
18966     // Handle references to XMM physical registers that got mapped into the
18967     // wrong class.  This can happen with constraints like {xmm0} where the
18968     // target independent register mapper will just pick the first match it can
18969     // find, ignoring the required type.
18970
18971     if (VT == MVT::f32 || VT == MVT::i32)
18972       Res.second = &X86::FR32RegClass;
18973     else if (VT == MVT::f64 || VT == MVT::i64)
18974       Res.second = &X86::FR64RegClass;
18975     else if (X86::VR128RegClass.hasType(VT))
18976       Res.second = &X86::VR128RegClass;
18977     else if (X86::VR256RegClass.hasType(VT))
18978       Res.second = &X86::VR256RegClass;
18979     else if (X86::VR512RegClass.hasType(VT))
18980       Res.second = &X86::VR512RegClass;
18981   }
18982
18983   return Res;
18984 }