15f4f06a12ded3977b9ee4331e70244ea2c6cc60
[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 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.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/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetKnownWindowsMSVC())
194     return new X86WindowsTargetObjectFile();
195   if (Subtarget->isTargetCOFF())
196     return new TargetLoweringObjectFileCOFF();
197   llvm_unreachable("unknown subtarget type");
198 }
199
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201   : TargetLowering(TM, createTLOF(TM)) {
202   Subtarget = &TM.getSubtarget<X86Subtarget>();
203   X86ScalarSSEf64 = Subtarget->hasSSE2();
204   X86ScalarSSEf32 = Subtarget->hasSSE1();
205   TD = getDataLayout();
206
207   resetOperationActions();
208 }
209
210 void X86TargetLowering::resetOperationActions() {
211   const TargetMachine &TM = getTargetMachine();
212   static bool FirstTimeThrough = true;
213
214   // If none of the target options have changed, then we don't need to reset the
215   // operation actions.
216   if (!FirstTimeThrough && TO == TM.Options) return;
217
218   if (!FirstTimeThrough) {
219     // Reinitialize the actions.
220     initActions();
221     FirstTimeThrough = false;
222   }
223
224   TO = TM.Options;
225
226   // Set up the TargetLowering object.
227   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228
229   // X86 is weird, it always uses i8 for shift amounts and setcc results.
230   setBooleanContents(ZeroOrOneBooleanContent);
231   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233
234   // For 64-bit since we have so many registers use the ILP scheduler, for
235   // 32-bit code use the register pressure specific scheduling.
236   // For Atom, always use ILP scheduling.
237   if (Subtarget->isAtom())
238     setSchedulingPreference(Sched::ILP);
239   else if (Subtarget->is64Bit())
240     setSchedulingPreference(Sched::ILP);
241   else
242     setSchedulingPreference(Sched::RegPressure);
243   const X86RegisterInfo *RegInfo =
244     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246
247   // Bypass expensive divides on Atom when compiling with O2
248   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249     addBypassSlowDiv(32, 8);
250     if (Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   // SETOEQ and SETUNE require checking two conditions.
306   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312
313   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314   // operation.
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
318
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322   } else if (!TM.Options.UseSoftFloat) {
323     // We have an algorithm for SSE2->double, and we turn this into a
324     // 64-bit FILD followed by conditional FADD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
326     // We have an algorithm for SSE2, and we turn this into a 64-bit
327     // FILD for other targets.
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
329   }
330
331   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332   // this operation.
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
335
336   if (!TM.Options.UseSoftFloat) {
337     // SSE has no i16 to fp conversion, only i32
338     if (X86ScalarSSEf32) {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
340       // f32 and f64 cases are Legal, f80 case is not
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     } else {
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
345     }
346   } else {
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
349   }
350
351   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
352   // are Legal, f80 is custom lowered.
353   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
354   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
355
356   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357   // this operation.
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
360
361   if (X86ScalarSSEf32) {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
363     // f32 and f64 cases are Legal, f80 case is not
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   } else {
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
368   }
369
370   // Handle FP_TO_UINT by promoting the destination to a larger signed
371   // conversion.
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
375
376   if (Subtarget->is64Bit()) {
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
379   } else if (!TM.Options.UseSoftFloat) {
380     // Since AVX is a superset of SSE3, only check for SSE here.
381     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382       // Expand FP_TO_UINT into a select.
383       // FIXME: We would like to use a Custom expander here eventually to do
384       // the optimal thing for SSE vs. the default expansion in the legalizer.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
386     else
387       // With SSE3 we can use fisttpll to convert to a signed i64; without
388       // SSE, we're stuck with a fistpll.
389       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
390   }
391
392   if (isTargetFTOL()) {
393     // Use the _ftol2 runtime function, which has a pseudo-instruction
394     // to handle its weird calling convention.
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
396   }
397
398   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399   if (!X86ScalarSSEf64) {
400     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
401     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
402     if (Subtarget->is64Bit()) {
403       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
404       // Without SSE, i64->f64 goes through memory.
405       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
406     }
407   }
408
409   // Scalar integer divide and remainder are lowered to use operations that
410   // produce two results, to match the available instructions. This exposes
411   // the two-result form to trivial CSE, which is able to combine x/y and x%y
412   // into a single instruction.
413   //
414   // Scalar integer multiply-high is also lowered to use two-result
415   // operations, to match the available instructions. However, plain multiply
416   // (low) operations are left as Legal, as there are single-result
417   // instructions for this in x86. Using the two-result multiply instructions
418   // when both high and low results are needed must be arranged by dagcombine.
419   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420     MVT VT = IntVTs[i];
421     setOperationAction(ISD::MULHS, VT, Expand);
422     setOperationAction(ISD::MULHU, VT, Expand);
423     setOperationAction(ISD::SDIV, VT, Expand);
424     setOperationAction(ISD::UDIV, VT, Expand);
425     setOperationAction(ISD::SREM, VT, Expand);
426     setOperationAction(ISD::UREM, VT, Expand);
427
428     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429     setOperationAction(ISD::ADDC, VT, Custom);
430     setOperationAction(ISD::ADDE, VT, Custom);
431     setOperationAction(ISD::SUBC, VT, Custom);
432     setOperationAction(ISD::SUBE, VT, Custom);
433   }
434
435   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
436   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
437   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
445   if (Subtarget->is64Bit())
446     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
450   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
454   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
455
456   // Promote the i8 variants and force them on up to i32 which has a shorter
457   // encoding.
458   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
460   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
462   if (Subtarget->hasBMI()) {
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
469     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasLZCNT()) {
475     // When promoting the i8 variants, force them to i32 for a shorter
476     // encoding.
477     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485   } else {
486     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
492     if (Subtarget->is64Bit()) {
493       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
494       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495     }
496   }
497
498   if (Subtarget->hasPOPCNT()) {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
500   } else {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
506   }
507
508   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
509
510   if (!Subtarget->hasMOVBE())
511     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
512
513   // These should be promoted to a larger select which is supported.
514   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
515   // X86 wants to expand cmov itself.
516   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
528   if (Subtarget->is64Bit()) {
529     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
530     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
531   }
532   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
533   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535   // support continuation, user-level threading, and etc.. As a result, no
536   // other SjLj exception interfaces are implemented and please don't build
537   // your own exception handling based on them.
538   // LLVM/Clang supports zero-cost DWARF exception handling.
539   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
541
542   // Darwin ABI issue.
543   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
544   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
547   if (Subtarget->is64Bit())
548     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
550   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
551   if (Subtarget->is64Bit()) {
552     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
553     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
554     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
555     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
556     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
557   }
558   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
562   if (Subtarget->is64Bit()) {
563     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
566   }
567
568   if (Subtarget->hasSSE1())
569     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
570
571   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
572
573   // Expand certain atomics
574   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575     MVT VT = IntVTs[i];
576     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
579   }
580
581   if (!Subtarget->is64Bit()) {
582     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
594   }
595
596   if (Subtarget->hasCmpxchg16b()) {
597     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
598   }
599
600   // FIXME - use subtarget debug flags
601   if (!Subtarget->isTargetDarwin() &&
602       !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                      MVT::i64 : MVT::i32, Custom);
641
642   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643     // f32 and f64 use SSE.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::FR64RegClass);
647
648     // Use ANDPD to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f64, Custom);
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f64, Custom);
654     setOperationAction(ISD::FNEG , MVT::f32, Custom);
655
656     // Use ANDPD and ORPD to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // Lower this to FGETSIGNx86 plus an AND.
661     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663
664     // We don't support sin/cos/fmod
665     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
666     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
667     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671
672     // Expand FP immediates into loads from the stack, except for the special
673     // cases we handle.
674     addLegalFPImmediate(APFloat(+0.0)); // xorpd
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677     // Use SSE for f32, x87 for f64.
678     // Set up the FP register classes.
679     addRegisterClass(MVT::f32, &X86::FR32RegClass);
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681
682     // Use ANDPS to simulate FABS.
683     setOperationAction(ISD::FABS , MVT::f32, Custom);
684
685     // Use XORP to simulate FNEG.
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
689
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693
694     // We don't support sin/cos/fmod
695     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
696     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
697     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698
699     // Special cases we handle for FP constants.
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701     addLegalFPImmediate(APFloat(+0.0)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705
706     if (!TM.Options.UnsafeFPMath) {
707       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
708       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
709       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710     }
711   } else if (!TM.Options.UseSoftFloat) {
712     // f32 and f64 in x87.
713     // Set up the FP register classes.
714     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716
717     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
718     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721
722     if (!TM.Options.UnsafeFPMath) {
723       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
724       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729     }
730     addLegalFPImmediate(APFloat(+0.0)); // FLD0
731     addLegalFPImmediate(APFloat(+1.0)); // FLD1
732     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738   }
739
740   // We don't support FMA.
741   setOperationAction(ISD::FMA, MVT::f64, Expand);
742   setOperationAction(ISD::FMA, MVT::f32, Expand);
743
744   // Long double always uses X87.
745   if (!TM.Options.UseSoftFloat) {
746     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
748     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749     {
750       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751       addLegalFPImmediate(TmpFlt);  // FLD0
752       TmpFlt.changeSign();
753       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
754
755       bool ignored;
756       APFloat TmpFlt2(+1.0);
757       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758                       &ignored);
759       addLegalFPImmediate(TmpFlt2);  // FLD1
760       TmpFlt2.changeSign();
761       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
762     }
763
764     if (!TM.Options.UnsafeFPMath) {
765       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
766       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
767       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768     }
769
770     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
772     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
774     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775     setOperationAction(ISD::FMA, MVT::f80, Expand);
776   }
777
778   // Always use a library call for pow.
779   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
782
783   setOperationAction(ISD::FLOG, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788
789   // First set operation action for all vector types to either promote
790   // (for widening) or expand (for scalarization). Then we will selectively
791   // turn on ones that can be effectively codegen'd.
792   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794     MVT VT = (MVT::SimpleValueType)i;
795     setOperationAction(ISD::ADD , VT, Expand);
796     setOperationAction(ISD::SUB , VT, Expand);
797     setOperationAction(ISD::FADD, VT, Expand);
798     setOperationAction(ISD::FNEG, VT, Expand);
799     setOperationAction(ISD::FSUB, VT, Expand);
800     setOperationAction(ISD::MUL , VT, Expand);
801     setOperationAction(ISD::FMUL, VT, Expand);
802     setOperationAction(ISD::SDIV, VT, Expand);
803     setOperationAction(ISD::UDIV, VT, Expand);
804     setOperationAction(ISD::FDIV, VT, Expand);
805     setOperationAction(ISD::SREM, VT, Expand);
806     setOperationAction(ISD::UREM, VT, Expand);
807     setOperationAction(ISD::LOAD, VT, Expand);
808     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::FABS, VT, Expand);
814     setOperationAction(ISD::FSIN, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FCOS, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FREM, VT, Expand);
819     setOperationAction(ISD::FMA,  VT, Expand);
820     setOperationAction(ISD::FPOWI, VT, Expand);
821     setOperationAction(ISD::FSQRT, VT, Expand);
822     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823     setOperationAction(ISD::FFLOOR, VT, Expand);
824     setOperationAction(ISD::FCEIL, VT, Expand);
825     setOperationAction(ISD::FTRUNC, VT, Expand);
826     setOperationAction(ISD::FRINT, VT, Expand);
827     setOperationAction(ISD::FNEARBYINT, VT, Expand);
828     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::SDIVREM, VT, Expand);
831     setOperationAction(ISD::UDIVREM, VT, Expand);
832     setOperationAction(ISD::FPOW, VT, Expand);
833     setOperationAction(ISD::CTPOP, VT, Expand);
834     setOperationAction(ISD::CTTZ, VT, Expand);
835     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836     setOperationAction(ISD::CTLZ, VT, Expand);
837     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::SHL, VT, Expand);
839     setOperationAction(ISD::SRA, VT, Expand);
840     setOperationAction(ISD::SRL, VT, Expand);
841     setOperationAction(ISD::ROTL, VT, Expand);
842     setOperationAction(ISD::ROTR, VT, Expand);
843     setOperationAction(ISD::BSWAP, VT, Expand);
844     setOperationAction(ISD::SETCC, VT, Expand);
845     setOperationAction(ISD::FLOG, VT, Expand);
846     setOperationAction(ISD::FLOG2, VT, Expand);
847     setOperationAction(ISD::FLOG10, VT, Expand);
848     setOperationAction(ISD::FEXP, VT, Expand);
849     setOperationAction(ISD::FEXP2, VT, Expand);
850     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855     setOperationAction(ISD::TRUNCATE, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859     setOperationAction(ISD::VSELECT, VT, Expand);
860     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862       setTruncStoreAction(VT,
863                           (MVT::SimpleValueType)InnerVT, Expand);
864     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
867   }
868
869   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870   // with -msoft-float, disable use of MMX as well.
871   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873     // No operations on x86mmx supported, everything uses intrinsics.
874   }
875
876   // MMX-sized vectors (other than x86mmx) are expected to be expanded
877   // into smaller operations.
878   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
879   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
880   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
882   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
883   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
884   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
885   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
886   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
887   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
888   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
889   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
890   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
891   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
892   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
893   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
894   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
898   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
899   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
900   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
903   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
907
908   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
910
911     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
912     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
916     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
917     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
918     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
919     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
920     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
921     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
923   }
924
925   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
927
928     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929     // registers cannot be used even for integer operations.
930     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
934
935     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
936     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
937     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
938     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
939     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
940     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
941     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
942     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
943     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
944     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
945     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
946     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
947     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
951     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
952     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
953
954     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
955     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
958
959     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
964
965     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967       MVT VT = (MVT::SimpleValueType)i;
968       // Do not attempt to custom lower non-power-of-2 vectors
969       if (!isPowerOf2_32(VT.getVectorNumElements()))
970         continue;
971       // Do not attempt to custom lower non-128-bit vectors
972       if (!VT.is128BitVector())
973         continue;
974       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
975       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
976       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
977     }
978
979     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
980     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
981     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
982     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
985
986     if (Subtarget->is64Bit()) {
987       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
989     }
990
991     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993       MVT VT = (MVT::SimpleValueType)i;
994
995       // Do not attempt to promote non-128-bit vectors
996       if (!VT.is128BitVector())
997         continue;
998
999       setOperationAction(ISD::AND,    VT, Promote);
1000       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1001       setOperationAction(ISD::OR,     VT, Promote);
1002       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1003       setOperationAction(ISD::XOR,    VT, Promote);
1004       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1005       setOperationAction(ISD::LOAD,   VT, Promote);
1006       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1007       setOperationAction(ISD::SELECT, VT, Promote);
1008       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1009     }
1010
1011     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1012
1013     // Custom lower v2i64 and v2f64 selects.
1014     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1015     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1016     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1017     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1018
1019     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1020     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1021
1022     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1023     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1024     // As there is no 64-bit GPR available, we need build a special custom
1025     // sequence to convert from v2i32 to v2f32.
1026     if (!Subtarget->is64Bit())
1027       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1028
1029     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1030     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1031
1032     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1033   }
1034
1035   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1037     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1038     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1041     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1046
1047     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1057
1058     // FIXME: Do we need to handle scalar-to-vector here?
1059     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1060
1061     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1062     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1063     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1066
1067     // i8 and i16 vectors are custom , because the source register and source
1068     // source memory operand types are not the same width.  f32 vectors are
1069     // custom since the immediate controlling the insert encodes additional
1070     // information.
1071     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1072     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1075
1076     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1080
1081     // FIXME: these should be Legal but thats only for the case where
1082     // the index is constant.  For now custom expand to deal with that.
1083     if (Subtarget->is64Bit()) {
1084       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1085       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1086     }
1087   }
1088
1089   if (Subtarget->hasSSE2()) {
1090     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1091     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1092
1093     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1098
1099     // In the customized shift lowering, the legal cases in AVX2 will be
1100     // recognized.
1101     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1102     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1103
1104     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1110     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1111   }
1112
1113   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1115     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1120
1121     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1122     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1123     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1124
1125     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1127     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1130     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1131     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1135     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1136     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1143     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1144     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1148     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1149     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1150
1151     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152     // even though v8i16 is a legal type.
1153     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1154     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1156
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1160
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1163
1164     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1165
1166     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1176
1177     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1181
1182     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1185
1186     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1190
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1203
1204     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1211     }
1212
1213     if (Subtarget->hasInt256()) {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1227       // Don't lower v32i8 because there is no 128-bit byte mul
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1232     } else {
1233       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1237
1238       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1246       // Don't lower v32i8 because there is no 128-bit byte mul
1247     }
1248
1249     // In the customized shift lowering, the legal cases in AVX2 will be
1250     // recognized.
1251     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1258
1259     // Custom lower several nodes for 256-bit types.
1260     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262       MVT VT = (MVT::SimpleValueType)i;
1263
1264       // Extract subvector is special because the value type
1265       // (result) is 128-bit but the source is 256-bit wide.
1266       if (VT.is128BitVector())
1267         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1268
1269       // Do not attempt to custom lower other non-256-bit vectors
1270       if (!VT.is256BitVector())
1271         continue;
1272
1273       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1274       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1275       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1276       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1278       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1279       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1280     }
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1314     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1315     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1316     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1317     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1318     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1324
1325     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1330     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1331
1332     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1337     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1338     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1340     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1341
1342     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1346     if (Subtarget->is64Bit()) {
1347       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1350       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1351     }
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1369     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1370     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1376
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1383
1384     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1385     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1386
1387     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1388
1389     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1390     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1392     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1393     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1394     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1395     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1396     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1397     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1398
1399     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1404
1405     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1406
1407     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1414     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1415
1416     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1420     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1421     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1422
1423     // Custom lower several nodes.
1424     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426       MVT VT = (MVT::SimpleValueType)i;
1427
1428       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429       // Extract subvector is special because the value type
1430       // (result) is 256/128-bit but the source is 512-bit wide.
1431       if (VT.is128BitVector() || VT.is256BitVector())
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1433
1434       if (VT.getVectorElementType() == MVT::i1)
1435         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1436
1437       // Do not attempt to custom lower other non-512-bit vectors
1438       if (!VT.is512BitVector())
1439         continue;
1440
1441       if ( EltSize >= 32) {
1442         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1443         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1444         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1445         setOperationAction(ISD::VSELECT,             VT, Legal);
1446         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1447         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1448         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1449       }
1450     }
1451     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452       MVT VT = (MVT::SimpleValueType)i;
1453
1454       // Do not attempt to promote non-256-bit vectors
1455       if (!VT.is512BitVector())
1456         continue;
1457
1458       setOperationAction(ISD::SELECT, VT, Promote);
1459       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1460     }
1461   }// has  AVX-512
1462
1463   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464   // of this type with custom code.
1465   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1468                        Custom);
1469   }
1470
1471   // We want to custom lower some of our intrinsics.
1472   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475
1476   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1477   // handle type legalization for these operations here.
1478   //
1479   // FIXME: We really should do custom legalization for addition and
1480   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1481   // than generic legalization for 64-bit multiplication-with-overflow, though.
1482   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1483     // Add/Sub/Mul with overflow operations are custom lowered.
1484     MVT VT = IntVTs[i];
1485     setOperationAction(ISD::SADDO, VT, Custom);
1486     setOperationAction(ISD::UADDO, VT, Custom);
1487     setOperationAction(ISD::SSUBO, VT, Custom);
1488     setOperationAction(ISD::USUBO, VT, Custom);
1489     setOperationAction(ISD::SMULO, VT, Custom);
1490     setOperationAction(ISD::UMULO, VT, Custom);
1491   }
1492
1493   // There are no 8-bit 3-address imul/mul instructions
1494   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1495   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1496
1497   if (!Subtarget->is64Bit()) {
1498     // These libcalls are not available in 32-bit.
1499     setLibcallName(RTLIB::SHL_I128, 0);
1500     setLibcallName(RTLIB::SRL_I128, 0);
1501     setLibcallName(RTLIB::SRA_I128, 0);
1502   }
1503
1504   // Combine sin / cos into one node or libcall if possible.
1505   if (Subtarget->hasSinCos()) {
1506     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1507     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1508     if (Subtarget->isTargetDarwin()) {
1509       // For MacOSX, we don't want to the normal expansion of a libcall to
1510       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1511       // traffic.
1512       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1513       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1514     }
1515   }
1516
1517   // We have target-specific dag combine patterns for the following nodes:
1518   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1519   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1520   setTargetDAGCombine(ISD::VSELECT);
1521   setTargetDAGCombine(ISD::SELECT);
1522   setTargetDAGCombine(ISD::SHL);
1523   setTargetDAGCombine(ISD::SRA);
1524   setTargetDAGCombine(ISD::SRL);
1525   setTargetDAGCombine(ISD::OR);
1526   setTargetDAGCombine(ISD::AND);
1527   setTargetDAGCombine(ISD::ADD);
1528   setTargetDAGCombine(ISD::FADD);
1529   setTargetDAGCombine(ISD::FSUB);
1530   setTargetDAGCombine(ISD::FMA);
1531   setTargetDAGCombine(ISD::SUB);
1532   setTargetDAGCombine(ISD::LOAD);
1533   setTargetDAGCombine(ISD::STORE);
1534   setTargetDAGCombine(ISD::ZERO_EXTEND);
1535   setTargetDAGCombine(ISD::ANY_EXTEND);
1536   setTargetDAGCombine(ISD::SIGN_EXTEND);
1537   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1538   setTargetDAGCombine(ISD::TRUNCATE);
1539   setTargetDAGCombine(ISD::SINT_TO_FP);
1540   setTargetDAGCombine(ISD::SETCC);
1541   if (Subtarget->is64Bit())
1542     setTargetDAGCombine(ISD::MUL);
1543   setTargetDAGCombine(ISD::XOR);
1544
1545   computeRegisterProperties();
1546
1547   // On Darwin, -Os means optimize for size without hurting performance,
1548   // do not reduce the limit.
1549   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1550   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1551   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1552   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1553   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1554   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555   setPrefLoopAlignment(4); // 2^4 bytes.
1556
1557   // Predictable cmov don't hurt on atom because it's in-order.
1558   PredictableSelectIsExpensive = !Subtarget->isAtom();
1559
1560   setPrefFunctionAlignment(4); // 2^4 bytes.
1561 }
1562
1563 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1564   if (!VT.isVector())
1565     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1566
1567   if (Subtarget->hasAVX512())
1568     switch(VT.getVectorNumElements()) {
1569     case  8: return MVT::v8i1;
1570     case 16: return MVT::v16i1;
1571   }
1572
1573   return VT.changeVectorElementTypeToInteger();
1574 }
1575
1576 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1577 /// the desired ByVal argument alignment.
1578 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1579   if (MaxAlign == 16)
1580     return;
1581   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1582     if (VTy->getBitWidth() == 128)
1583       MaxAlign = 16;
1584   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1585     unsigned EltAlign = 0;
1586     getMaxByValAlign(ATy->getElementType(), EltAlign);
1587     if (EltAlign > MaxAlign)
1588       MaxAlign = EltAlign;
1589   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1590     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1591       unsigned EltAlign = 0;
1592       getMaxByValAlign(STy->getElementType(i), EltAlign);
1593       if (EltAlign > MaxAlign)
1594         MaxAlign = EltAlign;
1595       if (MaxAlign == 16)
1596         break;
1597     }
1598   }
1599 }
1600
1601 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1602 /// function arguments in the caller parameter area. For X86, aggregates
1603 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1604 /// are at 4-byte boundaries.
1605 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1606   if (Subtarget->is64Bit()) {
1607     // Max of 8 and alignment of type.
1608     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1609     if (TyAlign > 8)
1610       return TyAlign;
1611     return 8;
1612   }
1613
1614   unsigned Align = 4;
1615   if (Subtarget->hasSSE1())
1616     getMaxByValAlign(Ty, Align);
1617   return Align;
1618 }
1619
1620 /// getOptimalMemOpType - Returns the target specific optimal type for load
1621 /// and store operations as a result of memset, memcpy, and memmove
1622 /// lowering. If DstAlign is zero that means it's safe to destination
1623 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1624 /// means there isn't a need to check it against alignment requirement,
1625 /// probably because the source does not need to be loaded. If 'IsMemset' is
1626 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1627 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1628 /// source is constant so it does not need to be loaded.
1629 /// It returns EVT::Other if the type should be determined using generic
1630 /// target-independent logic.
1631 EVT
1632 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1633                                        unsigned DstAlign, unsigned SrcAlign,
1634                                        bool IsMemset, bool ZeroMemset,
1635                                        bool MemcpyStrSrc,
1636                                        MachineFunction &MF) const {
1637   const Function *F = MF.getFunction();
1638   if ((!IsMemset || ZeroMemset) &&
1639       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1640                                        Attribute::NoImplicitFloat)) {
1641     if (Size >= 16 &&
1642         (Subtarget->isUnalignedMemAccessFast() ||
1643          ((DstAlign == 0 || DstAlign >= 16) &&
1644           (SrcAlign == 0 || SrcAlign >= 16)))) {
1645       if (Size >= 32) {
1646         if (Subtarget->hasInt256())
1647           return MVT::v8i32;
1648         if (Subtarget->hasFp256())
1649           return MVT::v8f32;
1650       }
1651       if (Subtarget->hasSSE2())
1652         return MVT::v4i32;
1653       if (Subtarget->hasSSE1())
1654         return MVT::v4f32;
1655     } else if (!MemcpyStrSrc && Size >= 8 &&
1656                !Subtarget->is64Bit() &&
1657                Subtarget->hasSSE2()) {
1658       // Do not use f64 to lower memcpy if source is string constant. It's
1659       // better to use i32 to avoid the loads.
1660       return MVT::f64;
1661     }
1662   }
1663   if (Subtarget->is64Bit() && Size >= 8)
1664     return MVT::i64;
1665   return MVT::i32;
1666 }
1667
1668 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1669   if (VT == MVT::f32)
1670     return X86ScalarSSEf32;
1671   else if (VT == MVT::f64)
1672     return X86ScalarSSEf64;
1673   return true;
1674 }
1675
1676 bool
1677 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1678                                                  unsigned,
1679                                                  bool *Fast) const {
1680   if (Fast)
1681     *Fast = Subtarget->isUnalignedMemAccessFast();
1682   return true;
1683 }
1684
1685 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1686 /// current function.  The returned value is a member of the
1687 /// MachineJumpTableInfo::JTEntryKind enum.
1688 unsigned X86TargetLowering::getJumpTableEncoding() const {
1689   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1690   // symbol.
1691   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1692       Subtarget->isPICStyleGOT())
1693     return MachineJumpTableInfo::EK_Custom32;
1694
1695   // Otherwise, use the normal jump table encoding heuristics.
1696   return TargetLowering::getJumpTableEncoding();
1697 }
1698
1699 const MCExpr *
1700 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1701                                              const MachineBasicBlock *MBB,
1702                                              unsigned uid,MCContext &Ctx) const{
1703   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1704          Subtarget->isPICStyleGOT());
1705   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1706   // entries.
1707   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1708                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1709 }
1710
1711 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1712 /// jumptable.
1713 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1714                                                     SelectionDAG &DAG) const {
1715   if (!Subtarget->is64Bit())
1716     // This doesn't have SDLoc associated with it, but is not really the
1717     // same as a Register.
1718     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1719   return Table;
1720 }
1721
1722 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1723 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1724 /// MCExpr.
1725 const MCExpr *X86TargetLowering::
1726 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1727                              MCContext &Ctx) const {
1728   // X86-64 uses RIP relative addressing based on the jump table label.
1729   if (Subtarget->isPICStyleRIPRel())
1730     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1731
1732   // Otherwise, the reference is relative to the PIC base.
1733   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1734 }
1735
1736 // FIXME: Why this routine is here? Move to RegInfo!
1737 std::pair<const TargetRegisterClass*, uint8_t>
1738 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1739   const TargetRegisterClass *RRC = 0;
1740   uint8_t Cost = 1;
1741   switch (VT.SimpleTy) {
1742   default:
1743     return TargetLowering::findRepresentativeClass(VT);
1744   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1745     RRC = Subtarget->is64Bit() ?
1746       (const TargetRegisterClass*)&X86::GR64RegClass :
1747       (const TargetRegisterClass*)&X86::GR32RegClass;
1748     break;
1749   case MVT::x86mmx:
1750     RRC = &X86::VR64RegClass;
1751     break;
1752   case MVT::f32: case MVT::f64:
1753   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1754   case MVT::v4f32: case MVT::v2f64:
1755   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1756   case MVT::v4f64:
1757     RRC = &X86::VR128RegClass;
1758     break;
1759   }
1760   return std::make_pair(RRC, Cost);
1761 }
1762
1763 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1764                                                unsigned &Offset) const {
1765   if (!Subtarget->isTargetLinux())
1766     return false;
1767
1768   if (Subtarget->is64Bit()) {
1769     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1770     Offset = 0x28;
1771     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1772       AddressSpace = 256;
1773     else
1774       AddressSpace = 257;
1775   } else {
1776     // %gs:0x14 on i386
1777     Offset = 0x14;
1778     AddressSpace = 256;
1779   }
1780   return true;
1781 }
1782
1783 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1784                                             unsigned DestAS) const {
1785   assert(SrcAS != DestAS && "Expected different address spaces!");
1786
1787   return SrcAS < 256 && DestAS < 256;
1788 }
1789
1790 //===----------------------------------------------------------------------===//
1791 //               Return Value Calling Convention Implementation
1792 //===----------------------------------------------------------------------===//
1793
1794 #include "X86GenCallingConv.inc"
1795
1796 bool
1797 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1798                                   MachineFunction &MF, bool isVarArg,
1799                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1800                         LLVMContext &Context) const {
1801   SmallVector<CCValAssign, 16> RVLocs;
1802   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1803                  RVLocs, Context);
1804   return CCInfo.CheckReturn(Outs, RetCC_X86);
1805 }
1806
1807 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1808   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1809   return ScratchRegs;
1810 }
1811
1812 SDValue
1813 X86TargetLowering::LowerReturn(SDValue Chain,
1814                                CallingConv::ID CallConv, bool isVarArg,
1815                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1816                                const SmallVectorImpl<SDValue> &OutVals,
1817                                SDLoc dl, SelectionDAG &DAG) const {
1818   MachineFunction &MF = DAG.getMachineFunction();
1819   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1820
1821   SmallVector<CCValAssign, 16> RVLocs;
1822   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1823                  RVLocs, *DAG.getContext());
1824   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1825
1826   SDValue Flag;
1827   SmallVector<SDValue, 6> RetOps;
1828   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1829   // Operand #1 = Bytes To Pop
1830   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1831                    MVT::i16));
1832
1833   // Copy the result values into the output registers.
1834   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1835     CCValAssign &VA = RVLocs[i];
1836     assert(VA.isRegLoc() && "Can only return in registers!");
1837     SDValue ValToCopy = OutVals[i];
1838     EVT ValVT = ValToCopy.getValueType();
1839
1840     // Promote values to the appropriate types
1841     if (VA.getLocInfo() == CCValAssign::SExt)
1842       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1843     else if (VA.getLocInfo() == CCValAssign::ZExt)
1844       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845     else if (VA.getLocInfo() == CCValAssign::AExt)
1846       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847     else if (VA.getLocInfo() == CCValAssign::BCvt)
1848       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1849
1850     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1851            "Unexpected FP-extend for return value.");  
1852
1853     // If this is x86-64, and we disabled SSE, we can't return FP values,
1854     // or SSE or MMX vectors.
1855     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1856          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1857           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1858       report_fatal_error("SSE register return with SSE disabled");
1859     }
1860     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1861     // llvm-gcc has never done it right and no one has noticed, so this
1862     // should be OK for now.
1863     if (ValVT == MVT::f64 &&
1864         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1865       report_fatal_error("SSE2 register return with SSE2 disabled");
1866
1867     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1868     // the RET instruction and handled by the FP Stackifier.
1869     if (VA.getLocReg() == X86::ST0 ||
1870         VA.getLocReg() == X86::ST1) {
1871       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1872       // change the value to the FP stack register class.
1873       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1874         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1875       RetOps.push_back(ValToCopy);
1876       // Don't emit a copytoreg.
1877       continue;
1878     }
1879
1880     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1881     // which is returned in RAX / RDX.
1882     if (Subtarget->is64Bit()) {
1883       if (ValVT == MVT::x86mmx) {
1884         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1885           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1886           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1887                                   ValToCopy);
1888           // If we don't have SSE2 available, convert to v4f32 so the generated
1889           // register is legal.
1890           if (!Subtarget->hasSSE2())
1891             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1892         }
1893       }
1894     }
1895
1896     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1897     Flag = Chain.getValue(1);
1898     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1899   }
1900
1901   // The x86-64 ABIs require that for returning structs by value we copy
1902   // the sret argument into %rax/%eax (depending on ABI) for the return.
1903   // Win32 requires us to put the sret argument to %eax as well.
1904   // We saved the argument into a virtual register in the entry block,
1905   // so now we copy the value out and into %rax/%eax.
1906   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1907       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1908     MachineFunction &MF = DAG.getMachineFunction();
1909     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1910     unsigned Reg = FuncInfo->getSRetReturnReg();
1911     assert(Reg &&
1912            "SRetReturnReg should have been set in LowerFormalArguments().");
1913     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1914
1915     unsigned RetValReg
1916         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1917           X86::RAX : X86::EAX;
1918     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1919     Flag = Chain.getValue(1);
1920
1921     // RAX/EAX now acts like a return value.
1922     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1923   }
1924
1925   RetOps[0] = Chain;  // Update chain.
1926
1927   // Add the flag if we have it.
1928   if (Flag.getNode())
1929     RetOps.push_back(Flag);
1930
1931   return DAG.getNode(X86ISD::RET_FLAG, dl,
1932                      MVT::Other, &RetOps[0], RetOps.size());
1933 }
1934
1935 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1936   if (N->getNumValues() != 1)
1937     return false;
1938   if (!N->hasNUsesOfValue(1, 0))
1939     return false;
1940
1941   SDValue TCChain = Chain;
1942   SDNode *Copy = *N->use_begin();
1943   if (Copy->getOpcode() == ISD::CopyToReg) {
1944     // If the copy has a glue operand, we conservatively assume it isn't safe to
1945     // perform a tail call.
1946     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1947       return false;
1948     TCChain = Copy->getOperand(0);
1949   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1950     return false;
1951
1952   bool HasRet = false;
1953   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1954        UI != UE; ++UI) {
1955     if (UI->getOpcode() != X86ISD::RET_FLAG)
1956       return false;
1957     HasRet = true;
1958   }
1959
1960   if (!HasRet)
1961     return false;
1962
1963   Chain = TCChain;
1964   return true;
1965 }
1966
1967 MVT
1968 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1969                                             ISD::NodeType ExtendKind) const {
1970   MVT ReturnMVT;
1971   // TODO: Is this also valid on 32-bit?
1972   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1973     ReturnMVT = MVT::i8;
1974   else
1975     ReturnMVT = MVT::i32;
1976
1977   MVT MinVT = getRegisterType(ReturnMVT);
1978   return VT.bitsLT(MinVT) ? MinVT : VT;
1979 }
1980
1981 /// LowerCallResult - Lower the result values of a call into the
1982 /// appropriate copies out of appropriate physical registers.
1983 ///
1984 SDValue
1985 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1986                                    CallingConv::ID CallConv, bool isVarArg,
1987                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1988                                    SDLoc dl, SelectionDAG &DAG,
1989                                    SmallVectorImpl<SDValue> &InVals) const {
1990
1991   // Assign locations to each value returned by this call.
1992   SmallVector<CCValAssign, 16> RVLocs;
1993   bool Is64Bit = Subtarget->is64Bit();
1994   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1995                  getTargetMachine(), RVLocs, *DAG.getContext());
1996   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1997
1998   // Copy all of the result registers out of their specified physreg.
1999   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2000     CCValAssign &VA = RVLocs[i];
2001     EVT CopyVT = VA.getValVT();
2002
2003     // If this is x86-64, and we disabled SSE, we can't return FP values
2004     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2005         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2006       report_fatal_error("SSE register return with SSE disabled");
2007     }
2008
2009     SDValue Val;
2010
2011     // If this is a call to a function that returns an fp value on the floating
2012     // point stack, we must guarantee the value is popped from the stack, so
2013     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2014     // if the return value is not used. We use the FpPOP_RETVAL instruction
2015     // instead.
2016     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2017       // If we prefer to use the value in xmm registers, copy it out as f80 and
2018       // use a truncate to move it from fp stack reg to xmm reg.
2019       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2020       SDValue Ops[] = { Chain, InFlag };
2021       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2022                                          MVT::Other, MVT::Glue, Ops), 1);
2023       Val = Chain.getValue(0);
2024
2025       // Round the f80 to the right size, which also moves it to the appropriate
2026       // xmm register.
2027       if (CopyVT != VA.getValVT())
2028         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2029                           // This truncation won't change the value.
2030                           DAG.getIntPtrConstant(1));
2031     } else {
2032       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2033                                  CopyVT, InFlag).getValue(1);
2034       Val = Chain.getValue(0);
2035     }
2036     InFlag = Chain.getValue(2);
2037     InVals.push_back(Val);
2038   }
2039
2040   return Chain;
2041 }
2042
2043 //===----------------------------------------------------------------------===//
2044 //                C & StdCall & Fast Calling Convention implementation
2045 //===----------------------------------------------------------------------===//
2046 //  StdCall calling convention seems to be standard for many Windows' API
2047 //  routines and around. It differs from C calling convention just a little:
2048 //  callee should clean up the stack, not caller. Symbols should be also
2049 //  decorated in some fancy way :) It doesn't support any vector arguments.
2050 //  For info on fast calling convention see Fast Calling Convention (tail call)
2051 //  implementation LowerX86_32FastCCCallTo.
2052
2053 /// CallIsStructReturn - Determines whether a call uses struct return
2054 /// semantics.
2055 enum StructReturnType {
2056   NotStructReturn,
2057   RegStructReturn,
2058   StackStructReturn
2059 };
2060 static StructReturnType
2061 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2062   if (Outs.empty())
2063     return NotStructReturn;
2064
2065   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2066   if (!Flags.isSRet())
2067     return NotStructReturn;
2068   if (Flags.isInReg())
2069     return RegStructReturn;
2070   return StackStructReturn;
2071 }
2072
2073 /// ArgsAreStructReturn - Determines whether a function uses struct
2074 /// return semantics.
2075 static StructReturnType
2076 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2077   if (Ins.empty())
2078     return NotStructReturn;
2079
2080   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2081   if (!Flags.isSRet())
2082     return NotStructReturn;
2083   if (Flags.isInReg())
2084     return RegStructReturn;
2085   return StackStructReturn;
2086 }
2087
2088 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2089 /// by "Src" to address "Dst" with size and alignment information specified by
2090 /// the specific parameter attribute. The copy will be passed as a byval
2091 /// function parameter.
2092 static SDValue
2093 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2094                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2095                           SDLoc dl) {
2096   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2097
2098   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2099                        /*isVolatile*/false, /*AlwaysInline=*/true,
2100                        MachinePointerInfo(), MachinePointerInfo());
2101 }
2102
2103 /// IsTailCallConvention - Return true if the calling convention is one that
2104 /// supports tail call optimization.
2105 static bool IsTailCallConvention(CallingConv::ID CC) {
2106   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2107           CC == CallingConv::HiPE);
2108 }
2109
2110 /// \brief Return true if the calling convention is a C calling convention.
2111 static bool IsCCallConvention(CallingConv::ID CC) {
2112   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2113           CC == CallingConv::X86_64_SysV);
2114 }
2115
2116 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2117   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2118     return false;
2119
2120   CallSite CS(CI);
2121   CallingConv::ID CalleeCC = CS.getCallingConv();
2122   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2123     return false;
2124
2125   return true;
2126 }
2127
2128 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2129 /// a tailcall target by changing its ABI.
2130 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2131                                    bool GuaranteedTailCallOpt) {
2132   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2133 }
2134
2135 SDValue
2136 X86TargetLowering::LowerMemArgument(SDValue Chain,
2137                                     CallingConv::ID CallConv,
2138                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2139                                     SDLoc dl, SelectionDAG &DAG,
2140                                     const CCValAssign &VA,
2141                                     MachineFrameInfo *MFI,
2142                                     unsigned i) const {
2143   // Create the nodes corresponding to a load from this parameter slot.
2144   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2145   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2146                               getTargetMachine().Options.GuaranteedTailCallOpt);
2147   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2148   EVT ValVT;
2149
2150   // If value is passed by pointer we have address passed instead of the value
2151   // itself.
2152   if (VA.getLocInfo() == CCValAssign::Indirect)
2153     ValVT = VA.getLocVT();
2154   else
2155     ValVT = VA.getValVT();
2156
2157   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2158   // changed with more analysis.
2159   // In case of tail call optimization mark all arguments mutable. Since they
2160   // could be overwritten by lowering of arguments in case of a tail call.
2161   if (Flags.isByVal()) {
2162     unsigned Bytes = Flags.getByValSize();
2163     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2164     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2165     return DAG.getFrameIndex(FI, getPointerTy());
2166   } else {
2167     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2168                                     VA.getLocMemOffset(), isImmutable);
2169     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2170     return DAG.getLoad(ValVT, dl, Chain, FIN,
2171                        MachinePointerInfo::getFixedStack(FI),
2172                        false, false, false, 0);
2173   }
2174 }
2175
2176 SDValue
2177 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2178                                         CallingConv::ID CallConv,
2179                                         bool isVarArg,
2180                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2181                                         SDLoc dl,
2182                                         SelectionDAG &DAG,
2183                                         SmallVectorImpl<SDValue> &InVals)
2184                                           const {
2185   MachineFunction &MF = DAG.getMachineFunction();
2186   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2187
2188   const Function* Fn = MF.getFunction();
2189   if (Fn->hasExternalLinkage() &&
2190       Subtarget->isTargetCygMing() &&
2191       Fn->getName() == "main")
2192     FuncInfo->setForceFramePointer(true);
2193
2194   MachineFrameInfo *MFI = MF.getFrameInfo();
2195   bool Is64Bit = Subtarget->is64Bit();
2196   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2197
2198   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2199          "Var args not supported with calling convention fastcc, ghc or hipe");
2200
2201   // Assign locations to all of the incoming arguments.
2202   SmallVector<CCValAssign, 16> ArgLocs;
2203   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2204                  ArgLocs, *DAG.getContext());
2205
2206   // Allocate shadow area for Win64
2207   if (IsWin64)
2208     CCInfo.AllocateStack(32, 8);
2209
2210   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2211
2212   unsigned LastVal = ~0U;
2213   SDValue ArgValue;
2214   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2215     CCValAssign &VA = ArgLocs[i];
2216     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2217     // places.
2218     assert(VA.getValNo() != LastVal &&
2219            "Don't support value assigned to multiple locs yet");
2220     (void)LastVal;
2221     LastVal = VA.getValNo();
2222
2223     if (VA.isRegLoc()) {
2224       EVT RegVT = VA.getLocVT();
2225       const TargetRegisterClass *RC;
2226       if (RegVT == MVT::i32)
2227         RC = &X86::GR32RegClass;
2228       else if (Is64Bit && RegVT == MVT::i64)
2229         RC = &X86::GR64RegClass;
2230       else if (RegVT == MVT::f32)
2231         RC = &X86::FR32RegClass;
2232       else if (RegVT == MVT::f64)
2233         RC = &X86::FR64RegClass;
2234       else if (RegVT.is512BitVector())
2235         RC = &X86::VR512RegClass;
2236       else if (RegVT.is256BitVector())
2237         RC = &X86::VR256RegClass;
2238       else if (RegVT.is128BitVector())
2239         RC = &X86::VR128RegClass;
2240       else if (RegVT == MVT::x86mmx)
2241         RC = &X86::VR64RegClass;
2242       else if (RegVT == MVT::i1)
2243         RC = &X86::VK1RegClass;
2244       else if (RegVT == MVT::v8i1)
2245         RC = &X86::VK8RegClass;
2246       else if (RegVT == MVT::v16i1)
2247         RC = &X86::VK16RegClass;
2248       else
2249         llvm_unreachable("Unknown argument type!");
2250
2251       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2252       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2253
2254       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2255       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2256       // right size.
2257       if (VA.getLocInfo() == CCValAssign::SExt)
2258         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2259                                DAG.getValueType(VA.getValVT()));
2260       else if (VA.getLocInfo() == CCValAssign::ZExt)
2261         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2262                                DAG.getValueType(VA.getValVT()));
2263       else if (VA.getLocInfo() == CCValAssign::BCvt)
2264         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2265
2266       if (VA.isExtInLoc()) {
2267         // Handle MMX values passed in XMM regs.
2268         if (RegVT.isVector())
2269           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2270         else
2271           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2272       }
2273     } else {
2274       assert(VA.isMemLoc());
2275       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2276     }
2277
2278     // If value is passed via pointer - do a load.
2279     if (VA.getLocInfo() == CCValAssign::Indirect)
2280       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2281                              MachinePointerInfo(), false, false, false, 0);
2282
2283     InVals.push_back(ArgValue);
2284   }
2285
2286   // The x86-64 ABIs require that for returning structs by value we copy
2287   // the sret argument into %rax/%eax (depending on ABI) for the return.
2288   // Win32 requires us to put the sret argument to %eax as well.
2289   // Save the argument into a virtual register so that we can access it
2290   // from the return points.
2291   if (MF.getFunction()->hasStructRetAttr() &&
2292       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2293     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2294     unsigned Reg = FuncInfo->getSRetReturnReg();
2295     if (!Reg) {
2296       MVT PtrTy = getPointerTy();
2297       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2298       FuncInfo->setSRetReturnReg(Reg);
2299     }
2300     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2301     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2302   }
2303
2304   unsigned StackSize = CCInfo.getNextStackOffset();
2305   // Align stack specially for tail calls.
2306   if (FuncIsMadeTailCallSafe(CallConv,
2307                              MF.getTarget().Options.GuaranteedTailCallOpt))
2308     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2309
2310   // If the function takes variable number of arguments, make a frame index for
2311   // the start of the first vararg value... for expansion of llvm.va_start.
2312   if (isVarArg) {
2313     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2314                     CallConv != CallingConv::X86_ThisCall)) {
2315       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2316     }
2317     if (Is64Bit) {
2318       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2319
2320       // FIXME: We should really autogenerate these arrays
2321       static const MCPhysReg GPR64ArgRegsWin64[] = {
2322         X86::RCX, X86::RDX, X86::R8,  X86::R9
2323       };
2324       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2325         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2326       };
2327       static const MCPhysReg XMMArgRegs64Bit[] = {
2328         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2329         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2330       };
2331       const MCPhysReg *GPR64ArgRegs;
2332       unsigned NumXMMRegs = 0;
2333
2334       if (IsWin64) {
2335         // The XMM registers which might contain var arg parameters are shadowed
2336         // in their paired GPR.  So we only need to save the GPR to their home
2337         // slots.
2338         TotalNumIntRegs = 4;
2339         GPR64ArgRegs = GPR64ArgRegsWin64;
2340       } else {
2341         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2342         GPR64ArgRegs = GPR64ArgRegs64Bit;
2343
2344         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2345                                                 TotalNumXMMRegs);
2346       }
2347       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2348                                                        TotalNumIntRegs);
2349
2350       bool NoImplicitFloatOps = Fn->getAttributes().
2351         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2352       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2353              "SSE register cannot be used when SSE is disabled!");
2354       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2355                NoImplicitFloatOps) &&
2356              "SSE register cannot be used when SSE is disabled!");
2357       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2358           !Subtarget->hasSSE1())
2359         // Kernel mode asks for SSE to be disabled, so don't push them
2360         // on the stack.
2361         TotalNumXMMRegs = 0;
2362
2363       if (IsWin64) {
2364         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2365         // Get to the caller-allocated home save location.  Add 8 to account
2366         // for the return address.
2367         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2368         FuncInfo->setRegSaveFrameIndex(
2369           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2370         // Fixup to set vararg frame on shadow area (4 x i64).
2371         if (NumIntRegs < 4)
2372           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2373       } else {
2374         // For X86-64, if there are vararg parameters that are passed via
2375         // registers, then we must store them to their spots on the stack so
2376         // they may be loaded by deferencing the result of va_next.
2377         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2378         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2379         FuncInfo->setRegSaveFrameIndex(
2380           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2381                                false));
2382       }
2383
2384       // Store the integer parameter registers.
2385       SmallVector<SDValue, 8> MemOps;
2386       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2387                                         getPointerTy());
2388       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2389       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2390         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2391                                   DAG.getIntPtrConstant(Offset));
2392         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2393                                      &X86::GR64RegClass);
2394         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2395         SDValue Store =
2396           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2397                        MachinePointerInfo::getFixedStack(
2398                          FuncInfo->getRegSaveFrameIndex(), Offset),
2399                        false, false, 0);
2400         MemOps.push_back(Store);
2401         Offset += 8;
2402       }
2403
2404       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2405         // Now store the XMM (fp + vector) parameter registers.
2406         SmallVector<SDValue, 11> SaveXMMOps;
2407         SaveXMMOps.push_back(Chain);
2408
2409         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2410         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2411         SaveXMMOps.push_back(ALVal);
2412
2413         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2414                                FuncInfo->getRegSaveFrameIndex()));
2415         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416                                FuncInfo->getVarArgsFPOffset()));
2417
2418         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2419           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2420                                        &X86::VR128RegClass);
2421           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2422           SaveXMMOps.push_back(Val);
2423         }
2424         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2425                                      MVT::Other,
2426                                      &SaveXMMOps[0], SaveXMMOps.size()));
2427       }
2428
2429       if (!MemOps.empty())
2430         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2431                             &MemOps[0], MemOps.size());
2432     }
2433   }
2434
2435   // Some CCs need callee pop.
2436   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2437                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2438     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2439   } else {
2440     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2441     // If this is an sret function, the return should pop the hidden pointer.
2442     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2443         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2444         argsAreStructReturn(Ins) == StackStructReturn)
2445       FuncInfo->setBytesToPopOnReturn(4);
2446   }
2447
2448   if (!Is64Bit) {
2449     // RegSaveFrameIndex is X86-64 only.
2450     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2451     if (CallConv == CallingConv::X86_FastCall ||
2452         CallConv == CallingConv::X86_ThisCall)
2453       // fastcc functions can't have varargs.
2454       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2455   }
2456
2457   FuncInfo->setArgumentStackSize(StackSize);
2458
2459   return Chain;
2460 }
2461
2462 SDValue
2463 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2464                                     SDValue StackPtr, SDValue Arg,
2465                                     SDLoc dl, SelectionDAG &DAG,
2466                                     const CCValAssign &VA,
2467                                     ISD::ArgFlagsTy Flags) const {
2468   unsigned LocMemOffset = VA.getLocMemOffset();
2469   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2470   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2471   if (Flags.isByVal())
2472     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2473
2474   return DAG.getStore(Chain, dl, Arg, PtrOff,
2475                       MachinePointerInfo::getStack(LocMemOffset),
2476                       false, false, 0);
2477 }
2478
2479 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2480 /// optimization is performed and it is required.
2481 SDValue
2482 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2483                                            SDValue &OutRetAddr, SDValue Chain,
2484                                            bool IsTailCall, bool Is64Bit,
2485                                            int FPDiff, SDLoc dl) const {
2486   // Adjust the Return address stack slot.
2487   EVT VT = getPointerTy();
2488   OutRetAddr = getReturnAddressFrameIndex(DAG);
2489
2490   // Load the "old" Return address.
2491   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2492                            false, false, false, 0);
2493   return SDValue(OutRetAddr.getNode(), 1);
2494 }
2495
2496 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2497 /// optimization is performed and it is required (FPDiff!=0).
2498 static SDValue
2499 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2500                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2501                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2502   // Store the return address to the appropriate stack slot.
2503   if (!FPDiff) return Chain;
2504   // Calculate the new stack slot for the return address.
2505   int NewReturnAddrFI =
2506     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2507                                          false);
2508   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2509   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2510                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2511                        false, false, 0);
2512   return Chain;
2513 }
2514
2515 SDValue
2516 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2517                              SmallVectorImpl<SDValue> &InVals) const {
2518   SelectionDAG &DAG                     = CLI.DAG;
2519   SDLoc &dl                             = CLI.DL;
2520   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2521   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2522   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2523   SDValue Chain                         = CLI.Chain;
2524   SDValue Callee                        = CLI.Callee;
2525   CallingConv::ID CallConv              = CLI.CallConv;
2526   bool &isTailCall                      = CLI.IsTailCall;
2527   bool isVarArg                         = CLI.IsVarArg;
2528
2529   MachineFunction &MF = DAG.getMachineFunction();
2530   bool Is64Bit        = Subtarget->is64Bit();
2531   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2532   StructReturnType SR = callIsStructReturn(Outs);
2533   bool IsSibcall      = false;
2534
2535   if (MF.getTarget().Options.DisableTailCalls)
2536     isTailCall = false;
2537
2538   if (isTailCall) {
2539     // Check if it's really possible to do a tail call.
2540     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2541                     isVarArg, SR != NotStructReturn,
2542                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2543                     Outs, OutVals, Ins, DAG);
2544
2545     // Sibcalls are automatically detected tailcalls which do not require
2546     // ABI changes.
2547     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2548       IsSibcall = true;
2549
2550     if (isTailCall)
2551       ++NumTailCalls;
2552   }
2553
2554   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2555          "Var args not supported with calling convention fastcc, ghc or hipe");
2556
2557   // Analyze operands of the call, assigning locations to each operand.
2558   SmallVector<CCValAssign, 16> ArgLocs;
2559   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2560                  ArgLocs, *DAG.getContext());
2561
2562   // Allocate shadow area for Win64
2563   if (IsWin64)
2564     CCInfo.AllocateStack(32, 8);
2565
2566   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2567
2568   // Get a count of how many bytes are to be pushed on the stack.
2569   unsigned NumBytes = CCInfo.getNextStackOffset();
2570   if (IsSibcall)
2571     // This is a sibcall. The memory operands are available in caller's
2572     // own caller's stack.
2573     NumBytes = 0;
2574   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2575            IsTailCallConvention(CallConv))
2576     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2577
2578   int FPDiff = 0;
2579   if (isTailCall && !IsSibcall) {
2580     // Lower arguments at fp - stackoffset + fpdiff.
2581     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2582     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2583
2584     FPDiff = NumBytesCallerPushed - NumBytes;
2585
2586     // Set the delta of movement of the returnaddr stackslot.
2587     // But only set if delta is greater than previous delta.
2588     if (FPDiff < X86Info->getTCReturnAddrDelta())
2589       X86Info->setTCReturnAddrDelta(FPDiff);
2590   }
2591
2592   unsigned NumBytesToPush = NumBytes;
2593   unsigned NumBytesToPop = NumBytes;
2594
2595   // If we have an inalloca argument, all stack space has already been allocated
2596   // for us and be right at the top of the stack.  We don't support multiple
2597   // arguments passed in memory when using inalloca.
2598   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2599     NumBytesToPush = 0;
2600     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2601            "an inalloca argument must be the only memory argument");
2602   }
2603
2604   if (!IsSibcall)
2605     Chain = DAG.getCALLSEQ_START(
2606         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2607
2608   SDValue RetAddrFrIdx;
2609   // Load return address for tail calls.
2610   if (isTailCall && FPDiff)
2611     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2612                                     Is64Bit, FPDiff, dl);
2613
2614   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2615   SmallVector<SDValue, 8> MemOpChains;
2616   SDValue StackPtr;
2617
2618   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2619   // of tail call optimization arguments are handle later.
2620   const X86RegisterInfo *RegInfo =
2621     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2622   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2623     // Skip inalloca arguments, they have already been written.
2624     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2625     if (Flags.isInAlloca())
2626       continue;
2627
2628     CCValAssign &VA = ArgLocs[i];
2629     EVT RegVT = VA.getLocVT();
2630     SDValue Arg = OutVals[i];
2631     bool isByVal = Flags.isByVal();
2632
2633     // Promote the value if needed.
2634     switch (VA.getLocInfo()) {
2635     default: llvm_unreachable("Unknown loc info!");
2636     case CCValAssign::Full: break;
2637     case CCValAssign::SExt:
2638       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2639       break;
2640     case CCValAssign::ZExt:
2641       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2642       break;
2643     case CCValAssign::AExt:
2644       if (RegVT.is128BitVector()) {
2645         // Special case: passing MMX values in XMM registers.
2646         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2647         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2648         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2649       } else
2650         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2651       break;
2652     case CCValAssign::BCvt:
2653       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2654       break;
2655     case CCValAssign::Indirect: {
2656       // Store the argument.
2657       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2658       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2659       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2660                            MachinePointerInfo::getFixedStack(FI),
2661                            false, false, 0);
2662       Arg = SpillSlot;
2663       break;
2664     }
2665     }
2666
2667     if (VA.isRegLoc()) {
2668       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2669       if (isVarArg && IsWin64) {
2670         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2671         // shadow reg if callee is a varargs function.
2672         unsigned ShadowReg = 0;
2673         switch (VA.getLocReg()) {
2674         case X86::XMM0: ShadowReg = X86::RCX; break;
2675         case X86::XMM1: ShadowReg = X86::RDX; break;
2676         case X86::XMM2: ShadowReg = X86::R8; break;
2677         case X86::XMM3: ShadowReg = X86::R9; break;
2678         }
2679         if (ShadowReg)
2680           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2681       }
2682     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2683       assert(VA.isMemLoc());
2684       if (StackPtr.getNode() == 0)
2685         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2686                                       getPointerTy());
2687       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2688                                              dl, DAG, VA, Flags));
2689     }
2690   }
2691
2692   if (!MemOpChains.empty())
2693     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2694                         &MemOpChains[0], MemOpChains.size());
2695
2696   if (Subtarget->isPICStyleGOT()) {
2697     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2698     // GOT pointer.
2699     if (!isTailCall) {
2700       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2701                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2702     } else {
2703       // If we are tail calling and generating PIC/GOT style code load the
2704       // address of the callee into ECX. The value in ecx is used as target of
2705       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2706       // for tail calls on PIC/GOT architectures. Normally we would just put the
2707       // address of GOT into ebx and then call target@PLT. But for tail calls
2708       // ebx would be restored (since ebx is callee saved) before jumping to the
2709       // target@PLT.
2710
2711       // Note: The actual moving to ECX is done further down.
2712       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2713       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2714           !G->getGlobal()->hasProtectedVisibility())
2715         Callee = LowerGlobalAddress(Callee, DAG);
2716       else if (isa<ExternalSymbolSDNode>(Callee))
2717         Callee = LowerExternalSymbol(Callee, DAG);
2718     }
2719   }
2720
2721   if (Is64Bit && isVarArg && !IsWin64) {
2722     // From AMD64 ABI document:
2723     // For calls that may call functions that use varargs or stdargs
2724     // (prototype-less calls or calls to functions containing ellipsis (...) in
2725     // the declaration) %al is used as hidden argument to specify the number
2726     // of SSE registers used. The contents of %al do not need to match exactly
2727     // the number of registers, but must be an ubound on the number of SSE
2728     // registers used and is in the range 0 - 8 inclusive.
2729
2730     // Count the number of XMM registers allocated.
2731     static const MCPhysReg XMMArgRegs[] = {
2732       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2733       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2734     };
2735     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2736     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2737            && "SSE registers cannot be used when SSE is disabled");
2738
2739     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2740                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2741   }
2742
2743   // For tail calls lower the arguments to the 'real' stack slot.
2744   if (isTailCall) {
2745     // Force all the incoming stack arguments to be loaded from the stack
2746     // before any new outgoing arguments are stored to the stack, because the
2747     // outgoing stack slots may alias the incoming argument stack slots, and
2748     // the alias isn't otherwise explicit. This is slightly more conservative
2749     // than necessary, because it means that each store effectively depends
2750     // on every argument instead of just those arguments it would clobber.
2751     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2752
2753     SmallVector<SDValue, 8> MemOpChains2;
2754     SDValue FIN;
2755     int FI = 0;
2756     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2757       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2758         CCValAssign &VA = ArgLocs[i];
2759         if (VA.isRegLoc())
2760           continue;
2761         assert(VA.isMemLoc());
2762         SDValue Arg = OutVals[i];
2763         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2764         // Create frame index.
2765         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2766         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2767         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2768         FIN = DAG.getFrameIndex(FI, getPointerTy());
2769
2770         if (Flags.isByVal()) {
2771           // Copy relative to framepointer.
2772           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2773           if (StackPtr.getNode() == 0)
2774             StackPtr = DAG.getCopyFromReg(Chain, dl,
2775                                           RegInfo->getStackRegister(),
2776                                           getPointerTy());
2777           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2778
2779           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2780                                                            ArgChain,
2781                                                            Flags, DAG, dl));
2782         } else {
2783           // Store relative to framepointer.
2784           MemOpChains2.push_back(
2785             DAG.getStore(ArgChain, dl, Arg, FIN,
2786                          MachinePointerInfo::getFixedStack(FI),
2787                          false, false, 0));
2788         }
2789       }
2790     }
2791
2792     if (!MemOpChains2.empty())
2793       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2794                           &MemOpChains2[0], MemOpChains2.size());
2795
2796     // Store the return address to the appropriate stack slot.
2797     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2798                                      getPointerTy(), RegInfo->getSlotSize(),
2799                                      FPDiff, dl);
2800   }
2801
2802   // Build a sequence of copy-to-reg nodes chained together with token chain
2803   // and flag operands which copy the outgoing args into registers.
2804   SDValue InFlag;
2805   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2806     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2807                              RegsToPass[i].second, InFlag);
2808     InFlag = Chain.getValue(1);
2809   }
2810
2811   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2812     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2813     // In the 64-bit large code model, we have to make all calls
2814     // through a register, since the call instruction's 32-bit
2815     // pc-relative offset may not be large enough to hold the whole
2816     // address.
2817   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2818     // If the callee is a GlobalAddress node (quite common, every direct call
2819     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2820     // it.
2821
2822     // We should use extra load for direct calls to dllimported functions in
2823     // non-JIT mode.
2824     const GlobalValue *GV = G->getGlobal();
2825     if (!GV->hasDLLImportStorageClass()) {
2826       unsigned char OpFlags = 0;
2827       bool ExtraLoad = false;
2828       unsigned WrapperKind = ISD::DELETED_NODE;
2829
2830       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2831       // external symbols most go through the PLT in PIC mode.  If the symbol
2832       // has hidden or protected visibility, or if it is static or local, then
2833       // we don't need to use the PLT - we can directly call it.
2834       if (Subtarget->isTargetELF() &&
2835           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2836           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2837         OpFlags = X86II::MO_PLT;
2838       } else if (Subtarget->isPICStyleStubAny() &&
2839                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2840                  (!Subtarget->getTargetTriple().isMacOSX() ||
2841                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2842         // PC-relative references to external symbols should go through $stub,
2843         // unless we're building with the leopard linker or later, which
2844         // automatically synthesizes these stubs.
2845         OpFlags = X86II::MO_DARWIN_STUB;
2846       } else if (Subtarget->isPICStyleRIPRel() &&
2847                  isa<Function>(GV) &&
2848                  cast<Function>(GV)->getAttributes().
2849                    hasAttribute(AttributeSet::FunctionIndex,
2850                                 Attribute::NonLazyBind)) {
2851         // If the function is marked as non-lazy, generate an indirect call
2852         // which loads from the GOT directly. This avoids runtime overhead
2853         // at the cost of eager binding (and one extra byte of encoding).
2854         OpFlags = X86II::MO_GOTPCREL;
2855         WrapperKind = X86ISD::WrapperRIP;
2856         ExtraLoad = true;
2857       }
2858
2859       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2860                                           G->getOffset(), OpFlags);
2861
2862       // Add a wrapper if needed.
2863       if (WrapperKind != ISD::DELETED_NODE)
2864         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2865       // Add extra indirection if needed.
2866       if (ExtraLoad)
2867         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2868                              MachinePointerInfo::getGOT(),
2869                              false, false, false, 0);
2870     }
2871   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2872     unsigned char OpFlags = 0;
2873
2874     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2875     // external symbols should go through the PLT.
2876     if (Subtarget->isTargetELF() &&
2877         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2878       OpFlags = X86II::MO_PLT;
2879     } else if (Subtarget->isPICStyleStubAny() &&
2880                (!Subtarget->getTargetTriple().isMacOSX() ||
2881                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2882       // PC-relative references to external symbols should go through $stub,
2883       // unless we're building with the leopard linker or later, which
2884       // automatically synthesizes these stubs.
2885       OpFlags = X86II::MO_DARWIN_STUB;
2886     }
2887
2888     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2889                                          OpFlags);
2890   }
2891
2892   // Returns a chain & a flag for retval copy to use.
2893   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2894   SmallVector<SDValue, 8> Ops;
2895
2896   if (!IsSibcall && isTailCall) {
2897     Chain = DAG.getCALLSEQ_END(Chain,
2898                                DAG.getIntPtrConstant(NumBytesToPop, true),
2899                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2900     InFlag = Chain.getValue(1);
2901   }
2902
2903   Ops.push_back(Chain);
2904   Ops.push_back(Callee);
2905
2906   if (isTailCall)
2907     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2908
2909   // Add argument registers to the end of the list so that they are known live
2910   // into the call.
2911   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2912     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2913                                   RegsToPass[i].second.getValueType()));
2914
2915   // Add a register mask operand representing the call-preserved registers.
2916   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2917   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2918   assert(Mask && "Missing call preserved mask for calling convention");
2919   Ops.push_back(DAG.getRegisterMask(Mask));
2920
2921   if (InFlag.getNode())
2922     Ops.push_back(InFlag);
2923
2924   if (isTailCall) {
2925     // We used to do:
2926     //// If this is the first return lowered for this function, add the regs
2927     //// to the liveout set for the function.
2928     // This isn't right, although it's probably harmless on x86; liveouts
2929     // should be computed from returns not tail calls.  Consider a void
2930     // function making a tail call to a function returning int.
2931     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2932   }
2933
2934   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2935   InFlag = Chain.getValue(1);
2936
2937   // Create the CALLSEQ_END node.
2938   unsigned NumBytesForCalleeToPop;
2939   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940                        getTargetMachine().Options.GuaranteedTailCallOpt))
2941     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2942   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2943            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2944            SR == StackStructReturn)
2945     // If this is a call to a struct-return function, the callee
2946     // pops the hidden struct pointer, so we have to push it back.
2947     // This is common for Darwin/X86, Linux & Mingw32 targets.
2948     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2949     NumBytesForCalleeToPop = 4;
2950   else
2951     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2952
2953   // Returns a flag for retval copy to use.
2954   if (!IsSibcall) {
2955     Chain = DAG.getCALLSEQ_END(Chain,
2956                                DAG.getIntPtrConstant(NumBytesToPop, true),
2957                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2958                                                      true),
2959                                InFlag, dl);
2960     InFlag = Chain.getValue(1);
2961   }
2962
2963   // Handle result values, copying them out of physregs into vregs that we
2964   // return.
2965   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2966                          Ins, dl, DAG, InVals);
2967 }
2968
2969 //===----------------------------------------------------------------------===//
2970 //                Fast Calling Convention (tail call) implementation
2971 //===----------------------------------------------------------------------===//
2972
2973 //  Like std call, callee cleans arguments, convention except that ECX is
2974 //  reserved for storing the tail called function address. Only 2 registers are
2975 //  free for argument passing (inreg). Tail call optimization is performed
2976 //  provided:
2977 //                * tailcallopt is enabled
2978 //                * caller/callee are fastcc
2979 //  On X86_64 architecture with GOT-style position independent code only local
2980 //  (within module) calls are supported at the moment.
2981 //  To keep the stack aligned according to platform abi the function
2982 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2983 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2984 //  If a tail called function callee has more arguments than the caller the
2985 //  caller needs to make sure that there is room to move the RETADDR to. This is
2986 //  achieved by reserving an area the size of the argument delta right after the
2987 //  original REtADDR, but before the saved framepointer or the spilled registers
2988 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2989 //  stack layout:
2990 //    arg1
2991 //    arg2
2992 //    RETADDR
2993 //    [ new RETADDR
2994 //      move area ]
2995 //    (possible EBP)
2996 //    ESI
2997 //    EDI
2998 //    local1 ..
2999
3000 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3001 /// for a 16 byte align requirement.
3002 unsigned
3003 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3004                                                SelectionDAG& DAG) const {
3005   MachineFunction &MF = DAG.getMachineFunction();
3006   const TargetMachine &TM = MF.getTarget();
3007   const X86RegisterInfo *RegInfo =
3008     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3009   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3010   unsigned StackAlignment = TFI.getStackAlignment();
3011   uint64_t AlignMask = StackAlignment - 1;
3012   int64_t Offset = StackSize;
3013   unsigned SlotSize = RegInfo->getSlotSize();
3014   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3015     // Number smaller than 12 so just add the difference.
3016     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3017   } else {
3018     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3019     Offset = ((~AlignMask) & Offset) + StackAlignment +
3020       (StackAlignment-SlotSize);
3021   }
3022   return Offset;
3023 }
3024
3025 /// MatchingStackOffset - Return true if the given stack call argument is
3026 /// already available in the same position (relatively) of the caller's
3027 /// incoming argument stack.
3028 static
3029 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3030                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3031                          const X86InstrInfo *TII) {
3032   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3033   int FI = INT_MAX;
3034   if (Arg.getOpcode() == ISD::CopyFromReg) {
3035     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3036     if (!TargetRegisterInfo::isVirtualRegister(VR))
3037       return false;
3038     MachineInstr *Def = MRI->getVRegDef(VR);
3039     if (!Def)
3040       return false;
3041     if (!Flags.isByVal()) {
3042       if (!TII->isLoadFromStackSlot(Def, FI))
3043         return false;
3044     } else {
3045       unsigned Opcode = Def->getOpcode();
3046       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3047           Def->getOperand(1).isFI()) {
3048         FI = Def->getOperand(1).getIndex();
3049         Bytes = Flags.getByValSize();
3050       } else
3051         return false;
3052     }
3053   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3054     if (Flags.isByVal())
3055       // ByVal argument is passed in as a pointer but it's now being
3056       // dereferenced. e.g.
3057       // define @foo(%struct.X* %A) {
3058       //   tail call @bar(%struct.X* byval %A)
3059       // }
3060       return false;
3061     SDValue Ptr = Ld->getBasePtr();
3062     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3063     if (!FINode)
3064       return false;
3065     FI = FINode->getIndex();
3066   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3067     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3068     FI = FINode->getIndex();
3069     Bytes = Flags.getByValSize();
3070   } else
3071     return false;
3072
3073   assert(FI != INT_MAX);
3074   if (!MFI->isFixedObjectIndex(FI))
3075     return false;
3076   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3077 }
3078
3079 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3080 /// for tail call optimization. Targets which want to do tail call
3081 /// optimization should implement this function.
3082 bool
3083 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3084                                                      CallingConv::ID CalleeCC,
3085                                                      bool isVarArg,
3086                                                      bool isCalleeStructRet,
3087                                                      bool isCallerStructRet,
3088                                                      Type *RetTy,
3089                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3090                                     const SmallVectorImpl<SDValue> &OutVals,
3091                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3092                                                      SelectionDAG &DAG) const {
3093   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3094     return false;
3095
3096   // If -tailcallopt is specified, make fastcc functions tail-callable.
3097   const MachineFunction &MF = DAG.getMachineFunction();
3098   const Function *CallerF = MF.getFunction();
3099
3100   // If the function return type is x86_fp80 and the callee return type is not,
3101   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3102   // perform a tailcall optimization here.
3103   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3104     return false;
3105
3106   CallingConv::ID CallerCC = CallerF->getCallingConv();
3107   bool CCMatch = CallerCC == CalleeCC;
3108   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3109   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3110
3111   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3112     if (IsTailCallConvention(CalleeCC) && CCMatch)
3113       return true;
3114     return false;
3115   }
3116
3117   // Look for obvious safe cases to perform tail call optimization that do not
3118   // require ABI changes. This is what gcc calls sibcall.
3119
3120   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3121   // emit a special epilogue.
3122   const X86RegisterInfo *RegInfo =
3123     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3124   if (RegInfo->needsStackRealignment(MF))
3125     return false;
3126
3127   // Also avoid sibcall optimization if either caller or callee uses struct
3128   // return semantics.
3129   if (isCalleeStructRet || isCallerStructRet)
3130     return false;
3131
3132   // An stdcall/thiscall caller is expected to clean up its arguments; the
3133   // callee isn't going to do that.
3134   // FIXME: this is more restrictive than needed. We could produce a tailcall
3135   // when the stack adjustment matches. For example, with a thiscall that takes
3136   // only one argument.
3137   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3138                    CallerCC == CallingConv::X86_ThisCall))
3139     return false;
3140
3141   // Do not sibcall optimize vararg calls unless all arguments are passed via
3142   // registers.
3143   if (isVarArg && !Outs.empty()) {
3144
3145     // Optimizing for varargs on Win64 is unlikely to be safe without
3146     // additional testing.
3147     if (IsCalleeWin64 || IsCallerWin64)
3148       return false;
3149
3150     SmallVector<CCValAssign, 16> ArgLocs;
3151     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3152                    getTargetMachine(), ArgLocs, *DAG.getContext());
3153
3154     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3155     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3156       if (!ArgLocs[i].isRegLoc())
3157         return false;
3158   }
3159
3160   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3161   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3162   // this into a sibcall.
3163   bool Unused = false;
3164   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3165     if (!Ins[i].Used) {
3166       Unused = true;
3167       break;
3168     }
3169   }
3170   if (Unused) {
3171     SmallVector<CCValAssign, 16> RVLocs;
3172     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3173                    getTargetMachine(), RVLocs, *DAG.getContext());
3174     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3175     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3176       CCValAssign &VA = RVLocs[i];
3177       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3178         return false;
3179     }
3180   }
3181
3182   // If the calling conventions do not match, then we'd better make sure the
3183   // results are returned in the same way as what the caller expects.
3184   if (!CCMatch) {
3185     SmallVector<CCValAssign, 16> RVLocs1;
3186     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3187                     getTargetMachine(), RVLocs1, *DAG.getContext());
3188     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3189
3190     SmallVector<CCValAssign, 16> RVLocs2;
3191     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3192                     getTargetMachine(), RVLocs2, *DAG.getContext());
3193     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3194
3195     if (RVLocs1.size() != RVLocs2.size())
3196       return false;
3197     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3198       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3199         return false;
3200       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3201         return false;
3202       if (RVLocs1[i].isRegLoc()) {
3203         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3204           return false;
3205       } else {
3206         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3207           return false;
3208       }
3209     }
3210   }
3211
3212   // If the callee takes no arguments then go on to check the results of the
3213   // call.
3214   if (!Outs.empty()) {
3215     // Check if stack adjustment is needed. For now, do not do this if any
3216     // argument is passed on the stack.
3217     SmallVector<CCValAssign, 16> ArgLocs;
3218     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3219                    getTargetMachine(), ArgLocs, *DAG.getContext());
3220
3221     // Allocate shadow area for Win64
3222     if (IsCalleeWin64)
3223       CCInfo.AllocateStack(32, 8);
3224
3225     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3226     if (CCInfo.getNextStackOffset()) {
3227       MachineFunction &MF = DAG.getMachineFunction();
3228       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3229         return false;
3230
3231       // Check if the arguments are already laid out in the right way as
3232       // the caller's fixed stack objects.
3233       MachineFrameInfo *MFI = MF.getFrameInfo();
3234       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3235       const X86InstrInfo *TII =
3236         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3237       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3238         CCValAssign &VA = ArgLocs[i];
3239         SDValue Arg = OutVals[i];
3240         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3241         if (VA.getLocInfo() == CCValAssign::Indirect)
3242           return false;
3243         if (!VA.isRegLoc()) {
3244           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3245                                    MFI, MRI, TII))
3246             return false;
3247         }
3248       }
3249     }
3250
3251     // If the tailcall address may be in a register, then make sure it's
3252     // possible to register allocate for it. In 32-bit, the call address can
3253     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3254     // callee-saved registers are restored. These happen to be the same
3255     // registers used to pass 'inreg' arguments so watch out for those.
3256     if (!Subtarget->is64Bit() &&
3257         ((!isa<GlobalAddressSDNode>(Callee) &&
3258           !isa<ExternalSymbolSDNode>(Callee)) ||
3259          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3260       unsigned NumInRegs = 0;
3261       // In PIC we need an extra register to formulate the address computation
3262       // for the callee.
3263       unsigned MaxInRegs =
3264           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3265
3266       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267         CCValAssign &VA = ArgLocs[i];
3268         if (!VA.isRegLoc())
3269           continue;
3270         unsigned Reg = VA.getLocReg();
3271         switch (Reg) {
3272         default: break;
3273         case X86::EAX: case X86::EDX: case X86::ECX:
3274           if (++NumInRegs == MaxInRegs)
3275             return false;
3276           break;
3277         }
3278       }
3279     }
3280   }
3281
3282   return true;
3283 }
3284
3285 FastISel *
3286 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3287                                   const TargetLibraryInfo *libInfo) const {
3288   return X86::createFastISel(funcInfo, libInfo);
3289 }
3290
3291 //===----------------------------------------------------------------------===//
3292 //                           Other Lowering Hooks
3293 //===----------------------------------------------------------------------===//
3294
3295 static bool MayFoldLoad(SDValue Op) {
3296   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3297 }
3298
3299 static bool MayFoldIntoStore(SDValue Op) {
3300   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3301 }
3302
3303 static bool isTargetShuffle(unsigned Opcode) {
3304   switch(Opcode) {
3305   default: return false;
3306   case X86ISD::PSHUFD:
3307   case X86ISD::PSHUFHW:
3308   case X86ISD::PSHUFLW:
3309   case X86ISD::SHUFP:
3310   case X86ISD::PALIGNR:
3311   case X86ISD::MOVLHPS:
3312   case X86ISD::MOVLHPD:
3313   case X86ISD::MOVHLPS:
3314   case X86ISD::MOVLPS:
3315   case X86ISD::MOVLPD:
3316   case X86ISD::MOVSHDUP:
3317   case X86ISD::MOVSLDUP:
3318   case X86ISD::MOVDDUP:
3319   case X86ISD::MOVSS:
3320   case X86ISD::MOVSD:
3321   case X86ISD::UNPCKL:
3322   case X86ISD::UNPCKH:
3323   case X86ISD::VPERMILP:
3324   case X86ISD::VPERM2X128:
3325   case X86ISD::VPERMI:
3326     return true;
3327   }
3328 }
3329
3330 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3331                                     SDValue V1, SelectionDAG &DAG) {
3332   switch(Opc) {
3333   default: llvm_unreachable("Unknown x86 shuffle node");
3334   case X86ISD::MOVSHDUP:
3335   case X86ISD::MOVSLDUP:
3336   case X86ISD::MOVDDUP:
3337     return DAG.getNode(Opc, dl, VT, V1);
3338   }
3339 }
3340
3341 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3342                                     SDValue V1, unsigned TargetMask,
3343                                     SelectionDAG &DAG) {
3344   switch(Opc) {
3345   default: llvm_unreachable("Unknown x86 shuffle node");
3346   case X86ISD::PSHUFD:
3347   case X86ISD::PSHUFHW:
3348   case X86ISD::PSHUFLW:
3349   case X86ISD::VPERMILP:
3350   case X86ISD::VPERMI:
3351     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3352   }
3353 }
3354
3355 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3356                                     SDValue V1, SDValue V2, unsigned TargetMask,
3357                                     SelectionDAG &DAG) {
3358   switch(Opc) {
3359   default: llvm_unreachable("Unknown x86 shuffle node");
3360   case X86ISD::PALIGNR:
3361   case X86ISD::SHUFP:
3362   case X86ISD::VPERM2X128:
3363     return DAG.getNode(Opc, dl, VT, V1, V2,
3364                        DAG.getConstant(TargetMask, MVT::i8));
3365   }
3366 }
3367
3368 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3369                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3370   switch(Opc) {
3371   default: llvm_unreachable("Unknown x86 shuffle node");
3372   case X86ISD::MOVLHPS:
3373   case X86ISD::MOVLHPD:
3374   case X86ISD::MOVHLPS:
3375   case X86ISD::MOVLPS:
3376   case X86ISD::MOVLPD:
3377   case X86ISD::MOVSS:
3378   case X86ISD::MOVSD:
3379   case X86ISD::UNPCKL:
3380   case X86ISD::UNPCKH:
3381     return DAG.getNode(Opc, dl, VT, V1, V2);
3382   }
3383 }
3384
3385 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3386   MachineFunction &MF = DAG.getMachineFunction();
3387   const X86RegisterInfo *RegInfo =
3388     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3389   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3390   int ReturnAddrIndex = FuncInfo->getRAIndex();
3391
3392   if (ReturnAddrIndex == 0) {
3393     // Set up a frame object for the return address.
3394     unsigned SlotSize = RegInfo->getSlotSize();
3395     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3396                                                            -(int64_t)SlotSize,
3397                                                            false);
3398     FuncInfo->setRAIndex(ReturnAddrIndex);
3399   }
3400
3401   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3402 }
3403
3404 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3405                                        bool hasSymbolicDisplacement) {
3406   // Offset should fit into 32 bit immediate field.
3407   if (!isInt<32>(Offset))
3408     return false;
3409
3410   // If we don't have a symbolic displacement - we don't have any extra
3411   // restrictions.
3412   if (!hasSymbolicDisplacement)
3413     return true;
3414
3415   // FIXME: Some tweaks might be needed for medium code model.
3416   if (M != CodeModel::Small && M != CodeModel::Kernel)
3417     return false;
3418
3419   // For small code model we assume that latest object is 16MB before end of 31
3420   // bits boundary. We may also accept pretty large negative constants knowing
3421   // that all objects are in the positive half of address space.
3422   if (M == CodeModel::Small && Offset < 16*1024*1024)
3423     return true;
3424
3425   // For kernel code model we know that all object resist in the negative half
3426   // of 32bits address space. We may not accept negative offsets, since they may
3427   // be just off and we may accept pretty large positive ones.
3428   if (M == CodeModel::Kernel && Offset > 0)
3429     return true;
3430
3431   return false;
3432 }
3433
3434 /// isCalleePop - Determines whether the callee is required to pop its
3435 /// own arguments. Callee pop is necessary to support tail calls.
3436 bool X86::isCalleePop(CallingConv::ID CallingConv,
3437                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3438   if (IsVarArg)
3439     return false;
3440
3441   switch (CallingConv) {
3442   default:
3443     return false;
3444   case CallingConv::X86_StdCall:
3445     return !is64Bit;
3446   case CallingConv::X86_FastCall:
3447     return !is64Bit;
3448   case CallingConv::X86_ThisCall:
3449     return !is64Bit;
3450   case CallingConv::Fast:
3451     return TailCallOpt;
3452   case CallingConv::GHC:
3453     return TailCallOpt;
3454   case CallingConv::HiPE:
3455     return TailCallOpt;
3456   }
3457 }
3458
3459 /// \brief Return true if the condition is an unsigned comparison operation.
3460 static bool isX86CCUnsigned(unsigned X86CC) {
3461   switch (X86CC) {
3462   default: llvm_unreachable("Invalid integer condition!");
3463   case X86::COND_E:     return true;
3464   case X86::COND_G:     return false;
3465   case X86::COND_GE:    return false;
3466   case X86::COND_L:     return false;
3467   case X86::COND_LE:    return false;
3468   case X86::COND_NE:    return true;
3469   case X86::COND_B:     return true;
3470   case X86::COND_A:     return true;
3471   case X86::COND_BE:    return true;
3472   case X86::COND_AE:    return true;
3473   }
3474   llvm_unreachable("covered switch fell through?!");
3475 }
3476
3477 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3478 /// specific condition code, returning the condition code and the LHS/RHS of the
3479 /// comparison to make.
3480 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3481                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3482   if (!isFP) {
3483     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3484       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3485         // X > -1   -> X == 0, jump !sign.
3486         RHS = DAG.getConstant(0, RHS.getValueType());
3487         return X86::COND_NS;
3488       }
3489       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3490         // X < 0   -> X == 0, jump on sign.
3491         return X86::COND_S;
3492       }
3493       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3494         // X < 1   -> X <= 0
3495         RHS = DAG.getConstant(0, RHS.getValueType());
3496         return X86::COND_LE;
3497       }
3498     }
3499
3500     switch (SetCCOpcode) {
3501     default: llvm_unreachable("Invalid integer condition!");
3502     case ISD::SETEQ:  return X86::COND_E;
3503     case ISD::SETGT:  return X86::COND_G;
3504     case ISD::SETGE:  return X86::COND_GE;
3505     case ISD::SETLT:  return X86::COND_L;
3506     case ISD::SETLE:  return X86::COND_LE;
3507     case ISD::SETNE:  return X86::COND_NE;
3508     case ISD::SETULT: return X86::COND_B;
3509     case ISD::SETUGT: return X86::COND_A;
3510     case ISD::SETULE: return X86::COND_BE;
3511     case ISD::SETUGE: return X86::COND_AE;
3512     }
3513   }
3514
3515   // First determine if it is required or is profitable to flip the operands.
3516
3517   // If LHS is a foldable load, but RHS is not, flip the condition.
3518   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3519       !ISD::isNON_EXTLoad(RHS.getNode())) {
3520     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3521     std::swap(LHS, RHS);
3522   }
3523
3524   switch (SetCCOpcode) {
3525   default: break;
3526   case ISD::SETOLT:
3527   case ISD::SETOLE:
3528   case ISD::SETUGT:
3529   case ISD::SETUGE:
3530     std::swap(LHS, RHS);
3531     break;
3532   }
3533
3534   // On a floating point condition, the flags are set as follows:
3535   // ZF  PF  CF   op
3536   //  0 | 0 | 0 | X > Y
3537   //  0 | 0 | 1 | X < Y
3538   //  1 | 0 | 0 | X == Y
3539   //  1 | 1 | 1 | unordered
3540   switch (SetCCOpcode) {
3541   default: llvm_unreachable("Condcode should be pre-legalized away");
3542   case ISD::SETUEQ:
3543   case ISD::SETEQ:   return X86::COND_E;
3544   case ISD::SETOLT:              // flipped
3545   case ISD::SETOGT:
3546   case ISD::SETGT:   return X86::COND_A;
3547   case ISD::SETOLE:              // flipped
3548   case ISD::SETOGE:
3549   case ISD::SETGE:   return X86::COND_AE;
3550   case ISD::SETUGT:              // flipped
3551   case ISD::SETULT:
3552   case ISD::SETLT:   return X86::COND_B;
3553   case ISD::SETUGE:              // flipped
3554   case ISD::SETULE:
3555   case ISD::SETLE:   return X86::COND_BE;
3556   case ISD::SETONE:
3557   case ISD::SETNE:   return X86::COND_NE;
3558   case ISD::SETUO:   return X86::COND_P;
3559   case ISD::SETO:    return X86::COND_NP;
3560   case ISD::SETOEQ:
3561   case ISD::SETUNE:  return X86::COND_INVALID;
3562   }
3563 }
3564
3565 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3566 /// code. Current x86 isa includes the following FP cmov instructions:
3567 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3568 static bool hasFPCMov(unsigned X86CC) {
3569   switch (X86CC) {
3570   default:
3571     return false;
3572   case X86::COND_B:
3573   case X86::COND_BE:
3574   case X86::COND_E:
3575   case X86::COND_P:
3576   case X86::COND_A:
3577   case X86::COND_AE:
3578   case X86::COND_NE:
3579   case X86::COND_NP:
3580     return true;
3581   }
3582 }
3583
3584 /// isFPImmLegal - Returns true if the target can instruction select the
3585 /// specified FP immediate natively. If false, the legalizer will
3586 /// materialize the FP immediate as a load from a constant pool.
3587 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3588   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3589     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3590       return true;
3591   }
3592   return false;
3593 }
3594
3595 /// \brief Returns true if it is beneficial to convert a load of a constant
3596 /// to just the constant itself.
3597 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3598                                                           Type *Ty) const {
3599   assert(Ty->isIntegerTy());
3600
3601   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3602   if (BitSize == 0 || BitSize > 64)
3603     return false;
3604   return true;
3605 }
3606
3607 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3608 /// the specified range (L, H].
3609 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3610   return (Val < 0) || (Val >= Low && Val < Hi);
3611 }
3612
3613 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3614 /// specified value.
3615 static bool isUndefOrEqual(int Val, int CmpVal) {
3616   return (Val < 0 || Val == CmpVal);
3617 }
3618
3619 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3620 /// from position Pos and ending in Pos+Size, falls within the specified
3621 /// sequential range (L, L+Pos]. or is undef.
3622 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3623                                        unsigned Pos, unsigned Size, int Low) {
3624   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3625     if (!isUndefOrEqual(Mask[i], Low))
3626       return false;
3627   return true;
3628 }
3629
3630 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3631 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3632 /// the second operand.
3633 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3634   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3635     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3636   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3637     return (Mask[0] < 2 && Mask[1] < 2);
3638   return false;
3639 }
3640
3641 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3642 /// is suitable for input to PSHUFHW.
3643 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3644   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3645     return false;
3646
3647   // Lower quadword copied in order or undef.
3648   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3649     return false;
3650
3651   // Upper quadword shuffled.
3652   for (unsigned i = 4; i != 8; ++i)
3653     if (!isUndefOrInRange(Mask[i], 4, 8))
3654       return false;
3655
3656   if (VT == MVT::v16i16) {
3657     // Lower quadword copied in order or undef.
3658     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3659       return false;
3660
3661     // Upper quadword shuffled.
3662     for (unsigned i = 12; i != 16; ++i)
3663       if (!isUndefOrInRange(Mask[i], 12, 16))
3664         return false;
3665   }
3666
3667   return true;
3668 }
3669
3670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFLW.
3672 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3674     return false;
3675
3676   // Upper quadword copied in order.
3677   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3678     return false;
3679
3680   // Lower quadword shuffled.
3681   for (unsigned i = 0; i != 4; ++i)
3682     if (!isUndefOrInRange(Mask[i], 0, 4))
3683       return false;
3684
3685   if (VT == MVT::v16i16) {
3686     // Upper quadword copied in order.
3687     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3688       return false;
3689
3690     // Lower quadword shuffled.
3691     for (unsigned i = 8; i != 12; ++i)
3692       if (!isUndefOrInRange(Mask[i], 8, 12))
3693         return false;
3694   }
3695
3696   return true;
3697 }
3698
3699 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PALIGNR.
3701 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3702                           const X86Subtarget *Subtarget) {
3703   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3704       (VT.is256BitVector() && !Subtarget->hasInt256()))
3705     return false;
3706
3707   unsigned NumElts = VT.getVectorNumElements();
3708   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3709   unsigned NumLaneElts = NumElts/NumLanes;
3710
3711   // Do not handle 64-bit element shuffles with palignr.
3712   if (NumLaneElts == 2)
3713     return false;
3714
3715   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3716     unsigned i;
3717     for (i = 0; i != NumLaneElts; ++i) {
3718       if (Mask[i+l] >= 0)
3719         break;
3720     }
3721
3722     // Lane is all undef, go to next lane
3723     if (i == NumLaneElts)
3724       continue;
3725
3726     int Start = Mask[i+l];
3727
3728     // Make sure its in this lane in one of the sources
3729     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3730         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3731       return false;
3732
3733     // If not lane 0, then we must match lane 0
3734     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3735       return false;
3736
3737     // Correct second source to be contiguous with first source
3738     if (Start >= (int)NumElts)
3739       Start -= NumElts - NumLaneElts;
3740
3741     // Make sure we're shifting in the right direction.
3742     if (Start <= (int)(i+l))
3743       return false;
3744
3745     Start -= i;
3746
3747     // Check the rest of the elements to see if they are consecutive.
3748     for (++i; i != NumLaneElts; ++i) {
3749       int Idx = Mask[i+l];
3750
3751       // Make sure its in this lane
3752       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3753           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3754         return false;
3755
3756       // If not lane 0, then we must match lane 0
3757       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3758         return false;
3759
3760       if (Idx >= (int)NumElts)
3761         Idx -= NumElts - NumLaneElts;
3762
3763       if (!isUndefOrEqual(Idx, Start+i))
3764         return false;
3765
3766     }
3767   }
3768
3769   return true;
3770 }
3771
3772 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3773 /// the two vector operands have swapped position.
3774 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3775                                      unsigned NumElems) {
3776   for (unsigned i = 0; i != NumElems; ++i) {
3777     int idx = Mask[i];
3778     if (idx < 0)
3779       continue;
3780     else if (idx < (int)NumElems)
3781       Mask[i] = idx + NumElems;
3782     else
3783       Mask[i] = idx - NumElems;
3784   }
3785 }
3786
3787 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3788 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3789 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3790 /// reverse of what x86 shuffles want.
3791 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3792
3793   unsigned NumElems = VT.getVectorNumElements();
3794   unsigned NumLanes = VT.getSizeInBits()/128;
3795   unsigned NumLaneElems = NumElems/NumLanes;
3796
3797   if (NumLaneElems != 2 && NumLaneElems != 4)
3798     return false;
3799
3800   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3801   bool symetricMaskRequired =
3802     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3803
3804   // VSHUFPSY divides the resulting vector into 4 chunks.
3805   // The sources are also splitted into 4 chunks, and each destination
3806   // chunk must come from a different source chunk.
3807   //
3808   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3809   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3810   //
3811   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3812   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3813   //
3814   // VSHUFPDY divides the resulting vector into 4 chunks.
3815   // The sources are also splitted into 4 chunks, and each destination
3816   // chunk must come from a different source chunk.
3817   //
3818   //  SRC1 =>      X3       X2       X1       X0
3819   //  SRC2 =>      Y3       Y2       Y1       Y0
3820   //
3821   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3822   //
3823   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3824   unsigned HalfLaneElems = NumLaneElems/2;
3825   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3826     for (unsigned i = 0; i != NumLaneElems; ++i) {
3827       int Idx = Mask[i+l];
3828       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3829       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3830         return false;
3831       // For VSHUFPSY, the mask of the second half must be the same as the
3832       // first but with the appropriate offsets. This works in the same way as
3833       // VPERMILPS works with masks.
3834       if (!symetricMaskRequired || Idx < 0)
3835         continue;
3836       if (MaskVal[i] < 0) {
3837         MaskVal[i] = Idx - l;
3838         continue;
3839       }
3840       if ((signed)(Idx - l) != MaskVal[i])
3841         return false;
3842     }
3843   }
3844
3845   return true;
3846 }
3847
3848 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3850 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3851   if (!VT.is128BitVector())
3852     return false;
3853
3854   unsigned NumElems = VT.getVectorNumElements();
3855
3856   if (NumElems != 4)
3857     return false;
3858
3859   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3860   return isUndefOrEqual(Mask[0], 6) &&
3861          isUndefOrEqual(Mask[1], 7) &&
3862          isUndefOrEqual(Mask[2], 2) &&
3863          isUndefOrEqual(Mask[3], 3);
3864 }
3865
3866 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3867 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3868 /// <2, 3, 2, 3>
3869 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3870   if (!VT.is128BitVector())
3871     return false;
3872
3873   unsigned NumElems = VT.getVectorNumElements();
3874
3875   if (NumElems != 4)
3876     return false;
3877
3878   return isUndefOrEqual(Mask[0], 2) &&
3879          isUndefOrEqual(Mask[1], 3) &&
3880          isUndefOrEqual(Mask[2], 2) &&
3881          isUndefOrEqual(Mask[3], 3);
3882 }
3883
3884 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3886 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3887   if (!VT.is128BitVector())
3888     return false;
3889
3890   unsigned NumElems = VT.getVectorNumElements();
3891
3892   if (NumElems != 2 && NumElems != 4)
3893     return false;
3894
3895   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3896     if (!isUndefOrEqual(Mask[i], i + NumElems))
3897       return false;
3898
3899   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3900     if (!isUndefOrEqual(Mask[i], i))
3901       return false;
3902
3903   return true;
3904 }
3905
3906 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3907 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3908 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3909   if (!VT.is128BitVector())
3910     return false;
3911
3912   unsigned NumElems = VT.getVectorNumElements();
3913
3914   if (NumElems != 2 && NumElems != 4)
3915     return false;
3916
3917   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3918     if (!isUndefOrEqual(Mask[i], i))
3919       return false;
3920
3921   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3923       return false;
3924
3925   return true;
3926 }
3927
3928 //
3929 // Some special combinations that can be optimized.
3930 //
3931 static
3932 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3933                                SelectionDAG &DAG) {
3934   MVT VT = SVOp->getSimpleValueType(0);
3935   SDLoc dl(SVOp);
3936
3937   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3938     return SDValue();
3939
3940   ArrayRef<int> Mask = SVOp->getMask();
3941
3942   // These are the special masks that may be optimized.
3943   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3944   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3945   bool MatchEvenMask = true;
3946   bool MatchOddMask  = true;
3947   for (int i=0; i<8; ++i) {
3948     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3949       MatchEvenMask = false;
3950     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3951       MatchOddMask = false;
3952   }
3953
3954   if (!MatchEvenMask && !MatchOddMask)
3955     return SDValue();
3956
3957   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3958
3959   SDValue Op0 = SVOp->getOperand(0);
3960   SDValue Op1 = SVOp->getOperand(1);
3961
3962   if (MatchEvenMask) {
3963     // Shift the second operand right to 32 bits.
3964     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3965     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3966   } else {
3967     // Shift the first operand left to 32 bits.
3968     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3969     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3970   }
3971   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3972   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3973 }
3974
3975 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3976 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3977 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3978                          bool HasInt256, bool V2IsSplat = false) {
3979
3980   assert(VT.getSizeInBits() >= 128 &&
3981          "Unsupported vector type for unpckl");
3982
3983   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3984   unsigned NumLanes;
3985   unsigned NumOf256BitLanes;
3986   unsigned NumElts = VT.getVectorNumElements();
3987   if (VT.is256BitVector()) {
3988     if (NumElts != 4 && NumElts != 8 &&
3989         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3990     return false;
3991     NumLanes = 2;
3992     NumOf256BitLanes = 1;
3993   } else if (VT.is512BitVector()) {
3994     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3995            "Unsupported vector type for unpckh");
3996     NumLanes = 2;
3997     NumOf256BitLanes = 2;
3998   } else {
3999     NumLanes = 1;
4000     NumOf256BitLanes = 1;
4001   }
4002
4003   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4004   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4005
4006   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4007     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4008       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4009         int BitI  = Mask[l256*NumEltsInStride+l+i];
4010         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4011         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4012           return false;
4013         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4014           return false;
4015         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4016           return false;
4017       }
4018     }
4019   }
4020   return true;
4021 }
4022
4023 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4025 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4026                          bool HasInt256, bool V2IsSplat = false) {
4027   assert(VT.getSizeInBits() >= 128 &&
4028          "Unsupported vector type for unpckh");
4029
4030   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4031   unsigned NumLanes;
4032   unsigned NumOf256BitLanes;
4033   unsigned NumElts = VT.getVectorNumElements();
4034   if (VT.is256BitVector()) {
4035     if (NumElts != 4 && NumElts != 8 &&
4036         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4037     return false;
4038     NumLanes = 2;
4039     NumOf256BitLanes = 1;
4040   } else if (VT.is512BitVector()) {
4041     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4042            "Unsupported vector type for unpckh");
4043     NumLanes = 2;
4044     NumOf256BitLanes = 2;
4045   } else {
4046     NumLanes = 1;
4047     NumOf256BitLanes = 1;
4048   }
4049
4050   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4051   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4052
4053   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4054     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4055       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4056         int BitI  = Mask[l256*NumEltsInStride+l+i];
4057         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4058         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4059           return false;
4060         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4061           return false;
4062         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4063           return false;
4064       }
4065     }
4066   }
4067   return true;
4068 }
4069
4070 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4071 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4072 /// <0, 0, 1, 1>
4073 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4074   unsigned NumElts = VT.getVectorNumElements();
4075   bool Is256BitVec = VT.is256BitVector();
4076
4077   if (VT.is512BitVector())
4078     return false;
4079   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4080          "Unsupported vector type for unpckh");
4081
4082   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4083       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4084     return false;
4085
4086   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4087   // FIXME: Need a better way to get rid of this, there's no latency difference
4088   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4089   // the former later. We should also remove the "_undef" special mask.
4090   if (NumElts == 4 && Is256BitVec)
4091     return false;
4092
4093   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4094   // independently on 128-bit lanes.
4095   unsigned NumLanes = VT.getSizeInBits()/128;
4096   unsigned NumLaneElts = NumElts/NumLanes;
4097
4098   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4099     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4100       int BitI  = Mask[l+i];
4101       int BitI1 = Mask[l+i+1];
4102
4103       if (!isUndefOrEqual(BitI, j))
4104         return false;
4105       if (!isUndefOrEqual(BitI1, j))
4106         return false;
4107     }
4108   }
4109
4110   return true;
4111 }
4112
4113 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4114 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4115 /// <2, 2, 3, 3>
4116 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4117   unsigned NumElts = VT.getVectorNumElements();
4118
4119   if (VT.is512BitVector())
4120     return false;
4121
4122   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4123          "Unsupported vector type for unpckh");
4124
4125   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4126       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4127     return false;
4128
4129   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4130   // independently on 128-bit lanes.
4131   unsigned NumLanes = VT.getSizeInBits()/128;
4132   unsigned NumLaneElts = NumElts/NumLanes;
4133
4134   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4135     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4136       int BitI  = Mask[l+i];
4137       int BitI1 = Mask[l+i+1];
4138       if (!isUndefOrEqual(BitI, j))
4139         return false;
4140       if (!isUndefOrEqual(BitI1, j))
4141         return false;
4142     }
4143   }
4144   return true;
4145 }
4146
4147 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4148 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4149 /// MOVSD, and MOVD, i.e. setting the lowest element.
4150 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4151   if (VT.getVectorElementType().getSizeInBits() < 32)
4152     return false;
4153   if (!VT.is128BitVector())
4154     return false;
4155
4156   unsigned NumElts = VT.getVectorNumElements();
4157
4158   if (!isUndefOrEqual(Mask[0], NumElts))
4159     return false;
4160
4161   for (unsigned i = 1; i != NumElts; ++i)
4162     if (!isUndefOrEqual(Mask[i], i))
4163       return false;
4164
4165   return true;
4166 }
4167
4168 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4169 /// as permutations between 128-bit chunks or halves. As an example: this
4170 /// shuffle bellow:
4171 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4172 /// The first half comes from the second half of V1 and the second half from the
4173 /// the second half of V2.
4174 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4175   if (!HasFp256 || !VT.is256BitVector())
4176     return false;
4177
4178   // The shuffle result is divided into half A and half B. In total the two
4179   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4180   // B must come from C, D, E or F.
4181   unsigned HalfSize = VT.getVectorNumElements()/2;
4182   bool MatchA = false, MatchB = false;
4183
4184   // Check if A comes from one of C, D, E, F.
4185   for (unsigned Half = 0; Half != 4; ++Half) {
4186     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4187       MatchA = true;
4188       break;
4189     }
4190   }
4191
4192   // Check if B comes from one of C, D, E, F.
4193   for (unsigned Half = 0; Half != 4; ++Half) {
4194     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4195       MatchB = true;
4196       break;
4197     }
4198   }
4199
4200   return MatchA && MatchB;
4201 }
4202
4203 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4204 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4205 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4206   MVT VT = SVOp->getSimpleValueType(0);
4207
4208   unsigned HalfSize = VT.getVectorNumElements()/2;
4209
4210   unsigned FstHalf = 0, SndHalf = 0;
4211   for (unsigned i = 0; i < HalfSize; ++i) {
4212     if (SVOp->getMaskElt(i) > 0) {
4213       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4214       break;
4215     }
4216   }
4217   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4218     if (SVOp->getMaskElt(i) > 0) {
4219       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4220       break;
4221     }
4222   }
4223
4224   return (FstHalf | (SndHalf << 4));
4225 }
4226
4227 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4228 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4229   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4230   if (EltSize < 32)
4231     return false;
4232
4233   unsigned NumElts = VT.getVectorNumElements();
4234   Imm8 = 0;
4235   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4236     for (unsigned i = 0; i != NumElts; ++i) {
4237       if (Mask[i] < 0)
4238         continue;
4239       Imm8 |= Mask[i] << (i*2);
4240     }
4241     return true;
4242   }
4243
4244   unsigned LaneSize = 4;
4245   SmallVector<int, 4> MaskVal(LaneSize, -1);
4246
4247   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4248     for (unsigned i = 0; i != LaneSize; ++i) {
4249       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4250         return false;
4251       if (Mask[i+l] < 0)
4252         continue;
4253       if (MaskVal[i] < 0) {
4254         MaskVal[i] = Mask[i+l] - l;
4255         Imm8 |= MaskVal[i] << (i*2);
4256         continue;
4257       }
4258       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4259         return false;
4260     }
4261   }
4262   return true;
4263 }
4264
4265 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4266 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4267 /// Note that VPERMIL mask matching is different depending whether theunderlying
4268 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4269 /// to the same elements of the low, but to the higher half of the source.
4270 /// In VPERMILPD the two lanes could be shuffled independently of each other
4271 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4272 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4273   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4274   if (VT.getSizeInBits() < 256 || EltSize < 32)
4275     return false;
4276   bool symetricMaskRequired = (EltSize == 32);
4277   unsigned NumElts = VT.getVectorNumElements();
4278
4279   unsigned NumLanes = VT.getSizeInBits()/128;
4280   unsigned LaneSize = NumElts/NumLanes;
4281   // 2 or 4 elements in one lane
4282
4283   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4284   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4285     for (unsigned i = 0; i != LaneSize; ++i) {
4286       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4287         return false;
4288       if (symetricMaskRequired) {
4289         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4290           ExpectedMaskVal[i] = Mask[i+l] - l;
4291           continue;
4292         }
4293         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4294           return false;
4295       }
4296     }
4297   }
4298   return true;
4299 }
4300
4301 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4302 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4303 /// element of vector 2 and the other elements to come from vector 1 in order.
4304 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4305                                bool V2IsSplat = false, bool V2IsUndef = false) {
4306   if (!VT.is128BitVector())
4307     return false;
4308
4309   unsigned NumOps = VT.getVectorNumElements();
4310   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4311     return false;
4312
4313   if (!isUndefOrEqual(Mask[0], 0))
4314     return false;
4315
4316   for (unsigned i = 1; i != NumOps; ++i)
4317     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4318           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4319           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4320       return false;
4321
4322   return true;
4323 }
4324
4325 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4326 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4327 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4328 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4329                            const X86Subtarget *Subtarget) {
4330   if (!Subtarget->hasSSE3())
4331     return false;
4332
4333   unsigned NumElems = VT.getVectorNumElements();
4334
4335   if ((VT.is128BitVector() && NumElems != 4) ||
4336       (VT.is256BitVector() && NumElems != 8) ||
4337       (VT.is512BitVector() && NumElems != 16))
4338     return false;
4339
4340   // "i+1" is the value the indexed mask element must have
4341   for (unsigned i = 0; i != NumElems; i += 2)
4342     if (!isUndefOrEqual(Mask[i], i+1) ||
4343         !isUndefOrEqual(Mask[i+1], i+1))
4344       return false;
4345
4346   return true;
4347 }
4348
4349 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4350 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4351 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4352 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4353                            const X86Subtarget *Subtarget) {
4354   if (!Subtarget->hasSSE3())
4355     return false;
4356
4357   unsigned NumElems = VT.getVectorNumElements();
4358
4359   if ((VT.is128BitVector() && NumElems != 4) ||
4360       (VT.is256BitVector() && NumElems != 8) ||
4361       (VT.is512BitVector() && NumElems != 16))
4362     return false;
4363
4364   // "i" is the value the indexed mask element must have
4365   for (unsigned i = 0; i != NumElems; i += 2)
4366     if (!isUndefOrEqual(Mask[i], i) ||
4367         !isUndefOrEqual(Mask[i+1], i))
4368       return false;
4369
4370   return true;
4371 }
4372
4373 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4374 /// specifies a shuffle of elements that is suitable for input to 256-bit
4375 /// version of MOVDDUP.
4376 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4377   if (!HasFp256 || !VT.is256BitVector())
4378     return false;
4379
4380   unsigned NumElts = VT.getVectorNumElements();
4381   if (NumElts != 4)
4382     return false;
4383
4384   for (unsigned i = 0; i != NumElts/2; ++i)
4385     if (!isUndefOrEqual(Mask[i], 0))
4386       return false;
4387   for (unsigned i = NumElts/2; i != NumElts; ++i)
4388     if (!isUndefOrEqual(Mask[i], NumElts/2))
4389       return false;
4390   return true;
4391 }
4392
4393 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4394 /// specifies a shuffle of elements that is suitable for input to 128-bit
4395 /// version of MOVDDUP.
4396 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4397   if (!VT.is128BitVector())
4398     return false;
4399
4400   unsigned e = VT.getVectorNumElements() / 2;
4401   for (unsigned i = 0; i != e; ++i)
4402     if (!isUndefOrEqual(Mask[i], i))
4403       return false;
4404   for (unsigned i = 0; i != e; ++i)
4405     if (!isUndefOrEqual(Mask[e+i], i))
4406       return false;
4407   return true;
4408 }
4409
4410 /// isVEXTRACTIndex - Return true if the specified
4411 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4412 /// suitable for instruction that extract 128 or 256 bit vectors
4413 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4414   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4415   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4416     return false;
4417
4418   // The index should be aligned on a vecWidth-bit boundary.
4419   uint64_t Index =
4420     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4421
4422   MVT VT = N->getSimpleValueType(0);
4423   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4424   bool Result = (Index * ElSize) % vecWidth == 0;
4425
4426   return Result;
4427 }
4428
4429 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4430 /// operand specifies a subvector insert that is suitable for input to
4431 /// insertion of 128 or 256-bit subvectors
4432 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4433   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4434   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4435     return false;
4436   // The index should be aligned on a vecWidth-bit boundary.
4437   uint64_t Index =
4438     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4439
4440   MVT VT = N->getSimpleValueType(0);
4441   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4442   bool Result = (Index * ElSize) % vecWidth == 0;
4443
4444   return Result;
4445 }
4446
4447 bool X86::isVINSERT128Index(SDNode *N) {
4448   return isVINSERTIndex(N, 128);
4449 }
4450
4451 bool X86::isVINSERT256Index(SDNode *N) {
4452   return isVINSERTIndex(N, 256);
4453 }
4454
4455 bool X86::isVEXTRACT128Index(SDNode *N) {
4456   return isVEXTRACTIndex(N, 128);
4457 }
4458
4459 bool X86::isVEXTRACT256Index(SDNode *N) {
4460   return isVEXTRACTIndex(N, 256);
4461 }
4462
4463 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4464 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4465 /// Handles 128-bit and 256-bit.
4466 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4467   MVT VT = N->getSimpleValueType(0);
4468
4469   assert((VT.getSizeInBits() >= 128) &&
4470          "Unsupported vector type for PSHUF/SHUFP");
4471
4472   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4473   // independently on 128-bit lanes.
4474   unsigned NumElts = VT.getVectorNumElements();
4475   unsigned NumLanes = VT.getSizeInBits()/128;
4476   unsigned NumLaneElts = NumElts/NumLanes;
4477
4478   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4479          "Only supports 2, 4 or 8 elements per lane");
4480
4481   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4482   unsigned Mask = 0;
4483   for (unsigned i = 0; i != NumElts; ++i) {
4484     int Elt = N->getMaskElt(i);
4485     if (Elt < 0) continue;
4486     Elt &= NumLaneElts - 1;
4487     unsigned ShAmt = (i << Shift) % 8;
4488     Mask |= Elt << ShAmt;
4489   }
4490
4491   return Mask;
4492 }
4493
4494 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4495 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4496 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4497   MVT VT = N->getSimpleValueType(0);
4498
4499   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4500          "Unsupported vector type for PSHUFHW");
4501
4502   unsigned NumElts = VT.getVectorNumElements();
4503
4504   unsigned Mask = 0;
4505   for (unsigned l = 0; l != NumElts; l += 8) {
4506     // 8 nodes per lane, but we only care about the last 4.
4507     for (unsigned i = 0; i < 4; ++i) {
4508       int Elt = N->getMaskElt(l+i+4);
4509       if (Elt < 0) continue;
4510       Elt &= 0x3; // only 2-bits.
4511       Mask |= Elt << (i * 2);
4512     }
4513   }
4514
4515   return Mask;
4516 }
4517
4518 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4519 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4520 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4521   MVT VT = N->getSimpleValueType(0);
4522
4523   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4524          "Unsupported vector type for PSHUFHW");
4525
4526   unsigned NumElts = VT.getVectorNumElements();
4527
4528   unsigned Mask = 0;
4529   for (unsigned l = 0; l != NumElts; l += 8) {
4530     // 8 nodes per lane, but we only care about the first 4.
4531     for (unsigned i = 0; i < 4; ++i) {
4532       int Elt = N->getMaskElt(l+i);
4533       if (Elt < 0) continue;
4534       Elt &= 0x3; // only 2-bits
4535       Mask |= Elt << (i * 2);
4536     }
4537   }
4538
4539   return Mask;
4540 }
4541
4542 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4543 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4544 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4545   MVT VT = SVOp->getSimpleValueType(0);
4546   unsigned EltSize = VT.is512BitVector() ? 1 :
4547     VT.getVectorElementType().getSizeInBits() >> 3;
4548
4549   unsigned NumElts = VT.getVectorNumElements();
4550   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4551   unsigned NumLaneElts = NumElts/NumLanes;
4552
4553   int Val = 0;
4554   unsigned i;
4555   for (i = 0; i != NumElts; ++i) {
4556     Val = SVOp->getMaskElt(i);
4557     if (Val >= 0)
4558       break;
4559   }
4560   if (Val >= (int)NumElts)
4561     Val -= NumElts - NumLaneElts;
4562
4563   assert(Val - i > 0 && "PALIGNR imm should be positive");
4564   return (Val - i) * EltSize;
4565 }
4566
4567 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4568   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4569   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4570     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4571
4572   uint64_t Index =
4573     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4574
4575   MVT VecVT = N->getOperand(0).getSimpleValueType();
4576   MVT ElVT = VecVT.getVectorElementType();
4577
4578   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4579   return Index / NumElemsPerChunk;
4580 }
4581
4582 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4583   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4584   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4585     llvm_unreachable("Illegal insert subvector for VINSERT");
4586
4587   uint64_t Index =
4588     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4589
4590   MVT VecVT = N->getSimpleValueType(0);
4591   MVT ElVT = VecVT.getVectorElementType();
4592
4593   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4594   return Index / NumElemsPerChunk;
4595 }
4596
4597 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4598 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4599 /// and VINSERTI128 instructions.
4600 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4601   return getExtractVEXTRACTImmediate(N, 128);
4602 }
4603
4604 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4605 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4606 /// and VINSERTI64x4 instructions.
4607 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4608   return getExtractVEXTRACTImmediate(N, 256);
4609 }
4610
4611 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4612 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4613 /// and VINSERTI128 instructions.
4614 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4615   return getInsertVINSERTImmediate(N, 128);
4616 }
4617
4618 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4619 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4620 /// and VINSERTI64x4 instructions.
4621 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4622   return getInsertVINSERTImmediate(N, 256);
4623 }
4624
4625 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4626 /// constant +0.0.
4627 bool X86::isZeroNode(SDValue Elt) {
4628   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4629     return CN->isNullValue();
4630   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4631     return CFP->getValueAPF().isPosZero();
4632   return false;
4633 }
4634
4635 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4636 /// their permute mask.
4637 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4638                                     SelectionDAG &DAG) {
4639   MVT VT = SVOp->getSimpleValueType(0);
4640   unsigned NumElems = VT.getVectorNumElements();
4641   SmallVector<int, 8> MaskVec;
4642
4643   for (unsigned i = 0; i != NumElems; ++i) {
4644     int Idx = SVOp->getMaskElt(i);
4645     if (Idx >= 0) {
4646       if (Idx < (int)NumElems)
4647         Idx += NumElems;
4648       else
4649         Idx -= NumElems;
4650     }
4651     MaskVec.push_back(Idx);
4652   }
4653   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4654                               SVOp->getOperand(0), &MaskVec[0]);
4655 }
4656
4657 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4658 /// match movhlps. The lower half elements should come from upper half of
4659 /// V1 (and in order), and the upper half elements should come from the upper
4660 /// half of V2 (and in order).
4661 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4662   if (!VT.is128BitVector())
4663     return false;
4664   if (VT.getVectorNumElements() != 4)
4665     return false;
4666   for (unsigned i = 0, e = 2; i != e; ++i)
4667     if (!isUndefOrEqual(Mask[i], i+2))
4668       return false;
4669   for (unsigned i = 2; i != 4; ++i)
4670     if (!isUndefOrEqual(Mask[i], i+4))
4671       return false;
4672   return true;
4673 }
4674
4675 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4676 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4677 /// required.
4678 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4679   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4680     return false;
4681   N = N->getOperand(0).getNode();
4682   if (!ISD::isNON_EXTLoad(N))
4683     return false;
4684   if (LD)
4685     *LD = cast<LoadSDNode>(N);
4686   return true;
4687 }
4688
4689 // Test whether the given value is a vector value which will be legalized
4690 // into a load.
4691 static bool WillBeConstantPoolLoad(SDNode *N) {
4692   if (N->getOpcode() != ISD::BUILD_VECTOR)
4693     return false;
4694
4695   // Check for any non-constant elements.
4696   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4697     switch (N->getOperand(i).getNode()->getOpcode()) {
4698     case ISD::UNDEF:
4699     case ISD::ConstantFP:
4700     case ISD::Constant:
4701       break;
4702     default:
4703       return false;
4704     }
4705
4706   // Vectors of all-zeros and all-ones are materialized with special
4707   // instructions rather than being loaded.
4708   return !ISD::isBuildVectorAllZeros(N) &&
4709          !ISD::isBuildVectorAllOnes(N);
4710 }
4711
4712 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4713 /// match movlp{s|d}. The lower half elements should come from lower half of
4714 /// V1 (and in order), and the upper half elements should come from the upper
4715 /// half of V2 (and in order). And since V1 will become the source of the
4716 /// MOVLP, it must be either a vector load or a scalar load to vector.
4717 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4718                                ArrayRef<int> Mask, MVT VT) {
4719   if (!VT.is128BitVector())
4720     return false;
4721
4722   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4723     return false;
4724   // Is V2 is a vector load, don't do this transformation. We will try to use
4725   // load folding shufps op.
4726   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4727     return false;
4728
4729   unsigned NumElems = VT.getVectorNumElements();
4730
4731   if (NumElems != 2 && NumElems != 4)
4732     return false;
4733   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4734     if (!isUndefOrEqual(Mask[i], i))
4735       return false;
4736   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4737     if (!isUndefOrEqual(Mask[i], i+NumElems))
4738       return false;
4739   return true;
4740 }
4741
4742 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4743 /// all the same.
4744 static bool isSplatVector(SDNode *N) {
4745   if (N->getOpcode() != ISD::BUILD_VECTOR)
4746     return false;
4747
4748   SDValue SplatValue = N->getOperand(0);
4749   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4750     if (N->getOperand(i) != SplatValue)
4751       return false;
4752   return true;
4753 }
4754
4755 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4756 /// to an zero vector.
4757 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4758 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4759   SDValue V1 = N->getOperand(0);
4760   SDValue V2 = N->getOperand(1);
4761   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4762   for (unsigned i = 0; i != NumElems; ++i) {
4763     int Idx = N->getMaskElt(i);
4764     if (Idx >= (int)NumElems) {
4765       unsigned Opc = V2.getOpcode();
4766       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4767         continue;
4768       if (Opc != ISD::BUILD_VECTOR ||
4769           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4770         return false;
4771     } else if (Idx >= 0) {
4772       unsigned Opc = V1.getOpcode();
4773       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4774         continue;
4775       if (Opc != ISD::BUILD_VECTOR ||
4776           !X86::isZeroNode(V1.getOperand(Idx)))
4777         return false;
4778     }
4779   }
4780   return true;
4781 }
4782
4783 /// getZeroVector - Returns a vector of specified type with all zero elements.
4784 ///
4785 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4786                              SelectionDAG &DAG, SDLoc dl) {
4787   assert(VT.isVector() && "Expected a vector type");
4788
4789   // Always build SSE zero vectors as <4 x i32> bitcasted
4790   // to their dest type. This ensures they get CSE'd.
4791   SDValue Vec;
4792   if (VT.is128BitVector()) {  // SSE
4793     if (Subtarget->hasSSE2()) {  // SSE2
4794       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4795       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4796     } else { // SSE1
4797       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4798       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4799     }
4800   } else if (VT.is256BitVector()) { // AVX
4801     if (Subtarget->hasInt256()) { // AVX2
4802       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4803       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4804       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4805                         array_lengthof(Ops));
4806     } else {
4807       // 256-bit logic and arithmetic instructions in AVX are all
4808       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4809       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4810       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4811       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4812                         array_lengthof(Ops));
4813     }
4814   } else if (VT.is512BitVector()) { // AVX-512
4815       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4816       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4817                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4818       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4819   } else if (VT.getScalarType() == MVT::i1) {
4820     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4821     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4822     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4825                        Ops, VT.getVectorNumElements());
4826   } else
4827     llvm_unreachable("Unexpected vector type");
4828
4829   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4830 }
4831
4832 /// getOnesVector - Returns a vector of specified type with all bits set.
4833 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4834 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4835 /// Then bitcast to their original type, ensuring they get CSE'd.
4836 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4837                              SDLoc dl) {
4838   assert(VT.isVector() && "Expected a vector type");
4839
4840   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4841   SDValue Vec;
4842   if (VT.is256BitVector()) {
4843     if (HasInt256) { // AVX2
4844       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4845       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4846                         array_lengthof(Ops));
4847     } else { // AVX
4848       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4849       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4850     }
4851   } else if (VT.is128BitVector()) {
4852     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4853   } else
4854     llvm_unreachable("Unexpected vector type");
4855
4856   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4857 }
4858
4859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4860 /// that point to V2 points to its first element.
4861 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4862   for (unsigned i = 0; i != NumElems; ++i) {
4863     if (Mask[i] > (int)NumElems) {
4864       Mask[i] = NumElems;
4865     }
4866   }
4867 }
4868
4869 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4870 /// operation of specified width.
4871 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4872                        SDValue V2) {
4873   unsigned NumElems = VT.getVectorNumElements();
4874   SmallVector<int, 8> Mask;
4875   Mask.push_back(NumElems);
4876   for (unsigned i = 1; i != NumElems; ++i)
4877     Mask.push_back(i);
4878   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4879 }
4880
4881 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4882 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4883                           SDValue V2) {
4884   unsigned NumElems = VT.getVectorNumElements();
4885   SmallVector<int, 8> Mask;
4886   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4887     Mask.push_back(i);
4888     Mask.push_back(i + NumElems);
4889   }
4890   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4891 }
4892
4893 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4894 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4895                           SDValue V2) {
4896   unsigned NumElems = VT.getVectorNumElements();
4897   SmallVector<int, 8> Mask;
4898   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4899     Mask.push_back(i + Half);
4900     Mask.push_back(i + NumElems + Half);
4901   }
4902   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4903 }
4904
4905 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4906 // a generic shuffle instruction because the target has no such instructions.
4907 // Generate shuffles which repeat i16 and i8 several times until they can be
4908 // represented by v4f32 and then be manipulated by target suported shuffles.
4909 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4910   MVT VT = V.getSimpleValueType();
4911   int NumElems = VT.getVectorNumElements();
4912   SDLoc dl(V);
4913
4914   while (NumElems > 4) {
4915     if (EltNo < NumElems/2) {
4916       V = getUnpackl(DAG, dl, VT, V, V);
4917     } else {
4918       V = getUnpackh(DAG, dl, VT, V, V);
4919       EltNo -= NumElems/2;
4920     }
4921     NumElems >>= 1;
4922   }
4923   return V;
4924 }
4925
4926 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4927 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4928   MVT VT = V.getSimpleValueType();
4929   SDLoc dl(V);
4930
4931   if (VT.is128BitVector()) {
4932     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4933     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4934     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4935                              &SplatMask[0]);
4936   } else if (VT.is256BitVector()) {
4937     // To use VPERMILPS to splat scalars, the second half of indicies must
4938     // refer to the higher part, which is a duplication of the lower one,
4939     // because VPERMILPS can only handle in-lane permutations.
4940     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4941                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4942
4943     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4944     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4945                              &SplatMask[0]);
4946   } else
4947     llvm_unreachable("Vector size not supported");
4948
4949   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4950 }
4951
4952 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4953 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4954   MVT SrcVT = SV->getSimpleValueType(0);
4955   SDValue V1 = SV->getOperand(0);
4956   SDLoc dl(SV);
4957
4958   int EltNo = SV->getSplatIndex();
4959   int NumElems = SrcVT.getVectorNumElements();
4960   bool Is256BitVec = SrcVT.is256BitVector();
4961
4962   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4963          "Unknown how to promote splat for type");
4964
4965   // Extract the 128-bit part containing the splat element and update
4966   // the splat element index when it refers to the higher register.
4967   if (Is256BitVec) {
4968     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4969     if (EltNo >= NumElems/2)
4970       EltNo -= NumElems/2;
4971   }
4972
4973   // All i16 and i8 vector types can't be used directly by a generic shuffle
4974   // instruction because the target has no such instruction. Generate shuffles
4975   // which repeat i16 and i8 several times until they fit in i32, and then can
4976   // be manipulated by target suported shuffles.
4977   MVT EltVT = SrcVT.getVectorElementType();
4978   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4979     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4980
4981   // Recreate the 256-bit vector and place the same 128-bit vector
4982   // into the low and high part. This is necessary because we want
4983   // to use VPERM* to shuffle the vectors
4984   if (Is256BitVec) {
4985     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4986   }
4987
4988   return getLegalSplat(DAG, V1, EltNo);
4989 }
4990
4991 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4992 /// vector of zero or undef vector.  This produces a shuffle where the low
4993 /// element of V2 is swizzled into the zero/undef vector, landing at element
4994 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4995 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4996                                            bool IsZero,
4997                                            const X86Subtarget *Subtarget,
4998                                            SelectionDAG &DAG) {
4999   MVT VT = V2.getSimpleValueType();
5000   SDValue V1 = IsZero
5001     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5002   unsigned NumElems = VT.getVectorNumElements();
5003   SmallVector<int, 16> MaskVec;
5004   for (unsigned i = 0; i != NumElems; ++i)
5005     // If this is the insertion idx, put the low elt of V2 here.
5006     MaskVec.push_back(i == Idx ? NumElems : i);
5007   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5008 }
5009
5010 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5011 /// target specific opcode. Returns true if the Mask could be calculated.
5012 /// Sets IsUnary to true if only uses one source.
5013 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5014                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5015   unsigned NumElems = VT.getVectorNumElements();
5016   SDValue ImmN;
5017
5018   IsUnary = false;
5019   switch(N->getOpcode()) {
5020   case X86ISD::SHUFP:
5021     ImmN = N->getOperand(N->getNumOperands()-1);
5022     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5023     break;
5024   case X86ISD::UNPCKH:
5025     DecodeUNPCKHMask(VT, Mask);
5026     break;
5027   case X86ISD::UNPCKL:
5028     DecodeUNPCKLMask(VT, Mask);
5029     break;
5030   case X86ISD::MOVHLPS:
5031     DecodeMOVHLPSMask(NumElems, Mask);
5032     break;
5033   case X86ISD::MOVLHPS:
5034     DecodeMOVLHPSMask(NumElems, Mask);
5035     break;
5036   case X86ISD::PALIGNR:
5037     ImmN = N->getOperand(N->getNumOperands()-1);
5038     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5039     break;
5040   case X86ISD::PSHUFD:
5041   case X86ISD::VPERMILP:
5042     ImmN = N->getOperand(N->getNumOperands()-1);
5043     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5044     IsUnary = true;
5045     break;
5046   case X86ISD::PSHUFHW:
5047     ImmN = N->getOperand(N->getNumOperands()-1);
5048     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5049     IsUnary = true;
5050     break;
5051   case X86ISD::PSHUFLW:
5052     ImmN = N->getOperand(N->getNumOperands()-1);
5053     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5054     IsUnary = true;
5055     break;
5056   case X86ISD::VPERMI:
5057     ImmN = N->getOperand(N->getNumOperands()-1);
5058     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5059     IsUnary = true;
5060     break;
5061   case X86ISD::MOVSS:
5062   case X86ISD::MOVSD: {
5063     // The index 0 always comes from the first element of the second source,
5064     // this is why MOVSS and MOVSD are used in the first place. The other
5065     // elements come from the other positions of the first source vector
5066     Mask.push_back(NumElems);
5067     for (unsigned i = 1; i != NumElems; ++i) {
5068       Mask.push_back(i);
5069     }
5070     break;
5071   }
5072   case X86ISD::VPERM2X128:
5073     ImmN = N->getOperand(N->getNumOperands()-1);
5074     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075     if (Mask.empty()) return false;
5076     break;
5077   case X86ISD::MOVDDUP:
5078   case X86ISD::MOVLHPD:
5079   case X86ISD::MOVLPD:
5080   case X86ISD::MOVLPS:
5081   case X86ISD::MOVSHDUP:
5082   case X86ISD::MOVSLDUP:
5083     // Not yet implemented
5084     return false;
5085   default: llvm_unreachable("unknown target shuffle node");
5086   }
5087
5088   return true;
5089 }
5090
5091 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5092 /// element of the result of the vector shuffle.
5093 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5094                                    unsigned Depth) {
5095   if (Depth == 6)
5096     return SDValue();  // Limit search depth.
5097
5098   SDValue V = SDValue(N, 0);
5099   EVT VT = V.getValueType();
5100   unsigned Opcode = V.getOpcode();
5101
5102   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5103   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5104     int Elt = SV->getMaskElt(Index);
5105
5106     if (Elt < 0)
5107       return DAG.getUNDEF(VT.getVectorElementType());
5108
5109     unsigned NumElems = VT.getVectorNumElements();
5110     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5111                                          : SV->getOperand(1);
5112     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5113   }
5114
5115   // Recurse into target specific vector shuffles to find scalars.
5116   if (isTargetShuffle(Opcode)) {
5117     MVT ShufVT = V.getSimpleValueType();
5118     unsigned NumElems = ShufVT.getVectorNumElements();
5119     SmallVector<int, 16> ShuffleMask;
5120     bool IsUnary;
5121
5122     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5123       return SDValue();
5124
5125     int Elt = ShuffleMask[Index];
5126     if (Elt < 0)
5127       return DAG.getUNDEF(ShufVT.getVectorElementType());
5128
5129     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5130                                          : N->getOperand(1);
5131     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5132                                Depth+1);
5133   }
5134
5135   // Actual nodes that may contain scalar elements
5136   if (Opcode == ISD::BITCAST) {
5137     V = V.getOperand(0);
5138     EVT SrcVT = V.getValueType();
5139     unsigned NumElems = VT.getVectorNumElements();
5140
5141     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5142       return SDValue();
5143   }
5144
5145   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5146     return (Index == 0) ? V.getOperand(0)
5147                         : DAG.getUNDEF(VT.getVectorElementType());
5148
5149   if (V.getOpcode() == ISD::BUILD_VECTOR)
5150     return V.getOperand(Index);
5151
5152   return SDValue();
5153 }
5154
5155 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5156 /// shuffle operation which come from a consecutively from a zero. The
5157 /// search can start in two different directions, from left or right.
5158 /// We count undefs as zeros until PreferredNum is reached.
5159 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5160                                          unsigned NumElems, bool ZerosFromLeft,
5161                                          SelectionDAG &DAG,
5162                                          unsigned PreferredNum = -1U) {
5163   unsigned NumZeros = 0;
5164   for (unsigned i = 0; i != NumElems; ++i) {
5165     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5166     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5167     if (!Elt.getNode())
5168       break;
5169
5170     if (X86::isZeroNode(Elt))
5171       ++NumZeros;
5172     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5173       NumZeros = std::min(NumZeros + 1, PreferredNum);
5174     else
5175       break;
5176   }
5177
5178   return NumZeros;
5179 }
5180
5181 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5182 /// correspond consecutively to elements from one of the vector operands,
5183 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5184 static
5185 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5186                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5187                               unsigned NumElems, unsigned &OpNum) {
5188   bool SeenV1 = false;
5189   bool SeenV2 = false;
5190
5191   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5192     int Idx = SVOp->getMaskElt(i);
5193     // Ignore undef indicies
5194     if (Idx < 0)
5195       continue;
5196
5197     if (Idx < (int)NumElems)
5198       SeenV1 = true;
5199     else
5200       SeenV2 = true;
5201
5202     // Only accept consecutive elements from the same vector
5203     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5204       return false;
5205   }
5206
5207   OpNum = SeenV1 ? 0 : 1;
5208   return true;
5209 }
5210
5211 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5212 /// logical left shift of a vector.
5213 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5214                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5215   unsigned NumElems =
5216     SVOp->getSimpleValueType(0).getVectorNumElements();
5217   unsigned NumZeros = getNumOfConsecutiveZeros(
5218       SVOp, NumElems, false /* check zeros from right */, DAG,
5219       SVOp->getMaskElt(0));
5220   unsigned OpSrc;
5221
5222   if (!NumZeros)
5223     return false;
5224
5225   // Considering the elements in the mask that are not consecutive zeros,
5226   // check if they consecutively come from only one of the source vectors.
5227   //
5228   //               V1 = {X, A, B, C}     0
5229   //                         \  \  \    /
5230   //   vector_shuffle V1, V2 <1, 2, 3, X>
5231   //
5232   if (!isShuffleMaskConsecutive(SVOp,
5233             0,                   // Mask Start Index
5234             NumElems-NumZeros,   // Mask End Index(exclusive)
5235             NumZeros,            // Where to start looking in the src vector
5236             NumElems,            // Number of elements in vector
5237             OpSrc))              // Which source operand ?
5238     return false;
5239
5240   isLeft = false;
5241   ShAmt = NumZeros;
5242   ShVal = SVOp->getOperand(OpSrc);
5243   return true;
5244 }
5245
5246 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5247 /// logical left shift of a vector.
5248 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5249                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5250   unsigned NumElems =
5251     SVOp->getSimpleValueType(0).getVectorNumElements();
5252   unsigned NumZeros = getNumOfConsecutiveZeros(
5253       SVOp, NumElems, true /* check zeros from left */, DAG,
5254       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5255   unsigned OpSrc;
5256
5257   if (!NumZeros)
5258     return false;
5259
5260   // Considering the elements in the mask that are not consecutive zeros,
5261   // check if they consecutively come from only one of the source vectors.
5262   //
5263   //                           0    { A, B, X, X } = V2
5264   //                          / \    /  /
5265   //   vector_shuffle V1, V2 <X, X, 4, 5>
5266   //
5267   if (!isShuffleMaskConsecutive(SVOp,
5268             NumZeros,     // Mask Start Index
5269             NumElems,     // Mask End Index(exclusive)
5270             0,            // Where to start looking in the src vector
5271             NumElems,     // Number of elements in vector
5272             OpSrc))       // Which source operand ?
5273     return false;
5274
5275   isLeft = true;
5276   ShAmt = NumZeros;
5277   ShVal = SVOp->getOperand(OpSrc);
5278   return true;
5279 }
5280
5281 /// isVectorShift - Returns true if the shuffle can be implemented as a
5282 /// logical left or right shift of a vector.
5283 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5284                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5285   // Although the logic below support any bitwidth size, there are no
5286   // shift instructions which handle more than 128-bit vectors.
5287   if (!SVOp->getSimpleValueType(0).is128BitVector())
5288     return false;
5289
5290   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5291       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5292     return true;
5293
5294   return false;
5295 }
5296
5297 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5298 ///
5299 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5300                                        unsigned NumNonZero, unsigned NumZero,
5301                                        SelectionDAG &DAG,
5302                                        const X86Subtarget* Subtarget,
5303                                        const TargetLowering &TLI) {
5304   if (NumNonZero > 8)
5305     return SDValue();
5306
5307   SDLoc dl(Op);
5308   SDValue V(0, 0);
5309   bool First = true;
5310   for (unsigned i = 0; i < 16; ++i) {
5311     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5312     if (ThisIsNonZero && First) {
5313       if (NumZero)
5314         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5315       else
5316         V = DAG.getUNDEF(MVT::v8i16);
5317       First = false;
5318     }
5319
5320     if ((i & 1) != 0) {
5321       SDValue ThisElt(0, 0), LastElt(0, 0);
5322       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5323       if (LastIsNonZero) {
5324         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5325                               MVT::i16, Op.getOperand(i-1));
5326       }
5327       if (ThisIsNonZero) {
5328         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5329         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5330                               ThisElt, DAG.getConstant(8, MVT::i8));
5331         if (LastIsNonZero)
5332           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5333       } else
5334         ThisElt = LastElt;
5335
5336       if (ThisElt.getNode())
5337         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5338                         DAG.getIntPtrConstant(i/2));
5339     }
5340   }
5341
5342   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5343 }
5344
5345 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5346 ///
5347 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5348                                      unsigned NumNonZero, unsigned NumZero,
5349                                      SelectionDAG &DAG,
5350                                      const X86Subtarget* Subtarget,
5351                                      const TargetLowering &TLI) {
5352   if (NumNonZero > 4)
5353     return SDValue();
5354
5355   SDLoc dl(Op);
5356   SDValue V(0, 0);
5357   bool First = true;
5358   for (unsigned i = 0; i < 8; ++i) {
5359     bool isNonZero = (NonZeros & (1 << i)) != 0;
5360     if (isNonZero) {
5361       if (First) {
5362         if (NumZero)
5363           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5364         else
5365           V = DAG.getUNDEF(MVT::v8i16);
5366         First = false;
5367       }
5368       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5369                       MVT::v8i16, V, Op.getOperand(i),
5370                       DAG.getIntPtrConstant(i));
5371     }
5372   }
5373
5374   return V;
5375 }
5376
5377 /// getVShift - Return a vector logical shift node.
5378 ///
5379 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5380                          unsigned NumBits, SelectionDAG &DAG,
5381                          const TargetLowering &TLI, SDLoc dl) {
5382   assert(VT.is128BitVector() && "Unknown type for VShift");
5383   EVT ShVT = MVT::v2i64;
5384   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5385   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5386   return DAG.getNode(ISD::BITCAST, dl, VT,
5387                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5388                              DAG.getConstant(NumBits,
5389                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5390 }
5391
5392 static SDValue
5393 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5394
5395   // Check if the scalar load can be widened into a vector load. And if
5396   // the address is "base + cst" see if the cst can be "absorbed" into
5397   // the shuffle mask.
5398   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5399     SDValue Ptr = LD->getBasePtr();
5400     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5401       return SDValue();
5402     EVT PVT = LD->getValueType(0);
5403     if (PVT != MVT::i32 && PVT != MVT::f32)
5404       return SDValue();
5405
5406     int FI = -1;
5407     int64_t Offset = 0;
5408     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5409       FI = FINode->getIndex();
5410       Offset = 0;
5411     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5412                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5413       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5414       Offset = Ptr.getConstantOperandVal(1);
5415       Ptr = Ptr.getOperand(0);
5416     } else {
5417       return SDValue();
5418     }
5419
5420     // FIXME: 256-bit vector instructions don't require a strict alignment,
5421     // improve this code to support it better.
5422     unsigned RequiredAlign = VT.getSizeInBits()/8;
5423     SDValue Chain = LD->getChain();
5424     // Make sure the stack object alignment is at least 16 or 32.
5425     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5426     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5427       if (MFI->isFixedObjectIndex(FI)) {
5428         // Can't change the alignment. FIXME: It's possible to compute
5429         // the exact stack offset and reference FI + adjust offset instead.
5430         // If someone *really* cares about this. That's the way to implement it.
5431         return SDValue();
5432       } else {
5433         MFI->setObjectAlignment(FI, RequiredAlign);
5434       }
5435     }
5436
5437     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5438     // Ptr + (Offset & ~15).
5439     if (Offset < 0)
5440       return SDValue();
5441     if ((Offset % RequiredAlign) & 3)
5442       return SDValue();
5443     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5444     if (StartOffset)
5445       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5446                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5447
5448     int EltNo = (Offset - StartOffset) >> 2;
5449     unsigned NumElems = VT.getVectorNumElements();
5450
5451     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5452     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5453                              LD->getPointerInfo().getWithOffset(StartOffset),
5454                              false, false, false, 0);
5455
5456     SmallVector<int, 8> Mask;
5457     for (unsigned i = 0; i != NumElems; ++i)
5458       Mask.push_back(EltNo);
5459
5460     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5461   }
5462
5463   return SDValue();
5464 }
5465
5466 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5467 /// vector of type 'VT', see if the elements can be replaced by a single large
5468 /// load which has the same value as a build_vector whose operands are 'elts'.
5469 ///
5470 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5471 ///
5472 /// FIXME: we'd also like to handle the case where the last elements are zero
5473 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5474 /// There's even a handy isZeroNode for that purpose.
5475 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5476                                         SDLoc &DL, SelectionDAG &DAG,
5477                                         bool isAfterLegalize) {
5478   EVT EltVT = VT.getVectorElementType();
5479   unsigned NumElems = Elts.size();
5480
5481   LoadSDNode *LDBase = NULL;
5482   unsigned LastLoadedElt = -1U;
5483
5484   // For each element in the initializer, see if we've found a load or an undef.
5485   // If we don't find an initial load element, or later load elements are
5486   // non-consecutive, bail out.
5487   for (unsigned i = 0; i < NumElems; ++i) {
5488     SDValue Elt = Elts[i];
5489
5490     if (!Elt.getNode() ||
5491         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5492       return SDValue();
5493     if (!LDBase) {
5494       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5495         return SDValue();
5496       LDBase = cast<LoadSDNode>(Elt.getNode());
5497       LastLoadedElt = i;
5498       continue;
5499     }
5500     if (Elt.getOpcode() == ISD::UNDEF)
5501       continue;
5502
5503     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5504     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5505       return SDValue();
5506     LastLoadedElt = i;
5507   }
5508
5509   // If we have found an entire vector of loads and undefs, then return a large
5510   // load of the entire vector width starting at the base pointer.  If we found
5511   // consecutive loads for the low half, generate a vzext_load node.
5512   if (LastLoadedElt == NumElems - 1) {
5513
5514     if (isAfterLegalize &&
5515         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5516       return SDValue();
5517
5518     SDValue NewLd = SDValue();
5519
5520     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5521       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5522                           LDBase->getPointerInfo(),
5523                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5524                           LDBase->isInvariant(), 0);
5525     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5526                         LDBase->getPointerInfo(),
5527                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5528                         LDBase->isInvariant(), LDBase->getAlignment());
5529
5530     if (LDBase->hasAnyUseOfValue(1)) {
5531       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5532                                      SDValue(LDBase, 1),
5533                                      SDValue(NewLd.getNode(), 1));
5534       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5535       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5536                              SDValue(NewLd.getNode(), 1));
5537     }
5538
5539     return NewLd;
5540   }
5541   if (NumElems == 4 && LastLoadedElt == 1 &&
5542       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5543     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5544     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5545     SDValue ResNode =
5546         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5547                                 array_lengthof(Ops), MVT::i64,
5548                                 LDBase->getPointerInfo(),
5549                                 LDBase->getAlignment(),
5550                                 false/*isVolatile*/, true/*ReadMem*/,
5551                                 false/*WriteMem*/);
5552
5553     // Make sure the newly-created LOAD is in the same position as LDBase in
5554     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5555     // update uses of LDBase's output chain to use the TokenFactor.
5556     if (LDBase->hasAnyUseOfValue(1)) {
5557       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5558                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5559       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5560       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5561                              SDValue(ResNode.getNode(), 1));
5562     }
5563
5564     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5565   }
5566   return SDValue();
5567 }
5568
5569 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5570 /// to generate a splat value for the following cases:
5571 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5572 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5573 /// a scalar load, or a constant.
5574 /// The VBROADCAST node is returned when a pattern is found,
5575 /// or SDValue() otherwise.
5576 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5577                                     SelectionDAG &DAG) {
5578   if (!Subtarget->hasFp256())
5579     return SDValue();
5580
5581   MVT VT = Op.getSimpleValueType();
5582   SDLoc dl(Op);
5583
5584   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5585          "Unsupported vector type for broadcast.");
5586
5587   SDValue Ld;
5588   bool ConstSplatVal;
5589
5590   switch (Op.getOpcode()) {
5591     default:
5592       // Unknown pattern found.
5593       return SDValue();
5594
5595     case ISD::BUILD_VECTOR: {
5596       // The BUILD_VECTOR node must be a splat.
5597       if (!isSplatVector(Op.getNode()))
5598         return SDValue();
5599
5600       Ld = Op.getOperand(0);
5601       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5602                      Ld.getOpcode() == ISD::ConstantFP);
5603
5604       // The suspected load node has several users. Make sure that all
5605       // of its users are from the BUILD_VECTOR node.
5606       // Constants may have multiple users.
5607       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5608         return SDValue();
5609       break;
5610     }
5611
5612     case ISD::VECTOR_SHUFFLE: {
5613       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614
5615       // Shuffles must have a splat mask where the first element is
5616       // broadcasted.
5617       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5618         return SDValue();
5619
5620       SDValue Sc = Op.getOperand(0);
5621       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5622           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5623
5624         if (!Subtarget->hasInt256())
5625           return SDValue();
5626
5627         // Use the register form of the broadcast instruction available on AVX2.
5628         if (VT.getSizeInBits() >= 256)
5629           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5630         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5631       }
5632
5633       Ld = Sc.getOperand(0);
5634       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5635                        Ld.getOpcode() == ISD::ConstantFP);
5636
5637       // The scalar_to_vector node and the suspected
5638       // load node must have exactly one user.
5639       // Constants may have multiple users.
5640
5641       // AVX-512 has register version of the broadcast
5642       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5643         Ld.getValueType().getSizeInBits() >= 32;
5644       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5645           !hasRegVer))
5646         return SDValue();
5647       break;
5648     }
5649   }
5650
5651   bool IsGE256 = (VT.getSizeInBits() >= 256);
5652
5653   // Handle the broadcasting a single constant scalar from the constant pool
5654   // into a vector. On Sandybridge it is still better to load a constant vector
5655   // from the constant pool and not to broadcast it from a scalar.
5656   if (ConstSplatVal && Subtarget->hasInt256()) {
5657     EVT CVT = Ld.getValueType();
5658     assert(!CVT.isVector() && "Must not broadcast a vector type");
5659     unsigned ScalarSize = CVT.getSizeInBits();
5660
5661     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5662       const Constant *C = 0;
5663       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5664         C = CI->getConstantIntValue();
5665       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5666         C = CF->getConstantFPValue();
5667
5668       assert(C && "Invalid constant type");
5669
5670       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5671       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5672       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5673       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5674                        MachinePointerInfo::getConstantPool(),
5675                        false, false, false, Alignment);
5676
5677       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5678     }
5679   }
5680
5681   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5682   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5683
5684   // Handle AVX2 in-register broadcasts.
5685   if (!IsLoad && Subtarget->hasInt256() &&
5686       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5687     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5688
5689   // The scalar source must be a normal load.
5690   if (!IsLoad)
5691     return SDValue();
5692
5693   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5694     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5695
5696   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697   // double since there is no vbroadcastsd xmm
5698   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5701   }
5702
5703   // Unsupported broadcast.
5704   return SDValue();
5705 }
5706
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5709 ///
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5711 /// index.
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5713                                          SDValue ExtIdx) {
5714   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5716     return Idx;
5717
5718   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5719   // lowered this:
5720   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5721   // to:
5722   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5723   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5724   //                           undef)
5725   //                       Constant<0>)
5726   // In this case the vector is the extract_subvector expression and the index
5727   // is 2, as specified by the shuffle.
5728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729   SDValue ShuffleVec = SVOp->getOperand(0);
5730   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731   assert(ShuffleVecVT.getVectorElementType() ==
5732          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5733
5734   int ShuffleIdx = SVOp->getMaskElt(Idx);
5735   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736     ExtractedFromVec = ShuffleVec;
5737     return ShuffleIdx;
5738   }
5739   return Idx;
5740 }
5741
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743   MVT VT = Op.getSimpleValueType();
5744
5745   // Skip if insert_vec_elt is not supported.
5746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5748     return SDValue();
5749
5750   SDLoc DL(Op);
5751   unsigned NumElems = Op.getNumOperands();
5752
5753   SDValue VecIn1;
5754   SDValue VecIn2;
5755   SmallVector<unsigned, 4> InsertIndices;
5756   SmallVector<int, 8> Mask(NumElems, -1);
5757
5758   for (unsigned i = 0; i != NumElems; ++i) {
5759     unsigned Opc = Op.getOperand(i).getOpcode();
5760
5761     if (Opc == ISD::UNDEF)
5762       continue;
5763
5764     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765       // Quit if more than 1 elements need inserting.
5766       if (InsertIndices.size() > 1)
5767         return SDValue();
5768
5769       InsertIndices.push_back(i);
5770       continue;
5771     }
5772
5773     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775     // Quit if non-constant index.
5776     if (!isa<ConstantSDNode>(ExtIdx))
5777       return SDValue();
5778     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5779
5780     // Quit if extracted from vector of different type.
5781     if (ExtractedFromVec.getValueType() != VT)
5782       return SDValue();
5783
5784     if (VecIn1.getNode() == 0)
5785       VecIn1 = ExtractedFromVec;
5786     else if (VecIn1 != ExtractedFromVec) {
5787       if (VecIn2.getNode() == 0)
5788         VecIn2 = ExtractedFromVec;
5789       else if (VecIn2 != ExtractedFromVec)
5790         // Quit if more than 2 vectors to shuffle
5791         return SDValue();
5792     }
5793
5794     if (ExtractedFromVec == VecIn1)
5795       Mask[i] = Idx;
5796     else if (ExtractedFromVec == VecIn2)
5797       Mask[i] = Idx + NumElems;
5798   }
5799
5800   if (VecIn1.getNode() == 0)
5801     return SDValue();
5802
5803   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806     unsigned Idx = InsertIndices[i];
5807     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808                      DAG.getIntPtrConstant(Idx));
5809   }
5810
5811   return NV;
5812 }
5813
5814 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5815 SDValue
5816 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5817
5818   MVT VT = Op.getSimpleValueType();
5819   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5820          "Unexpected type in LowerBUILD_VECTORvXi1!");
5821
5822   SDLoc dl(Op);
5823   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5824     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5825     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5826                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5827     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5828                        Ops, VT.getVectorNumElements());
5829   }
5830
5831   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5832     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5833     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5834                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5835     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5836                        Ops, VT.getVectorNumElements());
5837   }
5838
5839   bool AllContants = true;
5840   uint64_t Immediate = 0;
5841   int NonConstIdx = -1;
5842   bool IsSplat = true;
5843   unsigned NumNonConsts = 0;
5844   unsigned NumConsts = 0;
5845   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5846     SDValue In = Op.getOperand(idx);
5847     if (In.getOpcode() == ISD::UNDEF)
5848       continue;
5849     if (!isa<ConstantSDNode>(In)) {
5850       AllContants = false;
5851       NonConstIdx = idx;
5852       NumNonConsts++;
5853     }
5854     else {
5855       NumConsts++;
5856       if (cast<ConstantSDNode>(In)->getZExtValue())
5857       Immediate |= (1ULL << idx);
5858     }
5859     if (In != Op.getOperand(0))
5860       IsSplat = false;
5861   }
5862
5863   if (AllContants) {
5864     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5865       DAG.getConstant(Immediate, MVT::i16));
5866     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5867                        DAG.getIntPtrConstant(0));
5868   }
5869
5870   if (NumNonConsts == 1 && NonConstIdx != 0) {
5871     SDValue DstVec;
5872     if (NumConsts) {
5873       SDValue VecAsImm = DAG.getConstant(Immediate,
5874                                          MVT::getIntegerVT(VT.getSizeInBits()));
5875       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5876     }
5877     else 
5878       DstVec = DAG.getUNDEF(VT);
5879     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5880                        Op.getOperand(NonConstIdx),
5881                        DAG.getIntPtrConstant(NonConstIdx));
5882   }
5883   if (!IsSplat && (NonConstIdx != 0))
5884     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5885   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5886   SDValue Select;
5887   if (IsSplat)
5888     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5889                           DAG.getConstant(-1, SelectVT),
5890                           DAG.getConstant(0, SelectVT));
5891   else
5892     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5893                          DAG.getConstant((Immediate | 1), SelectVT),
5894                          DAG.getConstant(Immediate, SelectVT));
5895   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5896 }
5897
5898 SDValue
5899 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5900   SDLoc dl(Op);
5901
5902   MVT VT = Op.getSimpleValueType();
5903   MVT ExtVT = VT.getVectorElementType();
5904   unsigned NumElems = Op.getNumOperands();
5905
5906   // Generate vectors for predicate vectors.
5907   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5908     return LowerBUILD_VECTORvXi1(Op, DAG);
5909
5910   // Vectors containing all zeros can be matched by pxor and xorps later
5911   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5912     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5913     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5914     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5915       return Op;
5916
5917     return getZeroVector(VT, Subtarget, DAG, dl);
5918   }
5919
5920   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5921   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5922   // vpcmpeqd on 256-bit vectors.
5923   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5924     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5925       return Op;
5926
5927     if (!VT.is512BitVector())
5928       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5929   }
5930
5931   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5932   if (Broadcast.getNode())
5933     return Broadcast;
5934
5935   unsigned EVTBits = ExtVT.getSizeInBits();
5936
5937   unsigned NumZero  = 0;
5938   unsigned NumNonZero = 0;
5939   unsigned NonZeros = 0;
5940   bool IsAllConstants = true;
5941   SmallSet<SDValue, 8> Values;
5942   for (unsigned i = 0; i < NumElems; ++i) {
5943     SDValue Elt = Op.getOperand(i);
5944     if (Elt.getOpcode() == ISD::UNDEF)
5945       continue;
5946     Values.insert(Elt);
5947     if (Elt.getOpcode() != ISD::Constant &&
5948         Elt.getOpcode() != ISD::ConstantFP)
5949       IsAllConstants = false;
5950     if (X86::isZeroNode(Elt))
5951       NumZero++;
5952     else {
5953       NonZeros |= (1 << i);
5954       NumNonZero++;
5955     }
5956   }
5957
5958   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5959   if (NumNonZero == 0)
5960     return DAG.getUNDEF(VT);
5961
5962   // Special case for single non-zero, non-undef, element.
5963   if (NumNonZero == 1) {
5964     unsigned Idx = countTrailingZeros(NonZeros);
5965     SDValue Item = Op.getOperand(Idx);
5966
5967     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5968     // the value are obviously zero, truncate the value to i32 and do the
5969     // insertion that way.  Only do this if the value is non-constant or if the
5970     // value is a constant being inserted into element 0.  It is cheaper to do
5971     // a constant pool load than it is to do a movd + shuffle.
5972     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5973         (!IsAllConstants || Idx == 0)) {
5974       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5975         // Handle SSE only.
5976         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5977         EVT VecVT = MVT::v4i32;
5978         unsigned VecElts = 4;
5979
5980         // Truncate the value (which may itself be a constant) to i32, and
5981         // convert it to a vector with movd (S2V+shuffle to zero extend).
5982         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5983         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5984         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5985
5986         // Now we have our 32-bit value zero extended in the low element of
5987         // a vector.  If Idx != 0, swizzle it into place.
5988         if (Idx != 0) {
5989           SmallVector<int, 4> Mask;
5990           Mask.push_back(Idx);
5991           for (unsigned i = 1; i != VecElts; ++i)
5992             Mask.push_back(i);
5993           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5994                                       &Mask[0]);
5995         }
5996         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5997       }
5998     }
5999
6000     // If we have a constant or non-constant insertion into the low element of
6001     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6002     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6003     // depending on what the source datatype is.
6004     if (Idx == 0) {
6005       if (NumZero == 0)
6006         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6007
6008       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6009           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6010         if (VT.is256BitVector() || VT.is512BitVector()) {
6011           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6012           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6013                              Item, DAG.getIntPtrConstant(0));
6014         }
6015         assert(VT.is128BitVector() && "Expected an SSE value type!");
6016         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6017         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6018         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6019       }
6020
6021       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6022         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6023         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024         if (VT.is256BitVector()) {
6025           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6026           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6027         } else {
6028           assert(VT.is128BitVector() && "Expected an SSE value type!");
6029           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6030         }
6031         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6032       }
6033     }
6034
6035     // Is it a vector logical left shift?
6036     if (NumElems == 2 && Idx == 1 &&
6037         X86::isZeroNode(Op.getOperand(0)) &&
6038         !X86::isZeroNode(Op.getOperand(1))) {
6039       unsigned NumBits = VT.getSizeInBits();
6040       return getVShift(true, VT,
6041                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6042                                    VT, Op.getOperand(1)),
6043                        NumBits/2, DAG, *this, dl);
6044     }
6045
6046     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6047       return SDValue();
6048
6049     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6050     // is a non-constant being inserted into an element other than the low one,
6051     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6052     // movd/movss) to move this into the low element, then shuffle it into
6053     // place.
6054     if (EVTBits == 32) {
6055       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6056
6057       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6058       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6059       SmallVector<int, 8> MaskVec;
6060       for (unsigned i = 0; i != NumElems; ++i)
6061         MaskVec.push_back(i == Idx ? 0 : 1);
6062       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6063     }
6064   }
6065
6066   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6067   if (Values.size() == 1) {
6068     if (EVTBits == 32) {
6069       // Instead of a shuffle like this:
6070       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6071       // Check if it's possible to issue this instead.
6072       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6073       unsigned Idx = countTrailingZeros(NonZeros);
6074       SDValue Item = Op.getOperand(Idx);
6075       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6076         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6077     }
6078     return SDValue();
6079   }
6080
6081   // A vector full of immediates; various special cases are already
6082   // handled, so this is best done with a single constant-pool load.
6083   if (IsAllConstants)
6084     return SDValue();
6085
6086   // For AVX-length vectors, build the individual 128-bit pieces and use
6087   // shuffles to put them in place.
6088   if (VT.is256BitVector() || VT.is512BitVector()) {
6089     SmallVector<SDValue, 64> V;
6090     for (unsigned i = 0; i != NumElems; ++i)
6091       V.push_back(Op.getOperand(i));
6092
6093     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6094
6095     // Build both the lower and upper subvector.
6096     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6097     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6098                                 NumElems/2);
6099
6100     // Recreate the wider vector with the lower and upper part.
6101     if (VT.is256BitVector())
6102       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6103     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6104   }
6105
6106   // Let legalizer expand 2-wide build_vectors.
6107   if (EVTBits == 64) {
6108     if (NumNonZero == 1) {
6109       // One half is zero or undef.
6110       unsigned Idx = countTrailingZeros(NonZeros);
6111       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6112                                  Op.getOperand(Idx));
6113       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6114     }
6115     return SDValue();
6116   }
6117
6118   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6119   if (EVTBits == 8 && NumElems == 16) {
6120     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6121                                         Subtarget, *this);
6122     if (V.getNode()) return V;
6123   }
6124
6125   if (EVTBits == 16 && NumElems == 8) {
6126     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                       Subtarget, *this);
6128     if (V.getNode()) return V;
6129   }
6130
6131   // If element VT is == 32 bits, turn it into a number of shuffles.
6132   SmallVector<SDValue, 8> V(NumElems);
6133   if (NumElems == 4 && NumZero > 0) {
6134     for (unsigned i = 0; i < 4; ++i) {
6135       bool isZero = !(NonZeros & (1 << i));
6136       if (isZero)
6137         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6138       else
6139         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6140     }
6141
6142     for (unsigned i = 0; i < 2; ++i) {
6143       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6144         default: break;
6145         case 0:
6146           V[i] = V[i*2];  // Must be a zero vector.
6147           break;
6148         case 1:
6149           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6150           break;
6151         case 2:
6152           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6153           break;
6154         case 3:
6155           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6156           break;
6157       }
6158     }
6159
6160     bool Reverse1 = (NonZeros & 0x3) == 2;
6161     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6162     int MaskVec[] = {
6163       Reverse1 ? 1 : 0,
6164       Reverse1 ? 0 : 1,
6165       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6166       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6167     };
6168     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6169   }
6170
6171   if (Values.size() > 1 && VT.is128BitVector()) {
6172     // Check for a build vector of consecutive loads.
6173     for (unsigned i = 0; i < NumElems; ++i)
6174       V[i] = Op.getOperand(i);
6175
6176     // Check for elements which are consecutive loads.
6177     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6178     if (LD.getNode())
6179       return LD;
6180
6181     // Check for a build vector from mostly shuffle plus few inserting.
6182     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6183     if (Sh.getNode())
6184       return Sh;
6185
6186     // For SSE 4.1, use insertps to put the high elements into the low element.
6187     if (getSubtarget()->hasSSE41()) {
6188       SDValue Result;
6189       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6190         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6191       else
6192         Result = DAG.getUNDEF(VT);
6193
6194       for (unsigned i = 1; i < NumElems; ++i) {
6195         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6196         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6197                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6198       }
6199       return Result;
6200     }
6201
6202     // Otherwise, expand into a number of unpckl*, start by extending each of
6203     // our (non-undef) elements to the full vector width with the element in the
6204     // bottom slot of the vector (which generates no code for SSE).
6205     for (unsigned i = 0; i < NumElems; ++i) {
6206       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6207         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6208       else
6209         V[i] = DAG.getUNDEF(VT);
6210     }
6211
6212     // Next, we iteratively mix elements, e.g. for v4f32:
6213     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6214     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6215     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6216     unsigned EltStride = NumElems >> 1;
6217     while (EltStride != 0) {
6218       for (unsigned i = 0; i < EltStride; ++i) {
6219         // If V[i+EltStride] is undef and this is the first round of mixing,
6220         // then it is safe to just drop this shuffle: V[i] is already in the
6221         // right place, the one element (since it's the first round) being
6222         // inserted as undef can be dropped.  This isn't safe for successive
6223         // rounds because they will permute elements within both vectors.
6224         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6225             EltStride == NumElems/2)
6226           continue;
6227
6228         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6229       }
6230       EltStride >>= 1;
6231     }
6232     return V[0];
6233   }
6234   return SDValue();
6235 }
6236
6237 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6238 // to create 256-bit vectors from two other 128-bit ones.
6239 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6240   SDLoc dl(Op);
6241   MVT ResVT = Op.getSimpleValueType();
6242
6243   assert((ResVT.is256BitVector() ||
6244           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6245
6246   SDValue V1 = Op.getOperand(0);
6247   SDValue V2 = Op.getOperand(1);
6248   unsigned NumElems = ResVT.getVectorNumElements();
6249   if(ResVT.is256BitVector())
6250     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6251
6252   if (Op.getNumOperands() == 4) {
6253     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6254                                 ResVT.getVectorNumElements()/2);
6255     SDValue V3 = Op.getOperand(2);
6256     SDValue V4 = Op.getOperand(3);
6257     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6258       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6259   }
6260   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6261 }
6262
6263 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6264   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6265   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6266          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6267           Op.getNumOperands() == 4)));
6268
6269   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6270   // from two other 128-bit ones.
6271
6272   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6273   return LowerAVXCONCAT_VECTORS(Op, DAG);
6274 }
6275
6276 // Try to lower a shuffle node into a simple blend instruction.
6277 static SDValue
6278 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6279                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6280   SDValue V1 = SVOp->getOperand(0);
6281   SDValue V2 = SVOp->getOperand(1);
6282   SDLoc dl(SVOp);
6283   MVT VT = SVOp->getSimpleValueType(0);
6284   MVT EltVT = VT.getVectorElementType();
6285   unsigned NumElems = VT.getVectorNumElements();
6286
6287   // There is no blend with immediate in AVX-512.
6288   if (VT.is512BitVector())
6289     return SDValue();
6290
6291   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6292     return SDValue();
6293   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6294     return SDValue();
6295
6296   // Check the mask for BLEND and build the value.
6297   unsigned MaskValue = 0;
6298   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6299   unsigned NumLanes = (NumElems-1)/8 + 1;
6300   unsigned NumElemsInLane = NumElems / NumLanes;
6301
6302   // Blend for v16i16 should be symetric for the both lanes.
6303   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6304
6305     int SndLaneEltIdx = (NumLanes == 2) ?
6306       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6307     int EltIdx = SVOp->getMaskElt(i);
6308
6309     if ((EltIdx < 0 || EltIdx == (int)i) &&
6310         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6311       continue;
6312
6313     if (((unsigned)EltIdx == (i + NumElems)) &&
6314         (SndLaneEltIdx < 0 ||
6315          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6316       MaskValue |= (1<<i);
6317     else
6318       return SDValue();
6319   }
6320
6321   // Convert i32 vectors to floating point if it is not AVX2.
6322   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6323   MVT BlendVT = VT;
6324   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6325     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6326                                NumElems);
6327     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6328     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6329   }
6330
6331   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6332                             DAG.getConstant(MaskValue, MVT::i32));
6333   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6334 }
6335
6336 /// In vector type \p VT, return true if the element at index \p InputIdx
6337 /// falls on a different 128-bit lane than \p OutputIdx.
6338 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6339                                      unsigned OutputIdx) {
6340   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6341   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6342 }
6343
6344 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6345 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6346 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6347 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6348 /// zero.
6349 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6350                          SelectionDAG &DAG) {
6351   MVT VT = V1.getSimpleValueType();
6352   assert(VT.is128BitVector() || VT.is256BitVector());
6353
6354   MVT EltVT = VT.getVectorElementType();
6355   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6356   unsigned NumElts = VT.getVectorNumElements();
6357
6358   SmallVector<SDValue, 32> PshufbMask;
6359   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6360     int InputIdx = MaskVals[OutputIdx];
6361     unsigned InputByteIdx;
6362
6363     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6364       InputByteIdx = 0x80;
6365     else {
6366       // Cross lane is not allowed.
6367       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6368         return SDValue();
6369       InputByteIdx = InputIdx * EltSizeInBytes;
6370       // Index is an byte offset within the 128-bit lane.
6371       InputByteIdx &= 0xf;
6372     }
6373
6374     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6375       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6376       if (InputByteIdx != 0x80)
6377         ++InputByteIdx;
6378     }
6379   }
6380
6381   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6382   if (ShufVT != VT)
6383     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6384   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6385                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6386                                  PshufbMask.data(), PshufbMask.size()));
6387 }
6388
6389 // v8i16 shuffles - Prefer shuffles in the following order:
6390 // 1. [all]   pshuflw, pshufhw, optional move
6391 // 2. [ssse3] 1 x pshufb
6392 // 3. [ssse3] 2 x pshufb + 1 x por
6393 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6394 static SDValue
6395 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6396                          SelectionDAG &DAG) {
6397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6398   SDValue V1 = SVOp->getOperand(0);
6399   SDValue V2 = SVOp->getOperand(1);
6400   SDLoc dl(SVOp);
6401   SmallVector<int, 8> MaskVals;
6402
6403   // Determine if more than 1 of the words in each of the low and high quadwords
6404   // of the result come from the same quadword of one of the two inputs.  Undef
6405   // mask values count as coming from any quadword, for better codegen.
6406   //
6407   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6408   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6409   unsigned LoQuad[] = { 0, 0, 0, 0 };
6410   unsigned HiQuad[] = { 0, 0, 0, 0 };
6411   // Indices of quads used.
6412   std::bitset<4> InputQuads;
6413   for (unsigned i = 0; i < 8; ++i) {
6414     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6415     int EltIdx = SVOp->getMaskElt(i);
6416     MaskVals.push_back(EltIdx);
6417     if (EltIdx < 0) {
6418       ++Quad[0];
6419       ++Quad[1];
6420       ++Quad[2];
6421       ++Quad[3];
6422       continue;
6423     }
6424     ++Quad[EltIdx / 4];
6425     InputQuads.set(EltIdx / 4);
6426   }
6427
6428   int BestLoQuad = -1;
6429   unsigned MaxQuad = 1;
6430   for (unsigned i = 0; i < 4; ++i) {
6431     if (LoQuad[i] > MaxQuad) {
6432       BestLoQuad = i;
6433       MaxQuad = LoQuad[i];
6434     }
6435   }
6436
6437   int BestHiQuad = -1;
6438   MaxQuad = 1;
6439   for (unsigned i = 0; i < 4; ++i) {
6440     if (HiQuad[i] > MaxQuad) {
6441       BestHiQuad = i;
6442       MaxQuad = HiQuad[i];
6443     }
6444   }
6445
6446   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6447   // of the two input vectors, shuffle them into one input vector so only a
6448   // single pshufb instruction is necessary. If there are more than 2 input
6449   // quads, disable the next transformation since it does not help SSSE3.
6450   bool V1Used = InputQuads[0] || InputQuads[1];
6451   bool V2Used = InputQuads[2] || InputQuads[3];
6452   if (Subtarget->hasSSSE3()) {
6453     if (InputQuads.count() == 2 && V1Used && V2Used) {
6454       BestLoQuad = InputQuads[0] ? 0 : 1;
6455       BestHiQuad = InputQuads[2] ? 2 : 3;
6456     }
6457     if (InputQuads.count() > 2) {
6458       BestLoQuad = -1;
6459       BestHiQuad = -1;
6460     }
6461   }
6462
6463   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6464   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6465   // words from all 4 input quadwords.
6466   SDValue NewV;
6467   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6468     int MaskV[] = {
6469       BestLoQuad < 0 ? 0 : BestLoQuad,
6470       BestHiQuad < 0 ? 1 : BestHiQuad
6471     };
6472     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6473                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6474                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6475     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6476
6477     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6478     // source words for the shuffle, to aid later transformations.
6479     bool AllWordsInNewV = true;
6480     bool InOrder[2] = { true, true };
6481     for (unsigned i = 0; i != 8; ++i) {
6482       int idx = MaskVals[i];
6483       if (idx != (int)i)
6484         InOrder[i/4] = false;
6485       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6486         continue;
6487       AllWordsInNewV = false;
6488       break;
6489     }
6490
6491     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6492     if (AllWordsInNewV) {
6493       for (int i = 0; i != 8; ++i) {
6494         int idx = MaskVals[i];
6495         if (idx < 0)
6496           continue;
6497         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6498         if ((idx != i) && idx < 4)
6499           pshufhw = false;
6500         if ((idx != i) && idx > 3)
6501           pshuflw = false;
6502       }
6503       V1 = NewV;
6504       V2Used = false;
6505       BestLoQuad = 0;
6506       BestHiQuad = 1;
6507     }
6508
6509     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6510     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6511     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6512       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6513       unsigned TargetMask = 0;
6514       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6515                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6516       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6517       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6518                              getShufflePSHUFLWImmediate(SVOp);
6519       V1 = NewV.getOperand(0);
6520       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6521     }
6522   }
6523
6524   // Promote splats to a larger type which usually leads to more efficient code.
6525   // FIXME: Is this true if pshufb is available?
6526   if (SVOp->isSplat())
6527     return PromoteSplat(SVOp, DAG);
6528
6529   // If we have SSSE3, and all words of the result are from 1 input vector,
6530   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6531   // is present, fall back to case 4.
6532   if (Subtarget->hasSSSE3()) {
6533     SmallVector<SDValue,16> pshufbMask;
6534
6535     // If we have elements from both input vectors, set the high bit of the
6536     // shuffle mask element to zero out elements that come from V2 in the V1
6537     // mask, and elements that come from V1 in the V2 mask, so that the two
6538     // results can be OR'd together.
6539     bool TwoInputs = V1Used && V2Used;
6540     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6541     if (!TwoInputs)
6542       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6543
6544     // Calculate the shuffle mask for the second input, shuffle it, and
6545     // OR it with the first shuffled input.
6546     CommuteVectorShuffleMask(MaskVals, 8);
6547     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6548     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6549     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6550   }
6551
6552   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6553   // and update MaskVals with new element order.
6554   std::bitset<8> InOrder;
6555   if (BestLoQuad >= 0) {
6556     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6557     for (int i = 0; i != 4; ++i) {
6558       int idx = MaskVals[i];
6559       if (idx < 0) {
6560         InOrder.set(i);
6561       } else if ((idx / 4) == BestLoQuad) {
6562         MaskV[i] = idx & 3;
6563         InOrder.set(i);
6564       }
6565     }
6566     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6567                                 &MaskV[0]);
6568
6569     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6570       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6571       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6572                                   NewV.getOperand(0),
6573                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6574     }
6575   }
6576
6577   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6578   // and update MaskVals with the new element order.
6579   if (BestHiQuad >= 0) {
6580     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6581     for (unsigned i = 4; i != 8; ++i) {
6582       int idx = MaskVals[i];
6583       if (idx < 0) {
6584         InOrder.set(i);
6585       } else if ((idx / 4) == BestHiQuad) {
6586         MaskV[i] = (idx & 3) + 4;
6587         InOrder.set(i);
6588       }
6589     }
6590     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6591                                 &MaskV[0]);
6592
6593     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6594       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6595       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6596                                   NewV.getOperand(0),
6597                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6598     }
6599   }
6600
6601   // In case BestHi & BestLo were both -1, which means each quadword has a word
6602   // from each of the four input quadwords, calculate the InOrder bitvector now
6603   // before falling through to the insert/extract cleanup.
6604   if (BestLoQuad == -1 && BestHiQuad == -1) {
6605     NewV = V1;
6606     for (int i = 0; i != 8; ++i)
6607       if (MaskVals[i] < 0 || MaskVals[i] == i)
6608         InOrder.set(i);
6609   }
6610
6611   // The other elements are put in the right place using pextrw and pinsrw.
6612   for (unsigned i = 0; i != 8; ++i) {
6613     if (InOrder[i])
6614       continue;
6615     int EltIdx = MaskVals[i];
6616     if (EltIdx < 0)
6617       continue;
6618     SDValue ExtOp = (EltIdx < 8) ?
6619       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6620                   DAG.getIntPtrConstant(EltIdx)) :
6621       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6622                   DAG.getIntPtrConstant(EltIdx - 8));
6623     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6624                        DAG.getIntPtrConstant(i));
6625   }
6626   return NewV;
6627 }
6628
6629 /// \brief v16i16 shuffles
6630 ///
6631 /// FIXME: We only support generation of a single pshufb currently.  We can
6632 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6633 /// well (e.g 2 x pshufb + 1 x por).
6634 static SDValue
6635 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6636   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6637   SDValue V1 = SVOp->getOperand(0);
6638   SDValue V2 = SVOp->getOperand(1);
6639   SDLoc dl(SVOp);
6640
6641   if (V2.getOpcode() != ISD::UNDEF)
6642     return SDValue();
6643
6644   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6645   return getPSHUFB(MaskVals, V1, dl, DAG);
6646 }
6647
6648 // v16i8 shuffles - Prefer shuffles in the following order:
6649 // 1. [ssse3] 1 x pshufb
6650 // 2. [ssse3] 2 x pshufb + 1 x por
6651 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6652 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6653                                         const X86Subtarget* Subtarget,
6654                                         SelectionDAG &DAG) {
6655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6656   SDValue V1 = SVOp->getOperand(0);
6657   SDValue V2 = SVOp->getOperand(1);
6658   SDLoc dl(SVOp);
6659   ArrayRef<int> MaskVals = SVOp->getMask();
6660
6661   // Promote splats to a larger type which usually leads to more efficient code.
6662   // FIXME: Is this true if pshufb is available?
6663   if (SVOp->isSplat())
6664     return PromoteSplat(SVOp, DAG);
6665
6666   // If we have SSSE3, case 1 is generated when all result bytes come from
6667   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6668   // present, fall back to case 3.
6669
6670   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6671   if (Subtarget->hasSSSE3()) {
6672     SmallVector<SDValue,16> pshufbMask;
6673
6674     // If all result elements are from one input vector, then only translate
6675     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6676     //
6677     // Otherwise, we have elements from both input vectors, and must zero out
6678     // elements that come from V2 in the first mask, and V1 in the second mask
6679     // so that we can OR them together.
6680     for (unsigned i = 0; i != 16; ++i) {
6681       int EltIdx = MaskVals[i];
6682       if (EltIdx < 0 || EltIdx >= 16)
6683         EltIdx = 0x80;
6684       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6685     }
6686     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6687                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6688                                  MVT::v16i8, &pshufbMask[0], 16));
6689
6690     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6691     // the 2nd operand if it's undefined or zero.
6692     if (V2.getOpcode() == ISD::UNDEF ||
6693         ISD::isBuildVectorAllZeros(V2.getNode()))
6694       return V1;
6695
6696     // Calculate the shuffle mask for the second input, shuffle it, and
6697     // OR it with the first shuffled input.
6698     pshufbMask.clear();
6699     for (unsigned i = 0; i != 16; ++i) {
6700       int EltIdx = MaskVals[i];
6701       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6702       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6703     }
6704     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6705                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6706                                  MVT::v16i8, &pshufbMask[0], 16));
6707     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6708   }
6709
6710   // No SSSE3 - Calculate in place words and then fix all out of place words
6711   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6712   // the 16 different words that comprise the two doublequadword input vectors.
6713   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6714   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6715   SDValue NewV = V1;
6716   for (int i = 0; i != 8; ++i) {
6717     int Elt0 = MaskVals[i*2];
6718     int Elt1 = MaskVals[i*2+1];
6719
6720     // This word of the result is all undef, skip it.
6721     if (Elt0 < 0 && Elt1 < 0)
6722       continue;
6723
6724     // This word of the result is already in the correct place, skip it.
6725     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6726       continue;
6727
6728     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6729     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6730     SDValue InsElt;
6731
6732     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6733     // using a single extract together, load it and store it.
6734     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6735       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6736                            DAG.getIntPtrConstant(Elt1 / 2));
6737       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6738                         DAG.getIntPtrConstant(i));
6739       continue;
6740     }
6741
6742     // If Elt1 is defined, extract it from the appropriate source.  If the
6743     // source byte is not also odd, shift the extracted word left 8 bits
6744     // otherwise clear the bottom 8 bits if we need to do an or.
6745     if (Elt1 >= 0) {
6746       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6747                            DAG.getIntPtrConstant(Elt1 / 2));
6748       if ((Elt1 & 1) == 0)
6749         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6750                              DAG.getConstant(8,
6751                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6752       else if (Elt0 >= 0)
6753         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6754                              DAG.getConstant(0xFF00, MVT::i16));
6755     }
6756     // If Elt0 is defined, extract it from the appropriate source.  If the
6757     // source byte is not also even, shift the extracted word right 8 bits. If
6758     // Elt1 was also defined, OR the extracted values together before
6759     // inserting them in the result.
6760     if (Elt0 >= 0) {
6761       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6762                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6763       if ((Elt0 & 1) != 0)
6764         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6765                               DAG.getConstant(8,
6766                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6767       else if (Elt1 >= 0)
6768         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6769                              DAG.getConstant(0x00FF, MVT::i16));
6770       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6771                          : InsElt0;
6772     }
6773     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6774                        DAG.getIntPtrConstant(i));
6775   }
6776   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6777 }
6778
6779 // v32i8 shuffles - Translate to VPSHUFB if possible.
6780 static
6781 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6782                                  const X86Subtarget *Subtarget,
6783                                  SelectionDAG &DAG) {
6784   MVT VT = SVOp->getSimpleValueType(0);
6785   SDValue V1 = SVOp->getOperand(0);
6786   SDValue V2 = SVOp->getOperand(1);
6787   SDLoc dl(SVOp);
6788   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6789
6790   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6791   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6792   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6793
6794   // VPSHUFB may be generated if
6795   // (1) one of input vector is undefined or zeroinitializer.
6796   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6797   // And (2) the mask indexes don't cross the 128-bit lane.
6798   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6799       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6800     return SDValue();
6801
6802   if (V1IsAllZero && !V2IsAllZero) {
6803     CommuteVectorShuffleMask(MaskVals, 32);
6804     V1 = V2;
6805   }
6806   return getPSHUFB(MaskVals, V1, dl, DAG);
6807 }
6808
6809 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6810 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6811 /// done when every pair / quad of shuffle mask elements point to elements in
6812 /// the right sequence. e.g.
6813 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6814 static
6815 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6816                                  SelectionDAG &DAG) {
6817   MVT VT = SVOp->getSimpleValueType(0);
6818   SDLoc dl(SVOp);
6819   unsigned NumElems = VT.getVectorNumElements();
6820   MVT NewVT;
6821   unsigned Scale;
6822   switch (VT.SimpleTy) {
6823   default: llvm_unreachable("Unexpected!");
6824   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6825   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6826   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6827   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6828   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6829   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6830   }
6831
6832   SmallVector<int, 8> MaskVec;
6833   for (unsigned i = 0; i != NumElems; i += Scale) {
6834     int StartIdx = -1;
6835     for (unsigned j = 0; j != Scale; ++j) {
6836       int EltIdx = SVOp->getMaskElt(i+j);
6837       if (EltIdx < 0)
6838         continue;
6839       if (StartIdx < 0)
6840         StartIdx = (EltIdx / Scale);
6841       if (EltIdx != (int)(StartIdx*Scale + j))
6842         return SDValue();
6843     }
6844     MaskVec.push_back(StartIdx);
6845   }
6846
6847   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6848   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6849   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6850 }
6851
6852 /// getVZextMovL - Return a zero-extending vector move low node.
6853 ///
6854 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6855                             SDValue SrcOp, SelectionDAG &DAG,
6856                             const X86Subtarget *Subtarget, SDLoc dl) {
6857   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6858     LoadSDNode *LD = NULL;
6859     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6860       LD = dyn_cast<LoadSDNode>(SrcOp);
6861     if (!LD) {
6862       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6863       // instead.
6864       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6865       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6866           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6867           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6868           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6869         // PR2108
6870         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6871         return DAG.getNode(ISD::BITCAST, dl, VT,
6872                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6873                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6874                                                    OpVT,
6875                                                    SrcOp.getOperand(0)
6876                                                           .getOperand(0))));
6877       }
6878     }
6879   }
6880
6881   return DAG.getNode(ISD::BITCAST, dl, VT,
6882                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6883                                  DAG.getNode(ISD::BITCAST, dl,
6884                                              OpVT, SrcOp)));
6885 }
6886
6887 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6888 /// which could not be matched by any known target speficic shuffle
6889 static SDValue
6890 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6891
6892   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6893   if (NewOp.getNode())
6894     return NewOp;
6895
6896   MVT VT = SVOp->getSimpleValueType(0);
6897
6898   unsigned NumElems = VT.getVectorNumElements();
6899   unsigned NumLaneElems = NumElems / 2;
6900
6901   SDLoc dl(SVOp);
6902   MVT EltVT = VT.getVectorElementType();
6903   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6904   SDValue Output[2];
6905
6906   SmallVector<int, 16> Mask;
6907   for (unsigned l = 0; l < 2; ++l) {
6908     // Build a shuffle mask for the output, discovering on the fly which
6909     // input vectors to use as shuffle operands (recorded in InputUsed).
6910     // If building a suitable shuffle vector proves too hard, then bail
6911     // out with UseBuildVector set.
6912     bool UseBuildVector = false;
6913     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6914     unsigned LaneStart = l * NumLaneElems;
6915     for (unsigned i = 0; i != NumLaneElems; ++i) {
6916       // The mask element.  This indexes into the input.
6917       int Idx = SVOp->getMaskElt(i+LaneStart);
6918       if (Idx < 0) {
6919         // the mask element does not index into any input vector.
6920         Mask.push_back(-1);
6921         continue;
6922       }
6923
6924       // The input vector this mask element indexes into.
6925       int Input = Idx / NumLaneElems;
6926
6927       // Turn the index into an offset from the start of the input vector.
6928       Idx -= Input * NumLaneElems;
6929
6930       // Find or create a shuffle vector operand to hold this input.
6931       unsigned OpNo;
6932       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6933         if (InputUsed[OpNo] == Input)
6934           // This input vector is already an operand.
6935           break;
6936         if (InputUsed[OpNo] < 0) {
6937           // Create a new operand for this input vector.
6938           InputUsed[OpNo] = Input;
6939           break;
6940         }
6941       }
6942
6943       if (OpNo >= array_lengthof(InputUsed)) {
6944         // More than two input vectors used!  Give up on trying to create a
6945         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6946         UseBuildVector = true;
6947         break;
6948       }
6949
6950       // Add the mask index for the new shuffle vector.
6951       Mask.push_back(Idx + OpNo * NumLaneElems);
6952     }
6953
6954     if (UseBuildVector) {
6955       SmallVector<SDValue, 16> SVOps;
6956       for (unsigned i = 0; i != NumLaneElems; ++i) {
6957         // The mask element.  This indexes into the input.
6958         int Idx = SVOp->getMaskElt(i+LaneStart);
6959         if (Idx < 0) {
6960           SVOps.push_back(DAG.getUNDEF(EltVT));
6961           continue;
6962         }
6963
6964         // The input vector this mask element indexes into.
6965         int Input = Idx / NumElems;
6966
6967         // Turn the index into an offset from the start of the input vector.
6968         Idx -= Input * NumElems;
6969
6970         // Extract the vector element by hand.
6971         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6972                                     SVOp->getOperand(Input),
6973                                     DAG.getIntPtrConstant(Idx)));
6974       }
6975
6976       // Construct the output using a BUILD_VECTOR.
6977       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6978                               SVOps.size());
6979     } else if (InputUsed[0] < 0) {
6980       // No input vectors were used! The result is undefined.
6981       Output[l] = DAG.getUNDEF(NVT);
6982     } else {
6983       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6984                                         (InputUsed[0] % 2) * NumLaneElems,
6985                                         DAG, dl);
6986       // If only one input was used, use an undefined vector for the other.
6987       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6988         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6989                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6990       // At least one input vector was used. Create a new shuffle vector.
6991       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6992     }
6993
6994     Mask.clear();
6995   }
6996
6997   // Concatenate the result back
6998   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6999 }
7000
7001 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7002 /// 4 elements, and match them with several different shuffle types.
7003 static SDValue
7004 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7005   SDValue V1 = SVOp->getOperand(0);
7006   SDValue V2 = SVOp->getOperand(1);
7007   SDLoc dl(SVOp);
7008   MVT VT = SVOp->getSimpleValueType(0);
7009
7010   assert(VT.is128BitVector() && "Unsupported vector size");
7011
7012   std::pair<int, int> Locs[4];
7013   int Mask1[] = { -1, -1, -1, -1 };
7014   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7015
7016   unsigned NumHi = 0;
7017   unsigned NumLo = 0;
7018   for (unsigned i = 0; i != 4; ++i) {
7019     int Idx = PermMask[i];
7020     if (Idx < 0) {
7021       Locs[i] = std::make_pair(-1, -1);
7022     } else {
7023       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7024       if (Idx < 4) {
7025         Locs[i] = std::make_pair(0, NumLo);
7026         Mask1[NumLo] = Idx;
7027         NumLo++;
7028       } else {
7029         Locs[i] = std::make_pair(1, NumHi);
7030         if (2+NumHi < 4)
7031           Mask1[2+NumHi] = Idx;
7032         NumHi++;
7033       }
7034     }
7035   }
7036
7037   if (NumLo <= 2 && NumHi <= 2) {
7038     // If no more than two elements come from either vector. This can be
7039     // implemented with two shuffles. First shuffle gather the elements.
7040     // The second shuffle, which takes the first shuffle as both of its
7041     // vector operands, put the elements into the right order.
7042     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7043
7044     int Mask2[] = { -1, -1, -1, -1 };
7045
7046     for (unsigned i = 0; i != 4; ++i)
7047       if (Locs[i].first != -1) {
7048         unsigned Idx = (i < 2) ? 0 : 4;
7049         Idx += Locs[i].first * 2 + Locs[i].second;
7050         Mask2[i] = Idx;
7051       }
7052
7053     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7054   }
7055
7056   if (NumLo == 3 || NumHi == 3) {
7057     // Otherwise, we must have three elements from one vector, call it X, and
7058     // one element from the other, call it Y.  First, use a shufps to build an
7059     // intermediate vector with the one element from Y and the element from X
7060     // that will be in the same half in the final destination (the indexes don't
7061     // matter). Then, use a shufps to build the final vector, taking the half
7062     // containing the element from Y from the intermediate, and the other half
7063     // from X.
7064     if (NumHi == 3) {
7065       // Normalize it so the 3 elements come from V1.
7066       CommuteVectorShuffleMask(PermMask, 4);
7067       std::swap(V1, V2);
7068     }
7069
7070     // Find the element from V2.
7071     unsigned HiIndex;
7072     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7073       int Val = PermMask[HiIndex];
7074       if (Val < 0)
7075         continue;
7076       if (Val >= 4)
7077         break;
7078     }
7079
7080     Mask1[0] = PermMask[HiIndex];
7081     Mask1[1] = -1;
7082     Mask1[2] = PermMask[HiIndex^1];
7083     Mask1[3] = -1;
7084     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7085
7086     if (HiIndex >= 2) {
7087       Mask1[0] = PermMask[0];
7088       Mask1[1] = PermMask[1];
7089       Mask1[2] = HiIndex & 1 ? 6 : 4;
7090       Mask1[3] = HiIndex & 1 ? 4 : 6;
7091       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7092     }
7093
7094     Mask1[0] = HiIndex & 1 ? 2 : 0;
7095     Mask1[1] = HiIndex & 1 ? 0 : 2;
7096     Mask1[2] = PermMask[2];
7097     Mask1[3] = PermMask[3];
7098     if (Mask1[2] >= 0)
7099       Mask1[2] += 4;
7100     if (Mask1[3] >= 0)
7101       Mask1[3] += 4;
7102     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7103   }
7104
7105   // Break it into (shuffle shuffle_hi, shuffle_lo).
7106   int LoMask[] = { -1, -1, -1, -1 };
7107   int HiMask[] = { -1, -1, -1, -1 };
7108
7109   int *MaskPtr = LoMask;
7110   unsigned MaskIdx = 0;
7111   unsigned LoIdx = 0;
7112   unsigned HiIdx = 2;
7113   for (unsigned i = 0; i != 4; ++i) {
7114     if (i == 2) {
7115       MaskPtr = HiMask;
7116       MaskIdx = 1;
7117       LoIdx = 0;
7118       HiIdx = 2;
7119     }
7120     int Idx = PermMask[i];
7121     if (Idx < 0) {
7122       Locs[i] = std::make_pair(-1, -1);
7123     } else if (Idx < 4) {
7124       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7125       MaskPtr[LoIdx] = Idx;
7126       LoIdx++;
7127     } else {
7128       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7129       MaskPtr[HiIdx] = Idx;
7130       HiIdx++;
7131     }
7132   }
7133
7134   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7135   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7136   int MaskOps[] = { -1, -1, -1, -1 };
7137   for (unsigned i = 0; i != 4; ++i)
7138     if (Locs[i].first != -1)
7139       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7140   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7141 }
7142
7143 static bool MayFoldVectorLoad(SDValue V) {
7144   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7145     V = V.getOperand(0);
7146
7147   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7148     V = V.getOperand(0);
7149   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7150       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7151     // BUILD_VECTOR (load), undef
7152     V = V.getOperand(0);
7153
7154   return MayFoldLoad(V);
7155 }
7156
7157 static
7158 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7159   MVT VT = Op.getSimpleValueType();
7160
7161   // Canonizalize to v2f64.
7162   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7163   return DAG.getNode(ISD::BITCAST, dl, VT,
7164                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7165                                           V1, DAG));
7166 }
7167
7168 static
7169 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7170                         bool HasSSE2) {
7171   SDValue V1 = Op.getOperand(0);
7172   SDValue V2 = Op.getOperand(1);
7173   MVT VT = Op.getSimpleValueType();
7174
7175   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7176
7177   if (HasSSE2 && VT == MVT::v2f64)
7178     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7179
7180   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7181   return DAG.getNode(ISD::BITCAST, dl, VT,
7182                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7183                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7184                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7185 }
7186
7187 static
7188 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7189   SDValue V1 = Op.getOperand(0);
7190   SDValue V2 = Op.getOperand(1);
7191   MVT VT = Op.getSimpleValueType();
7192
7193   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7194          "unsupported shuffle type");
7195
7196   if (V2.getOpcode() == ISD::UNDEF)
7197     V2 = V1;
7198
7199   // v4i32 or v4f32
7200   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7201 }
7202
7203 static
7204 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7205   SDValue V1 = Op.getOperand(0);
7206   SDValue V2 = Op.getOperand(1);
7207   MVT VT = Op.getSimpleValueType();
7208   unsigned NumElems = VT.getVectorNumElements();
7209
7210   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7211   // operand of these instructions is only memory, so check if there's a
7212   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7213   // same masks.
7214   bool CanFoldLoad = false;
7215
7216   // Trivial case, when V2 comes from a load.
7217   if (MayFoldVectorLoad(V2))
7218     CanFoldLoad = true;
7219
7220   // When V1 is a load, it can be folded later into a store in isel, example:
7221   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7222   //    turns into:
7223   //  (MOVLPSmr addr:$src1, VR128:$src2)
7224   // So, recognize this potential and also use MOVLPS or MOVLPD
7225   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7226     CanFoldLoad = true;
7227
7228   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7229   if (CanFoldLoad) {
7230     if (HasSSE2 && NumElems == 2)
7231       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7232
7233     if (NumElems == 4)
7234       // If we don't care about the second element, proceed to use movss.
7235       if (SVOp->getMaskElt(1) != -1)
7236         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7237   }
7238
7239   // movl and movlp will both match v2i64, but v2i64 is never matched by
7240   // movl earlier because we make it strict to avoid messing with the movlp load
7241   // folding logic (see the code above getMOVLP call). Match it here then,
7242   // this is horrible, but will stay like this until we move all shuffle
7243   // matching to x86 specific nodes. Note that for the 1st condition all
7244   // types are matched with movsd.
7245   if (HasSSE2) {
7246     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7247     // as to remove this logic from here, as much as possible
7248     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7249       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7250     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7251   }
7252
7253   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7254
7255   // Invert the operand order and use SHUFPS to match it.
7256   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7257                               getShuffleSHUFImmediate(SVOp), DAG);
7258 }
7259
7260 // Reduce a vector shuffle to zext.
7261 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7262                                     SelectionDAG &DAG) {
7263   // PMOVZX is only available from SSE41.
7264   if (!Subtarget->hasSSE41())
7265     return SDValue();
7266
7267   MVT VT = Op.getSimpleValueType();
7268
7269   // Only AVX2 support 256-bit vector integer extending.
7270   if (!Subtarget->hasInt256() && VT.is256BitVector())
7271     return SDValue();
7272
7273   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7274   SDLoc DL(Op);
7275   SDValue V1 = Op.getOperand(0);
7276   SDValue V2 = Op.getOperand(1);
7277   unsigned NumElems = VT.getVectorNumElements();
7278
7279   // Extending is an unary operation and the element type of the source vector
7280   // won't be equal to or larger than i64.
7281   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7282       VT.getVectorElementType() == MVT::i64)
7283     return SDValue();
7284
7285   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7286   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7287   while ((1U << Shift) < NumElems) {
7288     if (SVOp->getMaskElt(1U << Shift) == 1)
7289       break;
7290     Shift += 1;
7291     // The maximal ratio is 8, i.e. from i8 to i64.
7292     if (Shift > 3)
7293       return SDValue();
7294   }
7295
7296   // Check the shuffle mask.
7297   unsigned Mask = (1U << Shift) - 1;
7298   for (unsigned i = 0; i != NumElems; ++i) {
7299     int EltIdx = SVOp->getMaskElt(i);
7300     if ((i & Mask) != 0 && EltIdx != -1)
7301       return SDValue();
7302     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7303       return SDValue();
7304   }
7305
7306   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7307   MVT NeVT = MVT::getIntegerVT(NBits);
7308   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7309
7310   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7311     return SDValue();
7312
7313   // Simplify the operand as it's prepared to be fed into shuffle.
7314   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7315   if (V1.getOpcode() == ISD::BITCAST &&
7316       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7317       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7318       V1.getOperand(0).getOperand(0)
7319         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7320     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7321     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7322     ConstantSDNode *CIdx =
7323       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7324     // If it's foldable, i.e. normal load with single use, we will let code
7325     // selection to fold it. Otherwise, we will short the conversion sequence.
7326     if (CIdx && CIdx->getZExtValue() == 0 &&
7327         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7328       MVT FullVT = V.getSimpleValueType();
7329       MVT V1VT = V1.getSimpleValueType();
7330       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7331         // The "ext_vec_elt" node is wider than the result node.
7332         // In this case we should extract subvector from V.
7333         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7334         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7335         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7336                                         FullVT.getVectorNumElements()/Ratio);
7337         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7338                         DAG.getIntPtrConstant(0));
7339       }
7340       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7341     }
7342   }
7343
7344   return DAG.getNode(ISD::BITCAST, DL, VT,
7345                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7346 }
7347
7348 static SDValue
7349 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7350                        SelectionDAG &DAG) {
7351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7352   MVT VT = Op.getSimpleValueType();
7353   SDLoc dl(Op);
7354   SDValue V1 = Op.getOperand(0);
7355   SDValue V2 = Op.getOperand(1);
7356
7357   if (isZeroShuffle(SVOp))
7358     return getZeroVector(VT, Subtarget, DAG, dl);
7359
7360   // Handle splat operations
7361   if (SVOp->isSplat()) {
7362     // Use vbroadcast whenever the splat comes from a foldable load
7363     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7364     if (Broadcast.getNode())
7365       return Broadcast;
7366   }
7367
7368   // Check integer expanding shuffles.
7369   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7370   if (NewOp.getNode())
7371     return NewOp;
7372
7373   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7374   // do it!
7375   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7376       VT == MVT::v16i16 || VT == MVT::v32i8) {
7377     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7378     if (NewOp.getNode())
7379       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7380   } else if ((VT == MVT::v4i32 ||
7381              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7382     // FIXME: Figure out a cleaner way to do this.
7383     // Try to make use of movq to zero out the top part.
7384     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7385       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7386       if (NewOp.getNode()) {
7387         MVT NewVT = NewOp.getSimpleValueType();
7388         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7389                                NewVT, true, false))
7390           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7391                               DAG, Subtarget, dl);
7392       }
7393     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7394       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7395       if (NewOp.getNode()) {
7396         MVT NewVT = NewOp.getSimpleValueType();
7397         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7398           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7399                               DAG, Subtarget, dl);
7400       }
7401     }
7402   }
7403   return SDValue();
7404 }
7405
7406 SDValue
7407 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7408   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7409   SDValue V1 = Op.getOperand(0);
7410   SDValue V2 = Op.getOperand(1);
7411   MVT VT = Op.getSimpleValueType();
7412   SDLoc dl(Op);
7413   unsigned NumElems = VT.getVectorNumElements();
7414   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7415   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7416   bool V1IsSplat = false;
7417   bool V2IsSplat = false;
7418   bool HasSSE2 = Subtarget->hasSSE2();
7419   bool HasFp256    = Subtarget->hasFp256();
7420   bool HasInt256   = Subtarget->hasInt256();
7421   MachineFunction &MF = DAG.getMachineFunction();
7422   bool OptForSize = MF.getFunction()->getAttributes().
7423     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7424
7425   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7426
7427   if (V1IsUndef && V2IsUndef)
7428     return DAG.getUNDEF(VT);
7429
7430   // When we create a shuffle node we put the UNDEF node to second operand,
7431   // but in some cases the first operand may be transformed to UNDEF.
7432   // In this case we should just commute the node.
7433   if (V1IsUndef)
7434     return CommuteVectorShuffle(SVOp, DAG);
7435
7436   // Vector shuffle lowering takes 3 steps:
7437   //
7438   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7439   //    narrowing and commutation of operands should be handled.
7440   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7441   //    shuffle nodes.
7442   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7443   //    so the shuffle can be broken into other shuffles and the legalizer can
7444   //    try the lowering again.
7445   //
7446   // The general idea is that no vector_shuffle operation should be left to
7447   // be matched during isel, all of them must be converted to a target specific
7448   // node here.
7449
7450   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7451   // narrowing and commutation of operands should be handled. The actual code
7452   // doesn't include all of those, work in progress...
7453   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7454   if (NewOp.getNode())
7455     return NewOp;
7456
7457   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7458
7459   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7460   // unpckh_undef). Only use pshufd if speed is more important than size.
7461   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7462     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7463   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7464     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7465
7466   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7467       V2IsUndef && MayFoldVectorLoad(V1))
7468     return getMOVDDup(Op, dl, V1, DAG);
7469
7470   if (isMOVHLPS_v_undef_Mask(M, VT))
7471     return getMOVHighToLow(Op, dl, DAG);
7472
7473   // Use to match splats
7474   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7475       (VT == MVT::v2f64 || VT == MVT::v2i64))
7476     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7477
7478   if (isPSHUFDMask(M, VT)) {
7479     // The actual implementation will match the mask in the if above and then
7480     // during isel it can match several different instructions, not only pshufd
7481     // as its name says, sad but true, emulate the behavior for now...
7482     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7483       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7484
7485     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7486
7487     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7488       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7489
7490     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7491       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7492                                   DAG);
7493
7494     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7495                                 TargetMask, DAG);
7496   }
7497
7498   if (isPALIGNRMask(M, VT, Subtarget))
7499     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7500                                 getShufflePALIGNRImmediate(SVOp),
7501                                 DAG);
7502
7503   // Check if this can be converted into a logical shift.
7504   bool isLeft = false;
7505   unsigned ShAmt = 0;
7506   SDValue ShVal;
7507   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7508   if (isShift && ShVal.hasOneUse()) {
7509     // If the shifted value has multiple uses, it may be cheaper to use
7510     // v_set0 + movlhps or movhlps, etc.
7511     MVT EltVT = VT.getVectorElementType();
7512     ShAmt *= EltVT.getSizeInBits();
7513     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7514   }
7515
7516   if (isMOVLMask(M, VT)) {
7517     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7518       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7519     if (!isMOVLPMask(M, VT)) {
7520       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7521         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7522
7523       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7524         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7525     }
7526   }
7527
7528   // FIXME: fold these into legal mask.
7529   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7530     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7531
7532   if (isMOVHLPSMask(M, VT))
7533     return getMOVHighToLow(Op, dl, DAG);
7534
7535   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7536     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7537
7538   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7539     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7540
7541   if (isMOVLPMask(M, VT))
7542     return getMOVLP(Op, dl, DAG, HasSSE2);
7543
7544   if (ShouldXformToMOVHLPS(M, VT) ||
7545       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7546     return CommuteVectorShuffle(SVOp, DAG);
7547
7548   if (isShift) {
7549     // No better options. Use a vshldq / vsrldq.
7550     MVT EltVT = VT.getVectorElementType();
7551     ShAmt *= EltVT.getSizeInBits();
7552     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7553   }
7554
7555   bool Commuted = false;
7556   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7557   // 1,1,1,1 -> v8i16 though.
7558   V1IsSplat = isSplatVector(V1.getNode());
7559   V2IsSplat = isSplatVector(V2.getNode());
7560
7561   // Canonicalize the splat or undef, if present, to be on the RHS.
7562   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7563     CommuteVectorShuffleMask(M, NumElems);
7564     std::swap(V1, V2);
7565     std::swap(V1IsSplat, V2IsSplat);
7566     Commuted = true;
7567   }
7568
7569   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7570     // Shuffling low element of v1 into undef, just return v1.
7571     if (V2IsUndef)
7572       return V1;
7573     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7574     // the instruction selector will not match, so get a canonical MOVL with
7575     // swapped operands to undo the commute.
7576     return getMOVL(DAG, dl, VT, V2, V1);
7577   }
7578
7579   if (isUNPCKLMask(M, VT, HasInt256))
7580     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7581
7582   if (isUNPCKHMask(M, VT, HasInt256))
7583     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7584
7585   if (V2IsSplat) {
7586     // Normalize mask so all entries that point to V2 points to its first
7587     // element then try to match unpck{h|l} again. If match, return a
7588     // new vector_shuffle with the corrected mask.p
7589     SmallVector<int, 8> NewMask(M.begin(), M.end());
7590     NormalizeMask(NewMask, NumElems);
7591     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7592       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7593     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7594       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7595   }
7596
7597   if (Commuted) {
7598     // Commute is back and try unpck* again.
7599     // FIXME: this seems wrong.
7600     CommuteVectorShuffleMask(M, NumElems);
7601     std::swap(V1, V2);
7602     std::swap(V1IsSplat, V2IsSplat);
7603
7604     if (isUNPCKLMask(M, VT, HasInt256))
7605       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7606
7607     if (isUNPCKHMask(M, VT, HasInt256))
7608       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7609   }
7610
7611   // Normalize the node to match x86 shuffle ops if needed
7612   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7613     return CommuteVectorShuffle(SVOp, DAG);
7614
7615   // The checks below are all present in isShuffleMaskLegal, but they are
7616   // inlined here right now to enable us to directly emit target specific
7617   // nodes, and remove one by one until they don't return Op anymore.
7618
7619   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7620       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7621     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7622       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7623   }
7624
7625   if (isPSHUFHWMask(M, VT, HasInt256))
7626     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7627                                 getShufflePSHUFHWImmediate(SVOp),
7628                                 DAG);
7629
7630   if (isPSHUFLWMask(M, VT, HasInt256))
7631     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7632                                 getShufflePSHUFLWImmediate(SVOp),
7633                                 DAG);
7634
7635   if (isSHUFPMask(M, VT))
7636     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7637                                 getShuffleSHUFImmediate(SVOp), DAG);
7638
7639   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7640     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7641   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7642     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7643
7644   //===--------------------------------------------------------------------===//
7645   // Generate target specific nodes for 128 or 256-bit shuffles only
7646   // supported in the AVX instruction set.
7647   //
7648
7649   // Handle VMOVDDUPY permutations
7650   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7651     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7652
7653   // Handle VPERMILPS/D* permutations
7654   if (isVPERMILPMask(M, VT)) {
7655     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7656       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7657                                   getShuffleSHUFImmediate(SVOp), DAG);
7658     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7659                                 getShuffleSHUFImmediate(SVOp), DAG);
7660   }
7661
7662   // Handle VPERM2F128/VPERM2I128 permutations
7663   if (isVPERM2X128Mask(M, VT, HasFp256))
7664     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7665                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7666
7667   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7668   if (BlendOp.getNode())
7669     return BlendOp;
7670
7671   unsigned Imm8;
7672   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7673     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7674
7675   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7676       VT.is512BitVector()) {
7677     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7678     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7679     SmallVector<SDValue, 16> permclMask;
7680     for (unsigned i = 0; i != NumElems; ++i) {
7681       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7682     }
7683
7684     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7685                                 &permclMask[0], NumElems);
7686     if (V2IsUndef)
7687       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7688       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7689                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7690     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7691                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7692   }
7693
7694   //===--------------------------------------------------------------------===//
7695   // Since no target specific shuffle was selected for this generic one,
7696   // lower it into other known shuffles. FIXME: this isn't true yet, but
7697   // this is the plan.
7698   //
7699
7700   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7701   if (VT == MVT::v8i16) {
7702     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7703     if (NewOp.getNode())
7704       return NewOp;
7705   }
7706
7707   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7708     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7709     if (NewOp.getNode())
7710       return NewOp;
7711   }
7712
7713   if (VT == MVT::v16i8) {
7714     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7715     if (NewOp.getNode())
7716       return NewOp;
7717   }
7718
7719   if (VT == MVT::v32i8) {
7720     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7721     if (NewOp.getNode())
7722       return NewOp;
7723   }
7724
7725   // Handle all 128-bit wide vectors with 4 elements, and match them with
7726   // several different shuffle types.
7727   if (NumElems == 4 && VT.is128BitVector())
7728     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7729
7730   // Handle general 256-bit shuffles
7731   if (VT.is256BitVector())
7732     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7733
7734   return SDValue();
7735 }
7736
7737 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7738   MVT VT = Op.getSimpleValueType();
7739   SDLoc dl(Op);
7740
7741   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7742     return SDValue();
7743
7744   if (VT.getSizeInBits() == 8) {
7745     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7746                                   Op.getOperand(0), Op.getOperand(1));
7747     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7748                                   DAG.getValueType(VT));
7749     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7750   }
7751
7752   if (VT.getSizeInBits() == 16) {
7753     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7754     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7755     if (Idx == 0)
7756       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7757                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7758                                      DAG.getNode(ISD::BITCAST, dl,
7759                                                  MVT::v4i32,
7760                                                  Op.getOperand(0)),
7761                                      Op.getOperand(1)));
7762     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7763                                   Op.getOperand(0), Op.getOperand(1));
7764     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7765                                   DAG.getValueType(VT));
7766     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7767   }
7768
7769   if (VT == MVT::f32) {
7770     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7771     // the result back to FR32 register. It's only worth matching if the
7772     // result has a single use which is a store or a bitcast to i32.  And in
7773     // the case of a store, it's not worth it if the index is a constant 0,
7774     // because a MOVSSmr can be used instead, which is smaller and faster.
7775     if (!Op.hasOneUse())
7776       return SDValue();
7777     SDNode *User = *Op.getNode()->use_begin();
7778     if ((User->getOpcode() != ISD::STORE ||
7779          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7780           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7781         (User->getOpcode() != ISD::BITCAST ||
7782          User->getValueType(0) != MVT::i32))
7783       return SDValue();
7784     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7785                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7786                                               Op.getOperand(0)),
7787                                               Op.getOperand(1));
7788     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7789   }
7790
7791   if (VT == MVT::i32 || VT == MVT::i64) {
7792     // ExtractPS/pextrq works with constant index.
7793     if (isa<ConstantSDNode>(Op.getOperand(1)))
7794       return Op;
7795   }
7796   return SDValue();
7797 }
7798
7799 /// Extract one bit from mask vector, like v16i1 or v8i1.
7800 /// AVX-512 feature.
7801 SDValue
7802 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7803   SDValue Vec = Op.getOperand(0);
7804   SDLoc dl(Vec);
7805   MVT VecVT = Vec.getSimpleValueType();
7806   SDValue Idx = Op.getOperand(1);
7807   MVT EltVT = Op.getSimpleValueType();
7808
7809   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7810
7811   // variable index can't be handled in mask registers,
7812   // extend vector to VR512
7813   if (!isa<ConstantSDNode>(Idx)) {
7814     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7815     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7816     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7817                               ExtVT.getVectorElementType(), Ext, Idx);
7818     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7819   }
7820
7821   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7822   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7823   unsigned MaxSift = rc->getSize()*8 - 1;
7824   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7825                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7826   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7827                     DAG.getConstant(MaxSift, MVT::i8));
7828   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7829                        DAG.getIntPtrConstant(0));
7830 }
7831
7832 SDValue
7833 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7834                                            SelectionDAG &DAG) const {
7835   SDLoc dl(Op);
7836   SDValue Vec = Op.getOperand(0);
7837   MVT VecVT = Vec.getSimpleValueType();
7838   SDValue Idx = Op.getOperand(1);
7839
7840   if (Op.getSimpleValueType() == MVT::i1)
7841     return ExtractBitFromMaskVector(Op, DAG);
7842
7843   if (!isa<ConstantSDNode>(Idx)) {
7844     if (VecVT.is512BitVector() ||
7845         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7846          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7847
7848       MVT MaskEltVT =
7849         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7850       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7851                                     MaskEltVT.getSizeInBits());
7852
7853       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7854       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7855                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7856                                 Idx, DAG.getConstant(0, getPointerTy()));
7857       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7858       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7859                         Perm, DAG.getConstant(0, getPointerTy()));
7860     }
7861     return SDValue();
7862   }
7863
7864   // If this is a 256-bit vector result, first extract the 128-bit vector and
7865   // then extract the element from the 128-bit vector.
7866   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7867
7868     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7869     // Get the 128-bit vector.
7870     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7871     MVT EltVT = VecVT.getVectorElementType();
7872
7873     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7874
7875     //if (IdxVal >= NumElems/2)
7876     //  IdxVal -= NumElems/2;
7877     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7878     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7879                        DAG.getConstant(IdxVal, MVT::i32));
7880   }
7881
7882   assert(VecVT.is128BitVector() && "Unexpected vector length");
7883
7884   if (Subtarget->hasSSE41()) {
7885     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7886     if (Res.getNode())
7887       return Res;
7888   }
7889
7890   MVT VT = Op.getSimpleValueType();
7891   // TODO: handle v16i8.
7892   if (VT.getSizeInBits() == 16) {
7893     SDValue Vec = Op.getOperand(0);
7894     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7895     if (Idx == 0)
7896       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7897                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898                                      DAG.getNode(ISD::BITCAST, dl,
7899                                                  MVT::v4i32, Vec),
7900                                      Op.getOperand(1)));
7901     // Transform it so it match pextrw which produces a 32-bit result.
7902     MVT EltVT = MVT::i32;
7903     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7904                                   Op.getOperand(0), Op.getOperand(1));
7905     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7906                                   DAG.getValueType(VT));
7907     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7908   }
7909
7910   if (VT.getSizeInBits() == 32) {
7911     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7912     if (Idx == 0)
7913       return Op;
7914
7915     // SHUFPS the element to the lowest double word, then movss.
7916     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7917     MVT VVT = Op.getOperand(0).getSimpleValueType();
7918     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7919                                        DAG.getUNDEF(VVT), Mask);
7920     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7921                        DAG.getIntPtrConstant(0));
7922   }
7923
7924   if (VT.getSizeInBits() == 64) {
7925     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7926     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7927     //        to match extract_elt for f64.
7928     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7929     if (Idx == 0)
7930       return Op;
7931
7932     // UNPCKHPD the element to the lowest double word, then movsd.
7933     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7934     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7935     int Mask[2] = { 1, -1 };
7936     MVT VVT = Op.getOperand(0).getSimpleValueType();
7937     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7938                                        DAG.getUNDEF(VVT), Mask);
7939     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7940                        DAG.getIntPtrConstant(0));
7941   }
7942
7943   return SDValue();
7944 }
7945
7946 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7947   MVT VT = Op.getSimpleValueType();
7948   MVT EltVT = VT.getVectorElementType();
7949   SDLoc dl(Op);
7950
7951   SDValue N0 = Op.getOperand(0);
7952   SDValue N1 = Op.getOperand(1);
7953   SDValue N2 = Op.getOperand(2);
7954
7955   if (!VT.is128BitVector())
7956     return SDValue();
7957
7958   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7959       isa<ConstantSDNode>(N2)) {
7960     unsigned Opc;
7961     if (VT == MVT::v8i16)
7962       Opc = X86ISD::PINSRW;
7963     else if (VT == MVT::v16i8)
7964       Opc = X86ISD::PINSRB;
7965     else
7966       Opc = X86ISD::PINSRB;
7967
7968     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7969     // argument.
7970     if (N1.getValueType() != MVT::i32)
7971       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7972     if (N2.getValueType() != MVT::i32)
7973       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7974     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7975   }
7976
7977   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7978     // Bits [7:6] of the constant are the source select.  This will always be
7979     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7980     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7981     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7982     // Bits [5:4] of the constant are the destination select.  This is the
7983     //  value of the incoming immediate.
7984     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7985     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7986     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7987     // Create this as a scalar to vector..
7988     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7989     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7990   }
7991
7992   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7993     // PINSR* works with constant index.
7994     return Op;
7995   }
7996   return SDValue();
7997 }
7998
7999 /// Insert one bit to mask vector, like v16i1 or v8i1.
8000 /// AVX-512 feature.
8001 SDValue 
8002 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8003   SDLoc dl(Op);
8004   SDValue Vec = Op.getOperand(0);
8005   SDValue Elt = Op.getOperand(1);
8006   SDValue Idx = Op.getOperand(2);
8007   MVT VecVT = Vec.getSimpleValueType();
8008
8009   if (!isa<ConstantSDNode>(Idx)) {
8010     // Non constant index. Extend source and destination,
8011     // insert element and then truncate the result.
8012     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8013     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8014     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8015       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8016       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8017     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8018   }
8019
8020   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8021   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8022   if (Vec.getOpcode() == ISD::UNDEF)
8023     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8024                        DAG.getConstant(IdxVal, MVT::i8));
8025   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8026   unsigned MaxSift = rc->getSize()*8 - 1;
8027   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8028                     DAG.getConstant(MaxSift, MVT::i8));
8029   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8030                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8031   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8032 }
8033 SDValue
8034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8035   MVT VT = Op.getSimpleValueType();
8036   MVT EltVT = VT.getVectorElementType();
8037   
8038   if (EltVT == MVT::i1)
8039     return InsertBitToMaskVector(Op, DAG);
8040
8041   SDLoc dl(Op);
8042   SDValue N0 = Op.getOperand(0);
8043   SDValue N1 = Op.getOperand(1);
8044   SDValue N2 = Op.getOperand(2);
8045
8046   // If this is a 256-bit vector result, first extract the 128-bit vector,
8047   // insert the element into the extracted half and then place it back.
8048   if (VT.is256BitVector() || VT.is512BitVector()) {
8049     if (!isa<ConstantSDNode>(N2))
8050       return SDValue();
8051
8052     // Get the desired 128-bit vector half.
8053     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8054     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8055
8056     // Insert the element into the desired half.
8057     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8058     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8059
8060     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8061                     DAG.getConstant(IdxIn128, MVT::i32));
8062
8063     // Insert the changed part back to the 256-bit vector
8064     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8065   }
8066
8067   if (Subtarget->hasSSE41())
8068     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8069
8070   if (EltVT == MVT::i8)
8071     return SDValue();
8072
8073   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8074     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8075     // as its second argument.
8076     if (N1.getValueType() != MVT::i32)
8077       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8078     if (N2.getValueType() != MVT::i32)
8079       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8080     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8081   }
8082   return SDValue();
8083 }
8084
8085 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8086   SDLoc dl(Op);
8087   MVT OpVT = Op.getSimpleValueType();
8088
8089   // If this is a 256-bit vector result, first insert into a 128-bit
8090   // vector and then insert into the 256-bit vector.
8091   if (!OpVT.is128BitVector()) {
8092     // Insert into a 128-bit vector.
8093     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8094     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8095                                  OpVT.getVectorNumElements() / SizeFactor);
8096
8097     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8098
8099     // Insert the 128-bit vector.
8100     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8101   }
8102
8103   if (OpVT == MVT::v1i64 &&
8104       Op.getOperand(0).getValueType() == MVT::i64)
8105     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8106
8107   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8108   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8109   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8110                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8111 }
8112
8113 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8114 // a simple subregister reference or explicit instructions to grab
8115 // upper bits of a vector.
8116 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8117                                       SelectionDAG &DAG) {
8118   SDLoc dl(Op);
8119   SDValue In =  Op.getOperand(0);
8120   SDValue Idx = Op.getOperand(1);
8121   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8122   MVT ResVT   = Op.getSimpleValueType();
8123   MVT InVT    = In.getSimpleValueType();
8124
8125   if (Subtarget->hasFp256()) {
8126     if (ResVT.is128BitVector() &&
8127         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8128         isa<ConstantSDNode>(Idx)) {
8129       return Extract128BitVector(In, IdxVal, DAG, dl);
8130     }
8131     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8132         isa<ConstantSDNode>(Idx)) {
8133       return Extract256BitVector(In, IdxVal, DAG, dl);
8134     }
8135   }
8136   return SDValue();
8137 }
8138
8139 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8140 // simple superregister reference or explicit instructions to insert
8141 // the upper bits of a vector.
8142 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8143                                      SelectionDAG &DAG) {
8144   if (Subtarget->hasFp256()) {
8145     SDLoc dl(Op.getNode());
8146     SDValue Vec = Op.getNode()->getOperand(0);
8147     SDValue SubVec = Op.getNode()->getOperand(1);
8148     SDValue Idx = Op.getNode()->getOperand(2);
8149
8150     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8151          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8152         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8153         isa<ConstantSDNode>(Idx)) {
8154       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8155       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8156     }
8157
8158     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8159         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8160         isa<ConstantSDNode>(Idx)) {
8161       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8162       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8163     }
8164   }
8165   return SDValue();
8166 }
8167
8168 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8169 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8170 // one of the above mentioned nodes. It has to be wrapped because otherwise
8171 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8172 // be used to form addressing mode. These wrapped nodes will be selected
8173 // into MOV32ri.
8174 SDValue
8175 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8176   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8177
8178   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8179   // global base reg.
8180   unsigned char OpFlag = 0;
8181   unsigned WrapperKind = X86ISD::Wrapper;
8182   CodeModel::Model M = getTargetMachine().getCodeModel();
8183
8184   if (Subtarget->isPICStyleRIPRel() &&
8185       (M == CodeModel::Small || M == CodeModel::Kernel))
8186     WrapperKind = X86ISD::WrapperRIP;
8187   else if (Subtarget->isPICStyleGOT())
8188     OpFlag = X86II::MO_GOTOFF;
8189   else if (Subtarget->isPICStyleStubPIC())
8190     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8191
8192   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8193                                              CP->getAlignment(),
8194                                              CP->getOffset(), OpFlag);
8195   SDLoc DL(CP);
8196   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8197   // With PIC, the address is actually $g + Offset.
8198   if (OpFlag) {
8199     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8200                          DAG.getNode(X86ISD::GlobalBaseReg,
8201                                      SDLoc(), getPointerTy()),
8202                          Result);
8203   }
8204
8205   return Result;
8206 }
8207
8208 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8209   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8210
8211   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8212   // global base reg.
8213   unsigned char OpFlag = 0;
8214   unsigned WrapperKind = X86ISD::Wrapper;
8215   CodeModel::Model M = getTargetMachine().getCodeModel();
8216
8217   if (Subtarget->isPICStyleRIPRel() &&
8218       (M == CodeModel::Small || M == CodeModel::Kernel))
8219     WrapperKind = X86ISD::WrapperRIP;
8220   else if (Subtarget->isPICStyleGOT())
8221     OpFlag = X86II::MO_GOTOFF;
8222   else if (Subtarget->isPICStyleStubPIC())
8223     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8224
8225   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8226                                           OpFlag);
8227   SDLoc DL(JT);
8228   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8229
8230   // With PIC, the address is actually $g + Offset.
8231   if (OpFlag)
8232     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8233                          DAG.getNode(X86ISD::GlobalBaseReg,
8234                                      SDLoc(), getPointerTy()),
8235                          Result);
8236
8237   return Result;
8238 }
8239
8240 SDValue
8241 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8242   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8243
8244   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8245   // global base reg.
8246   unsigned char OpFlag = 0;
8247   unsigned WrapperKind = X86ISD::Wrapper;
8248   CodeModel::Model M = getTargetMachine().getCodeModel();
8249
8250   if (Subtarget->isPICStyleRIPRel() &&
8251       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8252     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8253       OpFlag = X86II::MO_GOTPCREL;
8254     WrapperKind = X86ISD::WrapperRIP;
8255   } else if (Subtarget->isPICStyleGOT()) {
8256     OpFlag = X86II::MO_GOT;
8257   } else if (Subtarget->isPICStyleStubPIC()) {
8258     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8259   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8260     OpFlag = X86II::MO_DARWIN_NONLAZY;
8261   }
8262
8263   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8264
8265   SDLoc DL(Op);
8266   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8267
8268   // With PIC, the address is actually $g + Offset.
8269   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8270       !Subtarget->is64Bit()) {
8271     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8272                          DAG.getNode(X86ISD::GlobalBaseReg,
8273                                      SDLoc(), getPointerTy()),
8274                          Result);
8275   }
8276
8277   // For symbols that require a load from a stub to get the address, emit the
8278   // load.
8279   if (isGlobalStubReference(OpFlag))
8280     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8281                          MachinePointerInfo::getGOT(), false, false, false, 0);
8282
8283   return Result;
8284 }
8285
8286 SDValue
8287 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8288   // Create the TargetBlockAddressAddress node.
8289   unsigned char OpFlags =
8290     Subtarget->ClassifyBlockAddressReference();
8291   CodeModel::Model M = getTargetMachine().getCodeModel();
8292   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8293   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8294   SDLoc dl(Op);
8295   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8296                                              OpFlags);
8297
8298   if (Subtarget->isPICStyleRIPRel() &&
8299       (M == CodeModel::Small || M == CodeModel::Kernel))
8300     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8301   else
8302     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8303
8304   // With PIC, the address is actually $g + Offset.
8305   if (isGlobalRelativeToPICBase(OpFlags)) {
8306     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8307                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8308                          Result);
8309   }
8310
8311   return Result;
8312 }
8313
8314 SDValue
8315 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8316                                       int64_t Offset, SelectionDAG &DAG) const {
8317   // Create the TargetGlobalAddress node, folding in the constant
8318   // offset if it is legal.
8319   unsigned char OpFlags =
8320     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8321   CodeModel::Model M = getTargetMachine().getCodeModel();
8322   SDValue Result;
8323   if (OpFlags == X86II::MO_NO_FLAG &&
8324       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8325     // A direct static reference to a global.
8326     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8327     Offset = 0;
8328   } else {
8329     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8330   }
8331
8332   if (Subtarget->isPICStyleRIPRel() &&
8333       (M == CodeModel::Small || M == CodeModel::Kernel))
8334     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8335   else
8336     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8337
8338   // With PIC, the address is actually $g + Offset.
8339   if (isGlobalRelativeToPICBase(OpFlags)) {
8340     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8341                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8342                          Result);
8343   }
8344
8345   // For globals that require a load from a stub to get the address, emit the
8346   // load.
8347   if (isGlobalStubReference(OpFlags))
8348     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8349                          MachinePointerInfo::getGOT(), false, false, false, 0);
8350
8351   // If there was a non-zero offset that we didn't fold, create an explicit
8352   // addition for it.
8353   if (Offset != 0)
8354     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8355                          DAG.getConstant(Offset, getPointerTy()));
8356
8357   return Result;
8358 }
8359
8360 SDValue
8361 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8362   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8363   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8364   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8365 }
8366
8367 static SDValue
8368 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8369            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8370            unsigned char OperandFlags, bool LocalDynamic = false) {
8371   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8372   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8373   SDLoc dl(GA);
8374   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8375                                            GA->getValueType(0),
8376                                            GA->getOffset(),
8377                                            OperandFlags);
8378
8379   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8380                                            : X86ISD::TLSADDR;
8381
8382   if (InFlag) {
8383     SDValue Ops[] = { Chain,  TGA, *InFlag };
8384     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8385   } else {
8386     SDValue Ops[]  = { Chain, TGA };
8387     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8388   }
8389
8390   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8391   MFI->setAdjustsStack(true);
8392
8393   SDValue Flag = Chain.getValue(1);
8394   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8395 }
8396
8397 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8398 static SDValue
8399 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8400                                 const EVT PtrVT) {
8401   SDValue InFlag;
8402   SDLoc dl(GA);  // ? function entry point might be better
8403   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8404                                    DAG.getNode(X86ISD::GlobalBaseReg,
8405                                                SDLoc(), PtrVT), InFlag);
8406   InFlag = Chain.getValue(1);
8407
8408   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8409 }
8410
8411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8412 static SDValue
8413 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8414                                 const EVT PtrVT) {
8415   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8416                     X86::RAX, X86II::MO_TLSGD);
8417 }
8418
8419 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8420                                            SelectionDAG &DAG,
8421                                            const EVT PtrVT,
8422                                            bool is64Bit) {
8423   SDLoc dl(GA);
8424
8425   // Get the start address of the TLS block for this module.
8426   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8427       .getInfo<X86MachineFunctionInfo>();
8428   MFI->incNumLocalDynamicTLSAccesses();
8429
8430   SDValue Base;
8431   if (is64Bit) {
8432     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8433                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8434   } else {
8435     SDValue InFlag;
8436     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8437         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8438     InFlag = Chain.getValue(1);
8439     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8440                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8441   }
8442
8443   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8444   // of Base.
8445
8446   // Build x@dtpoff.
8447   unsigned char OperandFlags = X86II::MO_DTPOFF;
8448   unsigned WrapperKind = X86ISD::Wrapper;
8449   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8450                                            GA->getValueType(0),
8451                                            GA->getOffset(), OperandFlags);
8452   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8453
8454   // Add x@dtpoff with the base.
8455   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8456 }
8457
8458 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8459 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8460                                    const EVT PtrVT, TLSModel::Model model,
8461                                    bool is64Bit, bool isPIC) {
8462   SDLoc dl(GA);
8463
8464   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8465   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8466                                                          is64Bit ? 257 : 256));
8467
8468   SDValue ThreadPointer =
8469       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8470                   MachinePointerInfo(Ptr), false, false, false, 0);
8471
8472   unsigned char OperandFlags = 0;
8473   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8474   // initialexec.
8475   unsigned WrapperKind = X86ISD::Wrapper;
8476   if (model == TLSModel::LocalExec) {
8477     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8478   } else if (model == TLSModel::InitialExec) {
8479     if (is64Bit) {
8480       OperandFlags = X86II::MO_GOTTPOFF;
8481       WrapperKind = X86ISD::WrapperRIP;
8482     } else {
8483       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8484     }
8485   } else {
8486     llvm_unreachable("Unexpected model");
8487   }
8488
8489   // emit "addl x@ntpoff,%eax" (local exec)
8490   // or "addl x@indntpoff,%eax" (initial exec)
8491   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8492   SDValue TGA =
8493       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8494                                  GA->getOffset(), OperandFlags);
8495   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8496
8497   if (model == TLSModel::InitialExec) {
8498     if (isPIC && !is64Bit) {
8499       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8500                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8501                            Offset);
8502     }
8503
8504     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8505                          MachinePointerInfo::getGOT(), false, false, false, 0);
8506   }
8507
8508   // The address of the thread local variable is the add of the thread
8509   // pointer with the offset of the variable.
8510   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8511 }
8512
8513 SDValue
8514 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8515
8516   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8517   const GlobalValue *GV = GA->getGlobal();
8518
8519   if (Subtarget->isTargetELF()) {
8520     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8521
8522     switch (model) {
8523       case TLSModel::GeneralDynamic:
8524         if (Subtarget->is64Bit())
8525           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8526         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8527       case TLSModel::LocalDynamic:
8528         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8529                                            Subtarget->is64Bit());
8530       case TLSModel::InitialExec:
8531       case TLSModel::LocalExec:
8532         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8533                                    Subtarget->is64Bit(),
8534                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8535     }
8536     llvm_unreachable("Unknown TLS model.");
8537   }
8538
8539   if (Subtarget->isTargetDarwin()) {
8540     // Darwin only has one model of TLS.  Lower to that.
8541     unsigned char OpFlag = 0;
8542     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8543                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8544
8545     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8546     // global base reg.
8547     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8548                   !Subtarget->is64Bit();
8549     if (PIC32)
8550       OpFlag = X86II::MO_TLVP_PIC_BASE;
8551     else
8552       OpFlag = X86II::MO_TLVP;
8553     SDLoc DL(Op);
8554     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8555                                                 GA->getValueType(0),
8556                                                 GA->getOffset(), OpFlag);
8557     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8558
8559     // With PIC32, the address is actually $g + Offset.
8560     if (PIC32)
8561       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8562                            DAG.getNode(X86ISD::GlobalBaseReg,
8563                                        SDLoc(), getPointerTy()),
8564                            Offset);
8565
8566     // Lowering the machine isd will make sure everything is in the right
8567     // location.
8568     SDValue Chain = DAG.getEntryNode();
8569     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8570     SDValue Args[] = { Chain, Offset };
8571     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8572
8573     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8574     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8575     MFI->setAdjustsStack(true);
8576
8577     // And our return value (tls address) is in the standard call return value
8578     // location.
8579     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8580     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8581                               Chain.getValue(1));
8582   }
8583
8584   if (Subtarget->isTargetKnownWindowsMSVC() ||
8585       Subtarget->isTargetWindowsGNU()) {
8586     // Just use the implicit TLS architecture
8587     // Need to generate someting similar to:
8588     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8589     //                                  ; from TEB
8590     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8591     //   mov     rcx, qword [rdx+rcx*8]
8592     //   mov     eax, .tls$:tlsvar
8593     //   [rax+rcx] contains the address
8594     // Windows 64bit: gs:0x58
8595     // Windows 32bit: fs:__tls_array
8596
8597     // If GV is an alias then use the aliasee for determining
8598     // thread-localness.
8599     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8600       GV = GA->getAliasedGlobal();
8601     SDLoc dl(GA);
8602     SDValue Chain = DAG.getEntryNode();
8603
8604     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8605     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8606     // use its literal value of 0x2C.
8607     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8608                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8609                                                              256)
8610                                         : Type::getInt32PtrTy(*DAG.getContext(),
8611                                                               257));
8612
8613     SDValue TlsArray =
8614         Subtarget->is64Bit()
8615             ? DAG.getIntPtrConstant(0x58)
8616             : (Subtarget->isTargetWindowsGNU()
8617                    ? DAG.getIntPtrConstant(0x2C)
8618                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8619
8620     SDValue ThreadPointer =
8621         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8622                     MachinePointerInfo(Ptr), false, false, false, 0);
8623
8624     // Load the _tls_index variable
8625     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8626     if (Subtarget->is64Bit())
8627       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8628                            IDX, MachinePointerInfo(), MVT::i32,
8629                            false, false, 0);
8630     else
8631       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8632                         false, false, false, 0);
8633
8634     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8635                                     getPointerTy());
8636     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8637
8638     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8639     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8640                       false, false, false, 0);
8641
8642     // Get the offset of start of .tls section
8643     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8644                                              GA->getValueType(0),
8645                                              GA->getOffset(), X86II::MO_SECREL);
8646     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8647
8648     // The address of the thread local variable is the add of the thread
8649     // pointer with the offset of the variable.
8650     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8651   }
8652
8653   llvm_unreachable("TLS not implemented for this target.");
8654 }
8655
8656 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8657 /// and take a 2 x i32 value to shift plus a shift amount.
8658 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8659   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8660   MVT VT = Op.getSimpleValueType();
8661   unsigned VTBits = VT.getSizeInBits();
8662   SDLoc dl(Op);
8663   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8664   SDValue ShOpLo = Op.getOperand(0);
8665   SDValue ShOpHi = Op.getOperand(1);
8666   SDValue ShAmt  = Op.getOperand(2);
8667   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8668   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8669   // during isel.
8670   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8671                                   DAG.getConstant(VTBits - 1, MVT::i8));
8672   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8673                                      DAG.getConstant(VTBits - 1, MVT::i8))
8674                        : DAG.getConstant(0, VT);
8675
8676   SDValue Tmp2, Tmp3;
8677   if (Op.getOpcode() == ISD::SHL_PARTS) {
8678     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8679     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8680   } else {
8681     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8682     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8683   }
8684
8685   // If the shift amount is larger or equal than the width of a part we can't
8686   // rely on the results of shld/shrd. Insert a test and select the appropriate
8687   // values for large shift amounts.
8688   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8689                                 DAG.getConstant(VTBits, MVT::i8));
8690   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8691                              AndNode, DAG.getConstant(0, MVT::i8));
8692
8693   SDValue Hi, Lo;
8694   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8695   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8696   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8697
8698   if (Op.getOpcode() == ISD::SHL_PARTS) {
8699     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8700     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8701   } else {
8702     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8703     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8704   }
8705
8706   SDValue Ops[2] = { Lo, Hi };
8707   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8708 }
8709
8710 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8711                                            SelectionDAG &DAG) const {
8712   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8713
8714   if (SrcVT.isVector())
8715     return SDValue();
8716
8717   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8718          "Unknown SINT_TO_FP to lower!");
8719
8720   // These are really Legal; return the operand so the caller accepts it as
8721   // Legal.
8722   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8723     return Op;
8724   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8725       Subtarget->is64Bit()) {
8726     return Op;
8727   }
8728
8729   SDLoc dl(Op);
8730   unsigned Size = SrcVT.getSizeInBits()/8;
8731   MachineFunction &MF = DAG.getMachineFunction();
8732   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8733   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8734   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8735                                StackSlot,
8736                                MachinePointerInfo::getFixedStack(SSFI),
8737                                false, false, 0);
8738   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8739 }
8740
8741 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8742                                      SDValue StackSlot,
8743                                      SelectionDAG &DAG) const {
8744   // Build the FILD
8745   SDLoc DL(Op);
8746   SDVTList Tys;
8747   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8748   if (useSSE)
8749     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8750   else
8751     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8752
8753   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8754
8755   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8756   MachineMemOperand *MMO;
8757   if (FI) {
8758     int SSFI = FI->getIndex();
8759     MMO =
8760       DAG.getMachineFunction()
8761       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8762                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8763   } else {
8764     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8765     StackSlot = StackSlot.getOperand(1);
8766   }
8767   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8768   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8769                                            X86ISD::FILD, DL,
8770                                            Tys, Ops, array_lengthof(Ops),
8771                                            SrcVT, MMO);
8772
8773   if (useSSE) {
8774     Chain = Result.getValue(1);
8775     SDValue InFlag = Result.getValue(2);
8776
8777     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8778     // shouldn't be necessary except that RFP cannot be live across
8779     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8780     MachineFunction &MF = DAG.getMachineFunction();
8781     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8782     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8783     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8784     Tys = DAG.getVTList(MVT::Other);
8785     SDValue Ops[] = {
8786       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8787     };
8788     MachineMemOperand *MMO =
8789       DAG.getMachineFunction()
8790       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8791                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8792
8793     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8794                                     Ops, array_lengthof(Ops),
8795                                     Op.getValueType(), MMO);
8796     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8797                          MachinePointerInfo::getFixedStack(SSFI),
8798                          false, false, false, 0);
8799   }
8800
8801   return Result;
8802 }
8803
8804 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8805 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8806                                                SelectionDAG &DAG) const {
8807   // This algorithm is not obvious. Here it is what we're trying to output:
8808   /*
8809      movq       %rax,  %xmm0
8810      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8811      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8812      #ifdef __SSE3__
8813        haddpd   %xmm0, %xmm0
8814      #else
8815        pshufd   $0x4e, %xmm0, %xmm1
8816        addpd    %xmm1, %xmm0
8817      #endif
8818   */
8819
8820   SDLoc dl(Op);
8821   LLVMContext *Context = DAG.getContext();
8822
8823   // Build some magic constants.
8824   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8825   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8826   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8827
8828   SmallVector<Constant*,2> CV1;
8829   CV1.push_back(
8830     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8831                                       APInt(64, 0x4330000000000000ULL))));
8832   CV1.push_back(
8833     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8834                                       APInt(64, 0x4530000000000000ULL))));
8835   Constant *C1 = ConstantVector::get(CV1);
8836   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8837
8838   // Load the 64-bit value into an XMM register.
8839   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8840                             Op.getOperand(0));
8841   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8842                               MachinePointerInfo::getConstantPool(),
8843                               false, false, false, 16);
8844   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8845                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8846                               CLod0);
8847
8848   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8849                               MachinePointerInfo::getConstantPool(),
8850                               false, false, false, 16);
8851   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8852   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8853   SDValue Result;
8854
8855   if (Subtarget->hasSSE3()) {
8856     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8857     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8858   } else {
8859     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8860     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8861                                            S2F, 0x4E, DAG);
8862     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8863                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8864                          Sub);
8865   }
8866
8867   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8868                      DAG.getIntPtrConstant(0));
8869 }
8870
8871 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8872 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8873                                                SelectionDAG &DAG) const {
8874   SDLoc dl(Op);
8875   // FP constant to bias correct the final result.
8876   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8877                                    MVT::f64);
8878
8879   // Load the 32-bit value into an XMM register.
8880   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8881                              Op.getOperand(0));
8882
8883   // Zero out the upper parts of the register.
8884   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8885
8886   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8887                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8888                      DAG.getIntPtrConstant(0));
8889
8890   // Or the load with the bias.
8891   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8892                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8893                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8894                                                    MVT::v2f64, Load)),
8895                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8896                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8897                                                    MVT::v2f64, Bias)));
8898   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8899                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8900                    DAG.getIntPtrConstant(0));
8901
8902   // Subtract the bias.
8903   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8904
8905   // Handle final rounding.
8906   EVT DestVT = Op.getValueType();
8907
8908   if (DestVT.bitsLT(MVT::f64))
8909     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8910                        DAG.getIntPtrConstant(0));
8911   if (DestVT.bitsGT(MVT::f64))
8912     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8913
8914   // Handle final rounding.
8915   return Sub;
8916 }
8917
8918 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8919                                                SelectionDAG &DAG) const {
8920   SDValue N0 = Op.getOperand(0);
8921   MVT SVT = N0.getSimpleValueType();
8922   SDLoc dl(Op);
8923
8924   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8925           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8926          "Custom UINT_TO_FP is not supported!");
8927
8928   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8929   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8930                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8931 }
8932
8933 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8934                                            SelectionDAG &DAG) const {
8935   SDValue N0 = Op.getOperand(0);
8936   SDLoc dl(Op);
8937
8938   if (Op.getValueType().isVector())
8939     return lowerUINT_TO_FP_vec(Op, DAG);
8940
8941   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8942   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8943   // the optimization here.
8944   if (DAG.SignBitIsZero(N0))
8945     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8946
8947   MVT SrcVT = N0.getSimpleValueType();
8948   MVT DstVT = Op.getSimpleValueType();
8949   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8950     return LowerUINT_TO_FP_i64(Op, DAG);
8951   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8952     return LowerUINT_TO_FP_i32(Op, DAG);
8953   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8954     return SDValue();
8955
8956   // Make a 64-bit buffer, and use it to build an FILD.
8957   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8958   if (SrcVT == MVT::i32) {
8959     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8960     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8961                                      getPointerTy(), StackSlot, WordOff);
8962     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8963                                   StackSlot, MachinePointerInfo(),
8964                                   false, false, 0);
8965     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8966                                   OffsetSlot, MachinePointerInfo(),
8967                                   false, false, 0);
8968     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8969     return Fild;
8970   }
8971
8972   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8973   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8974                                StackSlot, MachinePointerInfo(),
8975                                false, false, 0);
8976   // For i64 source, we need to add the appropriate power of 2 if the input
8977   // was negative.  This is the same as the optimization in
8978   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8979   // we must be careful to do the computation in x87 extended precision, not
8980   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8981   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8982   MachineMemOperand *MMO =
8983     DAG.getMachineFunction()
8984     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8985                           MachineMemOperand::MOLoad, 8, 8);
8986
8987   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8988   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8989   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8990                                          array_lengthof(Ops), MVT::i64, MMO);
8991
8992   APInt FF(32, 0x5F800000ULL);
8993
8994   // Check whether the sign bit is set.
8995   SDValue SignSet = DAG.getSetCC(dl,
8996                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8997                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8998                                  ISD::SETLT);
8999
9000   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9001   SDValue FudgePtr = DAG.getConstantPool(
9002                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9003                                          getPointerTy());
9004
9005   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9006   SDValue Zero = DAG.getIntPtrConstant(0);
9007   SDValue Four = DAG.getIntPtrConstant(4);
9008   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9009                                Zero, Four);
9010   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9011
9012   // Load the value out, extending it from f32 to f80.
9013   // FIXME: Avoid the extend by constructing the right constant pool?
9014   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9015                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9016                                  MVT::f32, false, false, 4);
9017   // Extend everything to 80 bits to force it to be done on x87.
9018   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9019   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9020 }
9021
9022 std::pair<SDValue,SDValue>
9023 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9024                                     bool IsSigned, bool IsReplace) const {
9025   SDLoc DL(Op);
9026
9027   EVT DstTy = Op.getValueType();
9028
9029   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9030     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9031     DstTy = MVT::i64;
9032   }
9033
9034   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9035          DstTy.getSimpleVT() >= MVT::i16 &&
9036          "Unknown FP_TO_INT to lower!");
9037
9038   // These are really Legal.
9039   if (DstTy == MVT::i32 &&
9040       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9041     return std::make_pair(SDValue(), SDValue());
9042   if (Subtarget->is64Bit() &&
9043       DstTy == MVT::i64 &&
9044       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9045     return std::make_pair(SDValue(), SDValue());
9046
9047   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9048   // stack slot, or into the FTOL runtime function.
9049   MachineFunction &MF = DAG.getMachineFunction();
9050   unsigned MemSize = DstTy.getSizeInBits()/8;
9051   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9052   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9053
9054   unsigned Opc;
9055   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9056     Opc = X86ISD::WIN_FTOL;
9057   else
9058     switch (DstTy.getSimpleVT().SimpleTy) {
9059     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9060     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9061     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9062     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9063     }
9064
9065   SDValue Chain = DAG.getEntryNode();
9066   SDValue Value = Op.getOperand(0);
9067   EVT TheVT = Op.getOperand(0).getValueType();
9068   // FIXME This causes a redundant load/store if the SSE-class value is already
9069   // in memory, such as if it is on the callstack.
9070   if (isScalarFPTypeInSSEReg(TheVT)) {
9071     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9072     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9073                          MachinePointerInfo::getFixedStack(SSFI),
9074                          false, false, 0);
9075     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9076     SDValue Ops[] = {
9077       Chain, StackSlot, DAG.getValueType(TheVT)
9078     };
9079
9080     MachineMemOperand *MMO =
9081       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9082                               MachineMemOperand::MOLoad, MemSize, MemSize);
9083     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9084                                     array_lengthof(Ops), DstTy, MMO);
9085     Chain = Value.getValue(1);
9086     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9087     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9088   }
9089
9090   MachineMemOperand *MMO =
9091     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9092                             MachineMemOperand::MOStore, MemSize, MemSize);
9093
9094   if (Opc != X86ISD::WIN_FTOL) {
9095     // Build the FP_TO_INT*_IN_MEM
9096     SDValue Ops[] = { Chain, Value, StackSlot };
9097     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9098                                            Ops, array_lengthof(Ops), DstTy,
9099                                            MMO);
9100     return std::make_pair(FIST, StackSlot);
9101   } else {
9102     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9103       DAG.getVTList(MVT::Other, MVT::Glue),
9104       Chain, Value);
9105     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9106       MVT::i32, ftol.getValue(1));
9107     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9108       MVT::i32, eax.getValue(2));
9109     SDValue Ops[] = { eax, edx };
9110     SDValue pair = IsReplace
9111       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9112       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9113     return std::make_pair(pair, SDValue());
9114   }
9115 }
9116
9117 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9118                               const X86Subtarget *Subtarget) {
9119   MVT VT = Op->getSimpleValueType(0);
9120   SDValue In = Op->getOperand(0);
9121   MVT InVT = In.getSimpleValueType();
9122   SDLoc dl(Op);
9123
9124   // Optimize vectors in AVX mode:
9125   //
9126   //   v8i16 -> v8i32
9127   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9128   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9129   //   Concat upper and lower parts.
9130   //
9131   //   v4i32 -> v4i64
9132   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9133   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9134   //   Concat upper and lower parts.
9135   //
9136
9137   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9138       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9139       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9140     return SDValue();
9141
9142   if (Subtarget->hasInt256())
9143     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9144
9145   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9146   SDValue Undef = DAG.getUNDEF(InVT);
9147   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9148   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9149   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9150
9151   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9152                              VT.getVectorNumElements()/2);
9153
9154   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9155   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9156
9157   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9158 }
9159
9160 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9161                                         SelectionDAG &DAG) {
9162   MVT VT = Op->getSimpleValueType(0);
9163   SDValue In = Op->getOperand(0);
9164   MVT InVT = In.getSimpleValueType();
9165   SDLoc DL(Op);
9166   unsigned int NumElts = VT.getVectorNumElements();
9167   if (NumElts != 8 && NumElts != 16)
9168     return SDValue();
9169
9170   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9171     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9172
9173   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9175   // Now we have only mask extension
9176   assert(InVT.getVectorElementType() == MVT::i1);
9177   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9178   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9179   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9180   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9181   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9182                            MachinePointerInfo::getConstantPool(),
9183                            false, false, false, Alignment);
9184
9185   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9186   if (VT.is512BitVector())
9187     return Brcst;
9188   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9189 }
9190
9191 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9192                                SelectionDAG &DAG) {
9193   if (Subtarget->hasFp256()) {
9194     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9195     if (Res.getNode())
9196       return Res;
9197   }
9198
9199   return SDValue();
9200 }
9201
9202 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9203                                 SelectionDAG &DAG) {
9204   SDLoc DL(Op);
9205   MVT VT = Op.getSimpleValueType();
9206   SDValue In = Op.getOperand(0);
9207   MVT SVT = In.getSimpleValueType();
9208
9209   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9210     return LowerZERO_EXTEND_AVX512(Op, DAG);
9211
9212   if (Subtarget->hasFp256()) {
9213     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9214     if (Res.getNode())
9215       return Res;
9216   }
9217
9218   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9219          VT.getVectorNumElements() != SVT.getVectorNumElements());
9220   return SDValue();
9221 }
9222
9223 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9224   SDLoc DL(Op);
9225   MVT VT = Op.getSimpleValueType();
9226   SDValue In = Op.getOperand(0);
9227   MVT InVT = In.getSimpleValueType();
9228
9229   if (VT == MVT::i1) {
9230     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9231            "Invalid scalar TRUNCATE operation");
9232     if (InVT == MVT::i32)
9233       return SDValue();
9234     if (InVT.getSizeInBits() == 64)
9235       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9236     else if (InVT.getSizeInBits() < 32)
9237       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9238     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9239   }
9240   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9241          "Invalid TRUNCATE operation");
9242
9243   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9244     if (VT.getVectorElementType().getSizeInBits() >=8)
9245       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9246
9247     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9248     unsigned NumElts = InVT.getVectorNumElements();
9249     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9250     if (InVT.getSizeInBits() < 512) {
9251       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9252       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9253       InVT = ExtVT;
9254     }
9255     
9256     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9257     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9258     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9259     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9260     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9261                            MachinePointerInfo::getConstantPool(),
9262                            false, false, false, Alignment);
9263     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9264     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9265     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9266   }
9267
9268   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9269     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9270     if (Subtarget->hasInt256()) {
9271       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9272       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9273       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9274                                 ShufMask);
9275       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9276                          DAG.getIntPtrConstant(0));
9277     }
9278
9279     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9280                                DAG.getIntPtrConstant(0));
9281     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9282                                DAG.getIntPtrConstant(2));
9283     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9284     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9285     static const int ShufMask[] = {0, 2, 4, 6};
9286     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9287   }
9288
9289   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9290     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9291     if (Subtarget->hasInt256()) {
9292       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9293
9294       SmallVector<SDValue,32> pshufbMask;
9295       for (unsigned i = 0; i < 2; ++i) {
9296         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9297         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9298         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9299         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9300         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9301         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9302         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9303         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9304         for (unsigned j = 0; j < 8; ++j)
9305           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9306       }
9307       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9308                                &pshufbMask[0], 32);
9309       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9310       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9311
9312       static const int ShufMask[] = {0,  2,  -1,  -1};
9313       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9314                                 &ShufMask[0]);
9315       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9316                        DAG.getIntPtrConstant(0));
9317       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9318     }
9319
9320     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9321                                DAG.getIntPtrConstant(0));
9322
9323     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9324                                DAG.getIntPtrConstant(4));
9325
9326     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9327     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9328
9329     // The PSHUFB mask:
9330     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9331                                    -1, -1, -1, -1, -1, -1, -1, -1};
9332
9333     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9334     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9335     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9336
9337     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9338     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9339
9340     // The MOVLHPS Mask:
9341     static const int ShufMask2[] = {0, 1, 4, 5};
9342     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9343     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9344   }
9345
9346   // Handle truncation of V256 to V128 using shuffles.
9347   if (!VT.is128BitVector() || !InVT.is256BitVector())
9348     return SDValue();
9349
9350   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9351
9352   unsigned NumElems = VT.getVectorNumElements();
9353   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9354
9355   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9356   // Prepare truncation shuffle mask
9357   for (unsigned i = 0; i != NumElems; ++i)
9358     MaskVec[i] = i * 2;
9359   SDValue V = DAG.getVectorShuffle(NVT, DL,
9360                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9361                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9362   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9363                      DAG.getIntPtrConstant(0));
9364 }
9365
9366 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9367                                            SelectionDAG &DAG) const {
9368   assert(!Op.getSimpleValueType().isVector());
9369
9370   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9371     /*IsSigned=*/ true, /*IsReplace=*/ false);
9372   SDValue FIST = Vals.first, StackSlot = Vals.second;
9373   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9374   if (FIST.getNode() == 0) return Op;
9375
9376   if (StackSlot.getNode())
9377     // Load the result.
9378     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9379                        FIST, StackSlot, MachinePointerInfo(),
9380                        false, false, false, 0);
9381
9382   // The node is the result.
9383   return FIST;
9384 }
9385
9386 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9387                                            SelectionDAG &DAG) const {
9388   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9389     /*IsSigned=*/ false, /*IsReplace=*/ false);
9390   SDValue FIST = Vals.first, StackSlot = Vals.second;
9391   assert(FIST.getNode() && "Unexpected failure");
9392
9393   if (StackSlot.getNode())
9394     // Load the result.
9395     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9396                        FIST, StackSlot, MachinePointerInfo(),
9397                        false, false, false, 0);
9398
9399   // The node is the result.
9400   return FIST;
9401 }
9402
9403 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9404   SDLoc DL(Op);
9405   MVT VT = Op.getSimpleValueType();
9406   SDValue In = Op.getOperand(0);
9407   MVT SVT = In.getSimpleValueType();
9408
9409   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9410
9411   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9412                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9413                                  In, DAG.getUNDEF(SVT)));
9414 }
9415
9416 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9417   LLVMContext *Context = DAG.getContext();
9418   SDLoc dl(Op);
9419   MVT VT = Op.getSimpleValueType();
9420   MVT EltVT = VT;
9421   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9422   if (VT.isVector()) {
9423     EltVT = VT.getVectorElementType();
9424     NumElts = VT.getVectorNumElements();
9425   }
9426   Constant *C;
9427   if (EltVT == MVT::f64)
9428     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9429                                           APInt(64, ~(1ULL << 63))));
9430   else
9431     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9432                                           APInt(32, ~(1U << 31))));
9433   C = ConstantVector::getSplat(NumElts, C);
9434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9435   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9436   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9437   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9438                              MachinePointerInfo::getConstantPool(),
9439                              false, false, false, Alignment);
9440   if (VT.isVector()) {
9441     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9442     return DAG.getNode(ISD::BITCAST, dl, VT,
9443                        DAG.getNode(ISD::AND, dl, ANDVT,
9444                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9445                                                Op.getOperand(0)),
9446                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9447   }
9448   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9449 }
9450
9451 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9452   LLVMContext *Context = DAG.getContext();
9453   SDLoc dl(Op);
9454   MVT VT = Op.getSimpleValueType();
9455   MVT EltVT = VT;
9456   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9457   if (VT.isVector()) {
9458     EltVT = VT.getVectorElementType();
9459     NumElts = VT.getVectorNumElements();
9460   }
9461   Constant *C;
9462   if (EltVT == MVT::f64)
9463     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9464                                           APInt(64, 1ULL << 63)));
9465   else
9466     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9467                                           APInt(32, 1U << 31)));
9468   C = ConstantVector::getSplat(NumElts, C);
9469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9470   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9471   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9472   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9473                              MachinePointerInfo::getConstantPool(),
9474                              false, false, false, Alignment);
9475   if (VT.isVector()) {
9476     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9477     return DAG.getNode(ISD::BITCAST, dl, VT,
9478                        DAG.getNode(ISD::XOR, dl, XORVT,
9479                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9480                                                Op.getOperand(0)),
9481                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9482   }
9483
9484   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9485 }
9486
9487 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9489   LLVMContext *Context = DAG.getContext();
9490   SDValue Op0 = Op.getOperand(0);
9491   SDValue Op1 = Op.getOperand(1);
9492   SDLoc dl(Op);
9493   MVT VT = Op.getSimpleValueType();
9494   MVT SrcVT = Op1.getSimpleValueType();
9495
9496   // If second operand is smaller, extend it first.
9497   if (SrcVT.bitsLT(VT)) {
9498     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9499     SrcVT = VT;
9500   }
9501   // And if it is bigger, shrink it first.
9502   if (SrcVT.bitsGT(VT)) {
9503     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9504     SrcVT = VT;
9505   }
9506
9507   // At this point the operands and the result should have the same
9508   // type, and that won't be f80 since that is not custom lowered.
9509
9510   // First get the sign bit of second operand.
9511   SmallVector<Constant*,4> CV;
9512   if (SrcVT == MVT::f64) {
9513     const fltSemantics &Sem = APFloat::IEEEdouble;
9514     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9515     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9516   } else {
9517     const fltSemantics &Sem = APFloat::IEEEsingle;
9518     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9519     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9521     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9522   }
9523   Constant *C = ConstantVector::get(CV);
9524   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9525   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9526                               MachinePointerInfo::getConstantPool(),
9527                               false, false, false, 16);
9528   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9529
9530   // Shift sign bit right or left if the two operands have different types.
9531   if (SrcVT.bitsGT(VT)) {
9532     // Op0 is MVT::f32, Op1 is MVT::f64.
9533     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9534     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9535                           DAG.getConstant(32, MVT::i32));
9536     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9537     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9538                           DAG.getIntPtrConstant(0));
9539   }
9540
9541   // Clear first operand sign bit.
9542   CV.clear();
9543   if (VT == MVT::f64) {
9544     const fltSemantics &Sem = APFloat::IEEEdouble;
9545     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9546                                                    APInt(64, ~(1ULL << 63)))));
9547     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9548   } else {
9549     const fltSemantics &Sem = APFloat::IEEEsingle;
9550     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9551                                                    APInt(32, ~(1U << 31)))));
9552     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9553     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9554     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9555   }
9556   C = ConstantVector::get(CV);
9557   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9558   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9559                               MachinePointerInfo::getConstantPool(),
9560                               false, false, false, 16);
9561   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9562
9563   // Or the value with the sign bit.
9564   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9565 }
9566
9567 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9568   SDValue N0 = Op.getOperand(0);
9569   SDLoc dl(Op);
9570   MVT VT = Op.getSimpleValueType();
9571
9572   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9573   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9574                                   DAG.getConstant(1, VT));
9575   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9576 }
9577
9578 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9579 //
9580 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9581                                       SelectionDAG &DAG) {
9582   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9583
9584   if (!Subtarget->hasSSE41())
9585     return SDValue();
9586
9587   if (!Op->hasOneUse())
9588     return SDValue();
9589
9590   SDNode *N = Op.getNode();
9591   SDLoc DL(N);
9592
9593   SmallVector<SDValue, 8> Opnds;
9594   DenseMap<SDValue, unsigned> VecInMap;
9595   SmallVector<SDValue, 8> VecIns;
9596   EVT VT = MVT::Other;
9597
9598   // Recognize a special case where a vector is casted into wide integer to
9599   // test all 0s.
9600   Opnds.push_back(N->getOperand(0));
9601   Opnds.push_back(N->getOperand(1));
9602
9603   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9604     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9605     // BFS traverse all OR'd operands.
9606     if (I->getOpcode() == ISD::OR) {
9607       Opnds.push_back(I->getOperand(0));
9608       Opnds.push_back(I->getOperand(1));
9609       // Re-evaluate the number of nodes to be traversed.
9610       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9611       continue;
9612     }
9613
9614     // Quit if a non-EXTRACT_VECTOR_ELT
9615     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9616       return SDValue();
9617
9618     // Quit if without a constant index.
9619     SDValue Idx = I->getOperand(1);
9620     if (!isa<ConstantSDNode>(Idx))
9621       return SDValue();
9622
9623     SDValue ExtractedFromVec = I->getOperand(0);
9624     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9625     if (M == VecInMap.end()) {
9626       VT = ExtractedFromVec.getValueType();
9627       // Quit if not 128/256-bit vector.
9628       if (!VT.is128BitVector() && !VT.is256BitVector())
9629         return SDValue();
9630       // Quit if not the same type.
9631       if (VecInMap.begin() != VecInMap.end() &&
9632           VT != VecInMap.begin()->first.getValueType())
9633         return SDValue();
9634       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9635       VecIns.push_back(ExtractedFromVec);
9636     }
9637     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9638   }
9639
9640   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9641          "Not extracted from 128-/256-bit vector.");
9642
9643   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9644
9645   for (DenseMap<SDValue, unsigned>::const_iterator
9646         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9647     // Quit if not all elements are used.
9648     if (I->second != FullMask)
9649       return SDValue();
9650   }
9651
9652   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9653
9654   // Cast all vectors into TestVT for PTEST.
9655   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9656     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9657
9658   // If more than one full vectors are evaluated, OR them first before PTEST.
9659   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9660     // Each iteration will OR 2 nodes and append the result until there is only
9661     // 1 node left, i.e. the final OR'd value of all vectors.
9662     SDValue LHS = VecIns[Slot];
9663     SDValue RHS = VecIns[Slot + 1];
9664     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9665   }
9666
9667   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9668                      VecIns.back(), VecIns.back());
9669 }
9670
9671 /// Emit nodes that will be selected as "test Op0,Op0", or something
9672 /// equivalent.
9673 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9674                                     SelectionDAG &DAG) const {
9675   if (Op.getValueType() == MVT::i1)
9676     // KORTEST instruction should be selected
9677     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9678                        DAG.getConstant(0, Op.getValueType()));
9679
9680   // CF and OF aren't always set the way we want. Determine which
9681   // of these we need.
9682   bool NeedCF = false;
9683   bool NeedOF = false;
9684   switch (X86CC) {
9685   default: break;
9686   case X86::COND_A: case X86::COND_AE:
9687   case X86::COND_B: case X86::COND_BE:
9688     NeedCF = true;
9689     break;
9690   case X86::COND_G: case X86::COND_GE:
9691   case X86::COND_L: case X86::COND_LE:
9692   case X86::COND_O: case X86::COND_NO:
9693     NeedOF = true;
9694     break;
9695   }
9696   // See if we can use the EFLAGS value from the operand instead of
9697   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9698   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9699   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9700     // Emit a CMP with 0, which is the TEST pattern.
9701     //if (Op.getValueType() == MVT::i1)
9702     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9703     //                     DAG.getConstant(0, MVT::i1));
9704     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9705                        DAG.getConstant(0, Op.getValueType()));
9706   }
9707   unsigned Opcode = 0;
9708   unsigned NumOperands = 0;
9709
9710   // Truncate operations may prevent the merge of the SETCC instruction
9711   // and the arithmetic instruction before it. Attempt to truncate the operands
9712   // of the arithmetic instruction and use a reduced bit-width instruction.
9713   bool NeedTruncation = false;
9714   SDValue ArithOp = Op;
9715   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9716     SDValue Arith = Op->getOperand(0);
9717     // Both the trunc and the arithmetic op need to have one user each.
9718     if (Arith->hasOneUse())
9719       switch (Arith.getOpcode()) {
9720         default: break;
9721         case ISD::ADD:
9722         case ISD::SUB:
9723         case ISD::AND:
9724         case ISD::OR:
9725         case ISD::XOR: {
9726           NeedTruncation = true;
9727           ArithOp = Arith;
9728         }
9729       }
9730   }
9731
9732   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9733   // which may be the result of a CAST.  We use the variable 'Op', which is the
9734   // non-casted variable when we check for possible users.
9735   switch (ArithOp.getOpcode()) {
9736   case ISD::ADD:
9737     // Due to an isel shortcoming, be conservative if this add is likely to be
9738     // selected as part of a load-modify-store instruction. When the root node
9739     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9740     // uses of other nodes in the match, such as the ADD in this case. This
9741     // leads to the ADD being left around and reselected, with the result being
9742     // two adds in the output.  Alas, even if none our users are stores, that
9743     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9744     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9745     // climbing the DAG back to the root, and it doesn't seem to be worth the
9746     // effort.
9747     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9748          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9749       if (UI->getOpcode() != ISD::CopyToReg &&
9750           UI->getOpcode() != ISD::SETCC &&
9751           UI->getOpcode() != ISD::STORE)
9752         goto default_case;
9753
9754     if (ConstantSDNode *C =
9755         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9756       // An add of one will be selected as an INC.
9757       if (C->getAPIntValue() == 1) {
9758         Opcode = X86ISD::INC;
9759         NumOperands = 1;
9760         break;
9761       }
9762
9763       // An add of negative one (subtract of one) will be selected as a DEC.
9764       if (C->getAPIntValue().isAllOnesValue()) {
9765         Opcode = X86ISD::DEC;
9766         NumOperands = 1;
9767         break;
9768       }
9769     }
9770
9771     // Otherwise use a regular EFLAGS-setting add.
9772     Opcode = X86ISD::ADD;
9773     NumOperands = 2;
9774     break;
9775   case ISD::AND: {
9776     // If the primary and result isn't used, don't bother using X86ISD::AND,
9777     // because a TEST instruction will be better.
9778     bool NonFlagUse = false;
9779     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9780            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9781       SDNode *User = *UI;
9782       unsigned UOpNo = UI.getOperandNo();
9783       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9784         // Look pass truncate.
9785         UOpNo = User->use_begin().getOperandNo();
9786         User = *User->use_begin();
9787       }
9788
9789       if (User->getOpcode() != ISD::BRCOND &&
9790           User->getOpcode() != ISD::SETCC &&
9791           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9792         NonFlagUse = true;
9793         break;
9794       }
9795     }
9796
9797     if (!NonFlagUse)
9798       break;
9799   }
9800     // FALL THROUGH
9801   case ISD::SUB:
9802   case ISD::OR:
9803   case ISD::XOR:
9804     // Due to the ISEL shortcoming noted above, be conservative if this op is
9805     // likely to be selected as part of a load-modify-store instruction.
9806     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9807            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9808       if (UI->getOpcode() == ISD::STORE)
9809         goto default_case;
9810
9811     // Otherwise use a regular EFLAGS-setting instruction.
9812     switch (ArithOp.getOpcode()) {
9813     default: llvm_unreachable("unexpected operator!");
9814     case ISD::SUB: Opcode = X86ISD::SUB; break;
9815     case ISD::XOR: Opcode = X86ISD::XOR; break;
9816     case ISD::AND: Opcode = X86ISD::AND; break;
9817     case ISD::OR: {
9818       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9819         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9820         if (EFLAGS.getNode())
9821           return EFLAGS;
9822       }
9823       Opcode = X86ISD::OR;
9824       break;
9825     }
9826     }
9827
9828     NumOperands = 2;
9829     break;
9830   case X86ISD::ADD:
9831   case X86ISD::SUB:
9832   case X86ISD::INC:
9833   case X86ISD::DEC:
9834   case X86ISD::OR:
9835   case X86ISD::XOR:
9836   case X86ISD::AND:
9837     return SDValue(Op.getNode(), 1);
9838   default:
9839   default_case:
9840     break;
9841   }
9842
9843   // If we found that truncation is beneficial, perform the truncation and
9844   // update 'Op'.
9845   if (NeedTruncation) {
9846     EVT VT = Op.getValueType();
9847     SDValue WideVal = Op->getOperand(0);
9848     EVT WideVT = WideVal.getValueType();
9849     unsigned ConvertedOp = 0;
9850     // Use a target machine opcode to prevent further DAGCombine
9851     // optimizations that may separate the arithmetic operations
9852     // from the setcc node.
9853     switch (WideVal.getOpcode()) {
9854       default: break;
9855       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9856       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9857       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9858       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9859       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9860     }
9861
9862     if (ConvertedOp) {
9863       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9864       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9865         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9866         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9867         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9868       }
9869     }
9870   }
9871
9872   if (Opcode == 0)
9873     // Emit a CMP with 0, which is the TEST pattern.
9874     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9875                        DAG.getConstant(0, Op.getValueType()));
9876
9877   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9878   SmallVector<SDValue, 4> Ops;
9879   for (unsigned i = 0; i != NumOperands; ++i)
9880     Ops.push_back(Op.getOperand(i));
9881
9882   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9883   DAG.ReplaceAllUsesWith(Op, New);
9884   return SDValue(New.getNode(), 1);
9885 }
9886
9887 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9888 /// equivalent.
9889 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9890                                    SDLoc dl, SelectionDAG &DAG) const {
9891   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9892     if (C->getAPIntValue() == 0)
9893       return EmitTest(Op0, X86CC, dl, DAG);
9894
9895      if (Op0.getValueType() == MVT::i1)
9896        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9897   }
9898  
9899   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9900        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9901     // Do the comparison at i32 if it's smaller, besides the Atom case. 
9902     // This avoids subregister aliasing issues. Keep the smaller reference 
9903     // if we're optimizing for size, however, as that'll allow better folding 
9904     // of memory operations.
9905     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9906         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9907              AttributeSet::FunctionIndex, Attribute::MinSize) &&
9908         !Subtarget->isAtom()) {
9909       unsigned ExtendOp =
9910           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9911       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9912       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9913     }
9914     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9915     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9916     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9917                               Op0, Op1);
9918     return SDValue(Sub.getNode(), 1);
9919   }
9920   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9921 }
9922
9923 /// Convert a comparison if required by the subtarget.
9924 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9925                                                  SelectionDAG &DAG) const {
9926   // If the subtarget does not support the FUCOMI instruction, floating-point
9927   // comparisons have to be converted.
9928   if (Subtarget->hasCMov() ||
9929       Cmp.getOpcode() != X86ISD::CMP ||
9930       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9931       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9932     return Cmp;
9933
9934   // The instruction selector will select an FUCOM instruction instead of
9935   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9936   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9937   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9938   SDLoc dl(Cmp);
9939   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9940   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9941   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9942                             DAG.getConstant(8, MVT::i8));
9943   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9944   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9945 }
9946
9947 static bool isAllOnes(SDValue V) {
9948   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9949   return C && C->isAllOnesValue();
9950 }
9951
9952 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9953 /// if it's possible.
9954 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9955                                      SDLoc dl, SelectionDAG &DAG) const {
9956   SDValue Op0 = And.getOperand(0);
9957   SDValue Op1 = And.getOperand(1);
9958   if (Op0.getOpcode() == ISD::TRUNCATE)
9959     Op0 = Op0.getOperand(0);
9960   if (Op1.getOpcode() == ISD::TRUNCATE)
9961     Op1 = Op1.getOperand(0);
9962
9963   SDValue LHS, RHS;
9964   if (Op1.getOpcode() == ISD::SHL)
9965     std::swap(Op0, Op1);
9966   if (Op0.getOpcode() == ISD::SHL) {
9967     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9968       if (And00C->getZExtValue() == 1) {
9969         // If we looked past a truncate, check that it's only truncating away
9970         // known zeros.
9971         unsigned BitWidth = Op0.getValueSizeInBits();
9972         unsigned AndBitWidth = And.getValueSizeInBits();
9973         if (BitWidth > AndBitWidth) {
9974           APInt Zeros, Ones;
9975           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9976           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9977             return SDValue();
9978         }
9979         LHS = Op1;
9980         RHS = Op0.getOperand(1);
9981       }
9982   } else if (Op1.getOpcode() == ISD::Constant) {
9983     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9984     uint64_t AndRHSVal = AndRHS->getZExtValue();
9985     SDValue AndLHS = Op0;
9986
9987     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9988       LHS = AndLHS.getOperand(0);
9989       RHS = AndLHS.getOperand(1);
9990     }
9991
9992     // Use BT if the immediate can't be encoded in a TEST instruction.
9993     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9994       LHS = AndLHS;
9995       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9996     }
9997   }
9998
9999   if (LHS.getNode()) {
10000     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10001     // instruction.  Since the shift amount is in-range-or-undefined, we know
10002     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10003     // the encoding for the i16 version is larger than the i32 version.
10004     // Also promote i16 to i32 for performance / code size reason.
10005     if (LHS.getValueType() == MVT::i8 ||
10006         LHS.getValueType() == MVT::i16)
10007       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10008
10009     // If the operand types disagree, extend the shift amount to match.  Since
10010     // BT ignores high bits (like shifts) we can use anyextend.
10011     if (LHS.getValueType() != RHS.getValueType())
10012       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10013
10014     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10015     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10016     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10017                        DAG.getConstant(Cond, MVT::i8), BT);
10018   }
10019
10020   return SDValue();
10021 }
10022
10023 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10024 /// mask CMPs.
10025 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10026                               SDValue &Op1) {
10027   unsigned SSECC;
10028   bool Swap = false;
10029
10030   // SSE Condition code mapping:
10031   //  0 - EQ
10032   //  1 - LT
10033   //  2 - LE
10034   //  3 - UNORD
10035   //  4 - NEQ
10036   //  5 - NLT
10037   //  6 - NLE
10038   //  7 - ORD
10039   switch (SetCCOpcode) {
10040   default: llvm_unreachable("Unexpected SETCC condition");
10041   case ISD::SETOEQ:
10042   case ISD::SETEQ:  SSECC = 0; break;
10043   case ISD::SETOGT:
10044   case ISD::SETGT:  Swap = true; // Fallthrough
10045   case ISD::SETLT:
10046   case ISD::SETOLT: SSECC = 1; break;
10047   case ISD::SETOGE:
10048   case ISD::SETGE:  Swap = true; // Fallthrough
10049   case ISD::SETLE:
10050   case ISD::SETOLE: SSECC = 2; break;
10051   case ISD::SETUO:  SSECC = 3; break;
10052   case ISD::SETUNE:
10053   case ISD::SETNE:  SSECC = 4; break;
10054   case ISD::SETULE: Swap = true; // Fallthrough
10055   case ISD::SETUGE: SSECC = 5; break;
10056   case ISD::SETULT: Swap = true; // Fallthrough
10057   case ISD::SETUGT: SSECC = 6; break;
10058   case ISD::SETO:   SSECC = 7; break;
10059   case ISD::SETUEQ:
10060   case ISD::SETONE: SSECC = 8; break;
10061   }
10062   if (Swap)
10063     std::swap(Op0, Op1);
10064
10065   return SSECC;
10066 }
10067
10068 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10069 // ones, and then concatenate the result back.
10070 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10071   MVT VT = Op.getSimpleValueType();
10072
10073   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10074          "Unsupported value type for operation");
10075
10076   unsigned NumElems = VT.getVectorNumElements();
10077   SDLoc dl(Op);
10078   SDValue CC = Op.getOperand(2);
10079
10080   // Extract the LHS vectors
10081   SDValue LHS = Op.getOperand(0);
10082   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10083   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10084
10085   // Extract the RHS vectors
10086   SDValue RHS = Op.getOperand(1);
10087   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10088   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10089
10090   // Issue the operation on the smaller types and concatenate the result back
10091   MVT EltVT = VT.getVectorElementType();
10092   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10093   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10094                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10095                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10096 }
10097
10098 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10099                                      const X86Subtarget *Subtarget) {
10100   SDValue Op0 = Op.getOperand(0);
10101   SDValue Op1 = Op.getOperand(1);
10102   SDValue CC = Op.getOperand(2);
10103   MVT VT = Op.getSimpleValueType();
10104   SDLoc dl(Op);
10105
10106   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10107          Op.getValueType().getScalarType() == MVT::i1 &&
10108          "Cannot set masked compare for this operation");
10109
10110   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10111   unsigned  Opc = 0;
10112   bool Unsigned = false;
10113   bool Swap = false;
10114   unsigned SSECC;
10115   switch (SetCCOpcode) {
10116   default: llvm_unreachable("Unexpected SETCC condition");
10117   case ISD::SETNE:  SSECC = 4; break;
10118   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10119   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10120   case ISD::SETLT:  Swap = true; //fall-through
10121   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10122   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10123   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10124   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10125   case ISD::SETULE: Unsigned = true; //fall-through
10126   case ISD::SETLE:  SSECC = 2; break;
10127   }
10128
10129   if (Swap)
10130     std::swap(Op0, Op1);
10131   if (Opc)
10132     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10133   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10134   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10135                      DAG.getConstant(SSECC, MVT::i8));
10136 }
10137
10138 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10139 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10140 /// return an empty value.
10141 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10142 {
10143   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10144   if (!BV)
10145     return SDValue();
10146
10147   MVT VT = Op1.getSimpleValueType();
10148   MVT EVT = VT.getVectorElementType();
10149   unsigned n = VT.getVectorNumElements();
10150   SmallVector<SDValue, 8> ULTOp1;
10151
10152   for (unsigned i = 0; i < n; ++i) {
10153     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10154     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10155       return SDValue();
10156
10157     // Avoid underflow.
10158     APInt Val = Elt->getAPIntValue();
10159     if (Val == 0)
10160       return SDValue();
10161
10162     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10163   }
10164
10165   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10166 }
10167
10168 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10169                            SelectionDAG &DAG) {
10170   SDValue Op0 = Op.getOperand(0);
10171   SDValue Op1 = Op.getOperand(1);
10172   SDValue CC = Op.getOperand(2);
10173   MVT VT = Op.getSimpleValueType();
10174   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10175   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10176   SDLoc dl(Op);
10177
10178   if (isFP) {
10179 #ifndef NDEBUG
10180     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10181     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10182 #endif
10183
10184     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10185     unsigned Opc = X86ISD::CMPP;
10186     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10187       assert(VT.getVectorNumElements() <= 16);
10188       Opc = X86ISD::CMPM;
10189     }
10190     // In the two special cases we can't handle, emit two comparisons.
10191     if (SSECC == 8) {
10192       unsigned CC0, CC1;
10193       unsigned CombineOpc;
10194       if (SetCCOpcode == ISD::SETUEQ) {
10195         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10196       } else {
10197         assert(SetCCOpcode == ISD::SETONE);
10198         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10199       }
10200
10201       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10202                                  DAG.getConstant(CC0, MVT::i8));
10203       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10204                                  DAG.getConstant(CC1, MVT::i8));
10205       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10206     }
10207     // Handle all other FP comparisons here.
10208     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10209                        DAG.getConstant(SSECC, MVT::i8));
10210   }
10211
10212   // Break 256-bit integer vector compare into smaller ones.
10213   if (VT.is256BitVector() && !Subtarget->hasInt256())
10214     return Lower256IntVSETCC(Op, DAG);
10215
10216   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10217   EVT OpVT = Op1.getValueType();
10218   if (Subtarget->hasAVX512()) {
10219     if (Op1.getValueType().is512BitVector() ||
10220         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10221       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10222
10223     // In AVX-512 architecture setcc returns mask with i1 elements,
10224     // But there is no compare instruction for i8 and i16 elements.
10225     // We are not talking about 512-bit operands in this case, these
10226     // types are illegal.
10227     if (MaskResult &&
10228         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10229          OpVT.getVectorElementType().getSizeInBits() >= 8))
10230       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10231                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10232   }
10233
10234   // We are handling one of the integer comparisons here.  Since SSE only has
10235   // GT and EQ comparisons for integer, swapping operands and multiple
10236   // operations may be required for some comparisons.
10237   unsigned Opc;
10238   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10239   bool Subus = false;
10240
10241   switch (SetCCOpcode) {
10242   default: llvm_unreachable("Unexpected SETCC condition");
10243   case ISD::SETNE:  Invert = true;
10244   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10245   case ISD::SETLT:  Swap = true;
10246   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10247   case ISD::SETGE:  Swap = true;
10248   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10249                     Invert = true; break;
10250   case ISD::SETULT: Swap = true;
10251   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10252                     FlipSigns = true; break;
10253   case ISD::SETUGE: Swap = true;
10254   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10255                     FlipSigns = true; Invert = true; break;
10256   }
10257
10258   // Special case: Use min/max operations for SETULE/SETUGE
10259   MVT VET = VT.getVectorElementType();
10260   bool hasMinMax =
10261        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10262     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10263
10264   if (hasMinMax) {
10265     switch (SetCCOpcode) {
10266     default: break;
10267     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10268     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10269     }
10270
10271     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10272   }
10273
10274   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10275   if (!MinMax && hasSubus) {
10276     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10277     // Op0 u<= Op1:
10278     //   t = psubus Op0, Op1
10279     //   pcmpeq t, <0..0>
10280     switch (SetCCOpcode) {
10281     default: break;
10282     case ISD::SETULT: {
10283       // If the comparison is against a constant we can turn this into a
10284       // setule.  With psubus, setule does not require a swap.  This is
10285       // beneficial because the constant in the register is no longer
10286       // destructed as the destination so it can be hoisted out of a loop.
10287       // Only do this pre-AVX since vpcmp* is no longer destructive.
10288       if (Subtarget->hasAVX())
10289         break;
10290       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10291       if (ULEOp1.getNode()) {
10292         Op1 = ULEOp1;
10293         Subus = true; Invert = false; Swap = false;
10294       }
10295       break;
10296     }
10297     // Psubus is better than flip-sign because it requires no inversion.
10298     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10299     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10300     }
10301
10302     if (Subus) {
10303       Opc = X86ISD::SUBUS;
10304       FlipSigns = false;
10305     }
10306   }
10307
10308   if (Swap)
10309     std::swap(Op0, Op1);
10310
10311   // Check that the operation in question is available (most are plain SSE2,
10312   // but PCMPGTQ and PCMPEQQ have different requirements).
10313   if (VT == MVT::v2i64) {
10314     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10315       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10316
10317       // First cast everything to the right type.
10318       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10319       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10320
10321       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10322       // bits of the inputs before performing those operations. The lower
10323       // compare is always unsigned.
10324       SDValue SB;
10325       if (FlipSigns) {
10326         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10327       } else {
10328         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10329         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10330         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10331                          Sign, Zero, Sign, Zero);
10332       }
10333       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10334       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10335
10336       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10337       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10338       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10339
10340       // Create masks for only the low parts/high parts of the 64 bit integers.
10341       static const int MaskHi[] = { 1, 1, 3, 3 };
10342       static const int MaskLo[] = { 0, 0, 2, 2 };
10343       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10344       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10345       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10346
10347       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10348       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10349
10350       if (Invert)
10351         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10352
10353       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10354     }
10355
10356     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10357       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10358       // pcmpeqd + pshufd + pand.
10359       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10360
10361       // First cast everything to the right type.
10362       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10363       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10364
10365       // Do the compare.
10366       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10367
10368       // Make sure the lower and upper halves are both all-ones.
10369       static const int Mask[] = { 1, 0, 3, 2 };
10370       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10371       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10372
10373       if (Invert)
10374         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10375
10376       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10377     }
10378   }
10379
10380   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10381   // bits of the inputs before performing those operations.
10382   if (FlipSigns) {
10383     EVT EltVT = VT.getVectorElementType();
10384     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10385     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10386     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10387   }
10388
10389   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10390
10391   // If the logical-not of the result is required, perform that now.
10392   if (Invert)
10393     Result = DAG.getNOT(dl, Result, VT);
10394
10395   if (MinMax)
10396     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10397
10398   if (Subus)
10399     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10400                          getZeroVector(VT, Subtarget, DAG, dl));
10401
10402   return Result;
10403 }
10404
10405 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10406
10407   MVT VT = Op.getSimpleValueType();
10408
10409   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10410
10411   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10412          && "SetCC type must be 8-bit or 1-bit integer");
10413   SDValue Op0 = Op.getOperand(0);
10414   SDValue Op1 = Op.getOperand(1);
10415   SDLoc dl(Op);
10416   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10417
10418   // Optimize to BT if possible.
10419   // Lower (X & (1 << N)) == 0 to BT(X, N).
10420   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10421   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10422   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10423       Op1.getOpcode() == ISD::Constant &&
10424       cast<ConstantSDNode>(Op1)->isNullValue() &&
10425       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10426     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10427     if (NewSetCC.getNode())
10428       return NewSetCC;
10429   }
10430
10431   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10432   // these.
10433   if (Op1.getOpcode() == ISD::Constant &&
10434       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10435        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10436       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10437
10438     // If the input is a setcc, then reuse the input setcc or use a new one with
10439     // the inverted condition.
10440     if (Op0.getOpcode() == X86ISD::SETCC) {
10441       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10442       bool Invert = (CC == ISD::SETNE) ^
10443         cast<ConstantSDNode>(Op1)->isNullValue();
10444       if (!Invert)
10445         return Op0;
10446
10447       CCode = X86::GetOppositeBranchCondition(CCode);
10448       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10449                                   DAG.getConstant(CCode, MVT::i8),
10450                                   Op0.getOperand(1));
10451       if (VT == MVT::i1)
10452         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10453       return SetCC;
10454     }
10455   }
10456   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10457       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10458       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10459
10460     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10461     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10462   }
10463
10464   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10465   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10466   if (X86CC == X86::COND_INVALID)
10467     return SDValue();
10468
10469   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10470   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10471   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10472                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10473   if (VT == MVT::i1)
10474     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10475   return SetCC;
10476 }
10477
10478 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10479 static bool isX86LogicalCmp(SDValue Op) {
10480   unsigned Opc = Op.getNode()->getOpcode();
10481   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10482       Opc == X86ISD::SAHF)
10483     return true;
10484   if (Op.getResNo() == 1 &&
10485       (Opc == X86ISD::ADD ||
10486        Opc == X86ISD::SUB ||
10487        Opc == X86ISD::ADC ||
10488        Opc == X86ISD::SBB ||
10489        Opc == X86ISD::SMUL ||
10490        Opc == X86ISD::UMUL ||
10491        Opc == X86ISD::INC ||
10492        Opc == X86ISD::DEC ||
10493        Opc == X86ISD::OR ||
10494        Opc == X86ISD::XOR ||
10495        Opc == X86ISD::AND))
10496     return true;
10497
10498   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10499     return true;
10500
10501   return false;
10502 }
10503
10504 static bool isZero(SDValue V) {
10505   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10506   return C && C->isNullValue();
10507 }
10508
10509 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10510   if (V.getOpcode() != ISD::TRUNCATE)
10511     return false;
10512
10513   SDValue VOp0 = V.getOperand(0);
10514   unsigned InBits = VOp0.getValueSizeInBits();
10515   unsigned Bits = V.getValueSizeInBits();
10516   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10517 }
10518
10519 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10520   bool addTest = true;
10521   SDValue Cond  = Op.getOperand(0);
10522   SDValue Op1 = Op.getOperand(1);
10523   SDValue Op2 = Op.getOperand(2);
10524   SDLoc DL(Op);
10525   EVT VT = Op1.getValueType();
10526   SDValue CC;
10527
10528   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10529   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10530   // sequence later on.
10531   if (Cond.getOpcode() == ISD::SETCC &&
10532       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10533        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10534       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10535     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10536     int SSECC = translateX86FSETCC(
10537         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10538
10539     if (SSECC != 8) {
10540       if (Subtarget->hasAVX512()) {
10541         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10542                                   DAG.getConstant(SSECC, MVT::i8));
10543         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10544       }
10545       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10546                                 DAG.getConstant(SSECC, MVT::i8));
10547       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10548       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10549       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10550     }
10551   }
10552
10553   if (Cond.getOpcode() == ISD::SETCC) {
10554     SDValue NewCond = LowerSETCC(Cond, DAG);
10555     if (NewCond.getNode())
10556       Cond = NewCond;
10557   }
10558
10559   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10560   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10561   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10562   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10563   if (Cond.getOpcode() == X86ISD::SETCC &&
10564       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10565       isZero(Cond.getOperand(1).getOperand(1))) {
10566     SDValue Cmp = Cond.getOperand(1);
10567
10568     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10569
10570     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10571         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10572       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10573
10574       SDValue CmpOp0 = Cmp.getOperand(0);
10575       // Apply further optimizations for special cases
10576       // (select (x != 0), -1, 0) -> neg & sbb
10577       // (select (x == 0), 0, -1) -> neg & sbb
10578       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10579         if (YC->isNullValue() &&
10580             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10581           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10582           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10583                                     DAG.getConstant(0, CmpOp0.getValueType()),
10584                                     CmpOp0);
10585           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10586                                     DAG.getConstant(X86::COND_B, MVT::i8),
10587                                     SDValue(Neg.getNode(), 1));
10588           return Res;
10589         }
10590
10591       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10592                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10593       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10594
10595       SDValue Res =   // Res = 0 or -1.
10596         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10597                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10598
10599       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10600         Res = DAG.getNOT(DL, Res, Res.getValueType());
10601
10602       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10603       if (N2C == 0 || !N2C->isNullValue())
10604         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10605       return Res;
10606     }
10607   }
10608
10609   // Look past (and (setcc_carry (cmp ...)), 1).
10610   if (Cond.getOpcode() == ISD::AND &&
10611       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10612     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10613     if (C && C->getAPIntValue() == 1)
10614       Cond = Cond.getOperand(0);
10615   }
10616
10617   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10618   // setting operand in place of the X86ISD::SETCC.
10619   unsigned CondOpcode = Cond.getOpcode();
10620   if (CondOpcode == X86ISD::SETCC ||
10621       CondOpcode == X86ISD::SETCC_CARRY) {
10622     CC = Cond.getOperand(0);
10623
10624     SDValue Cmp = Cond.getOperand(1);
10625     unsigned Opc = Cmp.getOpcode();
10626     MVT VT = Op.getSimpleValueType();
10627
10628     bool IllegalFPCMov = false;
10629     if (VT.isFloatingPoint() && !VT.isVector() &&
10630         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10631       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10632
10633     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10634         Opc == X86ISD::BT) { // FIXME
10635       Cond = Cmp;
10636       addTest = false;
10637     }
10638   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10639              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10640              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10641               Cond.getOperand(0).getValueType() != MVT::i8)) {
10642     SDValue LHS = Cond.getOperand(0);
10643     SDValue RHS = Cond.getOperand(1);
10644     unsigned X86Opcode;
10645     unsigned X86Cond;
10646     SDVTList VTs;
10647     switch (CondOpcode) {
10648     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10649     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10650     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10651     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10652     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10653     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10654     default: llvm_unreachable("unexpected overflowing operator");
10655     }
10656     if (CondOpcode == ISD::UMULO)
10657       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10658                           MVT::i32);
10659     else
10660       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10661
10662     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10663
10664     if (CondOpcode == ISD::UMULO)
10665       Cond = X86Op.getValue(2);
10666     else
10667       Cond = X86Op.getValue(1);
10668
10669     CC = DAG.getConstant(X86Cond, MVT::i8);
10670     addTest = false;
10671   }
10672
10673   if (addTest) {
10674     // Look pass the truncate if the high bits are known zero.
10675     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10676         Cond = Cond.getOperand(0);
10677
10678     // We know the result of AND is compared against zero. Try to match
10679     // it to BT.
10680     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10681       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10682       if (NewSetCC.getNode()) {
10683         CC = NewSetCC.getOperand(0);
10684         Cond = NewSetCC.getOperand(1);
10685         addTest = false;
10686       }
10687     }
10688   }
10689
10690   if (addTest) {
10691     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10692     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10693   }
10694
10695   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10696   // a <  b ?  0 : -1 -> RES = setcc_carry
10697   // a >= b ? -1 :  0 -> RES = setcc_carry
10698   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10699   if (Cond.getOpcode() == X86ISD::SUB) {
10700     Cond = ConvertCmpIfNecessary(Cond, DAG);
10701     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10702
10703     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10704         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10705       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10706                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10707       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10708         return DAG.getNOT(DL, Res, Res.getValueType());
10709       return Res;
10710     }
10711   }
10712
10713   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10714   // widen the cmov and push the truncate through. This avoids introducing a new
10715   // branch during isel and doesn't add any extensions.
10716   if (Op.getValueType() == MVT::i8 &&
10717       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10718     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10719     if (T1.getValueType() == T2.getValueType() &&
10720         // Blacklist CopyFromReg to avoid partial register stalls.
10721         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10722       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10723       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10724       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10725     }
10726   }
10727
10728   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10729   // condition is true.
10730   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10731   SDValue Ops[] = { Op2, Op1, CC, Cond };
10732   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10733 }
10734
10735 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10736   MVT VT = Op->getSimpleValueType(0);
10737   SDValue In = Op->getOperand(0);
10738   MVT InVT = In.getSimpleValueType();
10739   SDLoc dl(Op);
10740
10741   unsigned int NumElts = VT.getVectorNumElements();
10742   if (NumElts != 8 && NumElts != 16)
10743     return SDValue();
10744
10745   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10746     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10747
10748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10749   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10750
10751   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10752   Constant *C = ConstantInt::get(*DAG.getContext(),
10753     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10754
10755   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10756   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10757   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10758                           MachinePointerInfo::getConstantPool(),
10759                           false, false, false, Alignment);
10760   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10761   if (VT.is512BitVector())
10762     return Brcst;
10763   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10764 }
10765
10766 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10767                                 SelectionDAG &DAG) {
10768   MVT VT = Op->getSimpleValueType(0);
10769   SDValue In = Op->getOperand(0);
10770   MVT InVT = In.getSimpleValueType();
10771   SDLoc dl(Op);
10772
10773   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10774     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10775
10776   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10777       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10778       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10779     return SDValue();
10780
10781   if (Subtarget->hasInt256())
10782     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10783
10784   // Optimize vectors in AVX mode
10785   // Sign extend  v8i16 to v8i32 and
10786   //              v4i32 to v4i64
10787   //
10788   // Divide input vector into two parts
10789   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10790   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10791   // concat the vectors to original VT
10792
10793   unsigned NumElems = InVT.getVectorNumElements();
10794   SDValue Undef = DAG.getUNDEF(InVT);
10795
10796   SmallVector<int,8> ShufMask1(NumElems, -1);
10797   for (unsigned i = 0; i != NumElems/2; ++i)
10798     ShufMask1[i] = i;
10799
10800   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10801
10802   SmallVector<int,8> ShufMask2(NumElems, -1);
10803   for (unsigned i = 0; i != NumElems/2; ++i)
10804     ShufMask2[i] = i + NumElems/2;
10805
10806   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10807
10808   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10809                                 VT.getVectorNumElements()/2);
10810
10811   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10812   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10813
10814   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10815 }
10816
10817 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10818 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10819 // from the AND / OR.
10820 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10821   Opc = Op.getOpcode();
10822   if (Opc != ISD::OR && Opc != ISD::AND)
10823     return false;
10824   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10825           Op.getOperand(0).hasOneUse() &&
10826           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10827           Op.getOperand(1).hasOneUse());
10828 }
10829
10830 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10831 // 1 and that the SETCC node has a single use.
10832 static bool isXor1OfSetCC(SDValue Op) {
10833   if (Op.getOpcode() != ISD::XOR)
10834     return false;
10835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10836   if (N1C && N1C->getAPIntValue() == 1) {
10837     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10838       Op.getOperand(0).hasOneUse();
10839   }
10840   return false;
10841 }
10842
10843 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10844   bool addTest = true;
10845   SDValue Chain = Op.getOperand(0);
10846   SDValue Cond  = Op.getOperand(1);
10847   SDValue Dest  = Op.getOperand(2);
10848   SDLoc dl(Op);
10849   SDValue CC;
10850   bool Inverted = false;
10851
10852   if (Cond.getOpcode() == ISD::SETCC) {
10853     // Check for setcc([su]{add,sub,mul}o == 0).
10854     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10855         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10856         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10857         Cond.getOperand(0).getResNo() == 1 &&
10858         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10859          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10860          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10861          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10862          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10863          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10864       Inverted = true;
10865       Cond = Cond.getOperand(0);
10866     } else {
10867       SDValue NewCond = LowerSETCC(Cond, DAG);
10868       if (NewCond.getNode())
10869         Cond = NewCond;
10870     }
10871   }
10872 #if 0
10873   // FIXME: LowerXALUO doesn't handle these!!
10874   else if (Cond.getOpcode() == X86ISD::ADD  ||
10875            Cond.getOpcode() == X86ISD::SUB  ||
10876            Cond.getOpcode() == X86ISD::SMUL ||
10877            Cond.getOpcode() == X86ISD::UMUL)
10878     Cond = LowerXALUO(Cond, DAG);
10879 #endif
10880
10881   // Look pass (and (setcc_carry (cmp ...)), 1).
10882   if (Cond.getOpcode() == ISD::AND &&
10883       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10884     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10885     if (C && C->getAPIntValue() == 1)
10886       Cond = Cond.getOperand(0);
10887   }
10888
10889   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10890   // setting operand in place of the X86ISD::SETCC.
10891   unsigned CondOpcode = Cond.getOpcode();
10892   if (CondOpcode == X86ISD::SETCC ||
10893       CondOpcode == X86ISD::SETCC_CARRY) {
10894     CC = Cond.getOperand(0);
10895
10896     SDValue Cmp = Cond.getOperand(1);
10897     unsigned Opc = Cmp.getOpcode();
10898     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10899     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10900       Cond = Cmp;
10901       addTest = false;
10902     } else {
10903       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10904       default: break;
10905       case X86::COND_O:
10906       case X86::COND_B:
10907         // These can only come from an arithmetic instruction with overflow,
10908         // e.g. SADDO, UADDO.
10909         Cond = Cond.getNode()->getOperand(1);
10910         addTest = false;
10911         break;
10912       }
10913     }
10914   }
10915   CondOpcode = Cond.getOpcode();
10916   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10917       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10918       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10919        Cond.getOperand(0).getValueType() != MVT::i8)) {
10920     SDValue LHS = Cond.getOperand(0);
10921     SDValue RHS = Cond.getOperand(1);
10922     unsigned X86Opcode;
10923     unsigned X86Cond;
10924     SDVTList VTs;
10925     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10926     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10927     // X86ISD::INC).
10928     switch (CondOpcode) {
10929     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10930     case ISD::SADDO:
10931       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10932         if (C->isOne()) {
10933           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10934           break;
10935         }
10936       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10937     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10938     case ISD::SSUBO:
10939       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10940         if (C->isOne()) {
10941           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10942           break;
10943         }
10944       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10945     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10946     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10947     default: llvm_unreachable("unexpected overflowing operator");
10948     }
10949     if (Inverted)
10950       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10951     if (CondOpcode == ISD::UMULO)
10952       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10953                           MVT::i32);
10954     else
10955       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10956
10957     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10958
10959     if (CondOpcode == ISD::UMULO)
10960       Cond = X86Op.getValue(2);
10961     else
10962       Cond = X86Op.getValue(1);
10963
10964     CC = DAG.getConstant(X86Cond, MVT::i8);
10965     addTest = false;
10966   } else {
10967     unsigned CondOpc;
10968     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10969       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10970       if (CondOpc == ISD::OR) {
10971         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10972         // two branches instead of an explicit OR instruction with a
10973         // separate test.
10974         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10975             isX86LogicalCmp(Cmp)) {
10976           CC = Cond.getOperand(0).getOperand(0);
10977           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10978                               Chain, Dest, CC, Cmp);
10979           CC = Cond.getOperand(1).getOperand(0);
10980           Cond = Cmp;
10981           addTest = false;
10982         }
10983       } else { // ISD::AND
10984         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10985         // two branches instead of an explicit AND instruction with a
10986         // separate test. However, we only do this if this block doesn't
10987         // have a fall-through edge, because this requires an explicit
10988         // jmp when the condition is false.
10989         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10990             isX86LogicalCmp(Cmp) &&
10991             Op.getNode()->hasOneUse()) {
10992           X86::CondCode CCode =
10993             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10994           CCode = X86::GetOppositeBranchCondition(CCode);
10995           CC = DAG.getConstant(CCode, MVT::i8);
10996           SDNode *User = *Op.getNode()->use_begin();
10997           // Look for an unconditional branch following this conditional branch.
10998           // We need this because we need to reverse the successors in order
10999           // to implement FCMP_OEQ.
11000           if (User->getOpcode() == ISD::BR) {
11001             SDValue FalseBB = User->getOperand(1);
11002             SDNode *NewBR =
11003               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11004             assert(NewBR == User);
11005             (void)NewBR;
11006             Dest = FalseBB;
11007
11008             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11009                                 Chain, Dest, CC, Cmp);
11010             X86::CondCode CCode =
11011               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11012             CCode = X86::GetOppositeBranchCondition(CCode);
11013             CC = DAG.getConstant(CCode, MVT::i8);
11014             Cond = Cmp;
11015             addTest = false;
11016           }
11017         }
11018       }
11019     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11020       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11021       // It should be transformed during dag combiner except when the condition
11022       // is set by a arithmetics with overflow node.
11023       X86::CondCode CCode =
11024         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11025       CCode = X86::GetOppositeBranchCondition(CCode);
11026       CC = DAG.getConstant(CCode, MVT::i8);
11027       Cond = Cond.getOperand(0).getOperand(1);
11028       addTest = false;
11029     } else if (Cond.getOpcode() == ISD::SETCC &&
11030                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11031       // For FCMP_OEQ, we can emit
11032       // two branches instead of an explicit AND instruction with a
11033       // separate test. However, we only do this if this block doesn't
11034       // have a fall-through edge, because this requires an explicit
11035       // jmp when the condition is false.
11036       if (Op.getNode()->hasOneUse()) {
11037         SDNode *User = *Op.getNode()->use_begin();
11038         // Look for an unconditional branch following this conditional branch.
11039         // We need this because we need to reverse the successors in order
11040         // to implement FCMP_OEQ.
11041         if (User->getOpcode() == ISD::BR) {
11042           SDValue FalseBB = User->getOperand(1);
11043           SDNode *NewBR =
11044             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11045           assert(NewBR == User);
11046           (void)NewBR;
11047           Dest = FalseBB;
11048
11049           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11050                                     Cond.getOperand(0), Cond.getOperand(1));
11051           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11052           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11053           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11054                               Chain, Dest, CC, Cmp);
11055           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11056           Cond = Cmp;
11057           addTest = false;
11058         }
11059       }
11060     } else if (Cond.getOpcode() == ISD::SETCC &&
11061                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11062       // For FCMP_UNE, we can emit
11063       // two branches instead of an explicit AND instruction with a
11064       // separate test. However, we only do this if this block doesn't
11065       // have a fall-through edge, because this requires an explicit
11066       // jmp when the condition is false.
11067       if (Op.getNode()->hasOneUse()) {
11068         SDNode *User = *Op.getNode()->use_begin();
11069         // Look for an unconditional branch following this conditional branch.
11070         // We need this because we need to reverse the successors in order
11071         // to implement FCMP_UNE.
11072         if (User->getOpcode() == ISD::BR) {
11073           SDValue FalseBB = User->getOperand(1);
11074           SDNode *NewBR =
11075             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11076           assert(NewBR == User);
11077           (void)NewBR;
11078
11079           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11080                                     Cond.getOperand(0), Cond.getOperand(1));
11081           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11082           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11083           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11084                               Chain, Dest, CC, Cmp);
11085           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11086           Cond = Cmp;
11087           addTest = false;
11088           Dest = FalseBB;
11089         }
11090       }
11091     }
11092   }
11093
11094   if (addTest) {
11095     // Look pass the truncate if the high bits are known zero.
11096     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11097         Cond = Cond.getOperand(0);
11098
11099     // We know the result of AND is compared against zero. Try to match
11100     // it to BT.
11101     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11102       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11103       if (NewSetCC.getNode()) {
11104         CC = NewSetCC.getOperand(0);
11105         Cond = NewSetCC.getOperand(1);
11106         addTest = false;
11107       }
11108     }
11109   }
11110
11111   if (addTest) {
11112     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11113     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11114   }
11115   Cond = ConvertCmpIfNecessary(Cond, DAG);
11116   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11117                      Chain, Dest, CC, Cond);
11118 }
11119
11120 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11121 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11122 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11123 // that the guard pages used by the OS virtual memory manager are allocated in
11124 // correct sequence.
11125 SDValue
11126 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11127                                            SelectionDAG &DAG) const {
11128   MachineFunction &MF = DAG.getMachineFunction();
11129   bool SplitStack = MF.shouldSplitStack();
11130   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11131                SplitStack;
11132   SDLoc dl(Op);
11133
11134   if (!Lower) {
11135     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11136     SDNode* Node = Op.getNode();
11137
11138     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11139     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11140         " not tell us which reg is the stack pointer!");
11141     EVT VT = Node->getValueType(0);
11142     SDValue Tmp1 = SDValue(Node, 0);
11143     SDValue Tmp2 = SDValue(Node, 1);
11144     SDValue Tmp3 = Node->getOperand(2);
11145     SDValue Chain = Tmp1.getOperand(0);
11146
11147     // Chain the dynamic stack allocation so that it doesn't modify the stack
11148     // pointer when other instructions are using the stack.
11149     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11150         SDLoc(Node));
11151
11152     SDValue Size = Tmp2.getOperand(1);
11153     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11154     Chain = SP.getValue(1);
11155     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11156     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11157     unsigned StackAlign = TFI.getStackAlignment();
11158     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11159     if (Align > StackAlign)
11160       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11161           DAG.getConstant(-(uint64_t)Align, VT));
11162     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11163
11164     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11165         DAG.getIntPtrConstant(0, true), SDValue(),
11166         SDLoc(Node));
11167
11168     SDValue Ops[2] = { Tmp1, Tmp2 };
11169     return DAG.getMergeValues(Ops, 2, dl);
11170   }
11171
11172   // Get the inputs.
11173   SDValue Chain = Op.getOperand(0);
11174   SDValue Size  = Op.getOperand(1);
11175   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11176   EVT VT = Op.getNode()->getValueType(0);
11177
11178   bool Is64Bit = Subtarget->is64Bit();
11179   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11180
11181   if (SplitStack) {
11182     MachineRegisterInfo &MRI = MF.getRegInfo();
11183
11184     if (Is64Bit) {
11185       // The 64 bit implementation of segmented stacks needs to clobber both r10
11186       // r11. This makes it impossible to use it along with nested parameters.
11187       const Function *F = MF.getFunction();
11188
11189       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11190            I != E; ++I)
11191         if (I->hasNestAttr())
11192           report_fatal_error("Cannot use segmented stacks with functions that "
11193                              "have nested arguments.");
11194     }
11195
11196     const TargetRegisterClass *AddrRegClass =
11197       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11198     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11199     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11200     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11201                                 DAG.getRegister(Vreg, SPTy));
11202     SDValue Ops1[2] = { Value, Chain };
11203     return DAG.getMergeValues(Ops1, 2, dl);
11204   } else {
11205     SDValue Flag;
11206     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11207
11208     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11209     Flag = Chain.getValue(1);
11210     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11211
11212     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11213
11214     const X86RegisterInfo *RegInfo =
11215       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11216     unsigned SPReg = RegInfo->getStackRegister();
11217     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11218     Chain = SP.getValue(1);
11219
11220     if (Align) {
11221       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11222                        DAG.getConstant(-(uint64_t)Align, VT));
11223       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11224     }
11225
11226     SDValue Ops1[2] = { SP, Chain };
11227     return DAG.getMergeValues(Ops1, 2, dl);
11228   }
11229 }
11230
11231 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11232   MachineFunction &MF = DAG.getMachineFunction();
11233   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11234
11235   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11236   SDLoc DL(Op);
11237
11238   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11239     // vastart just stores the address of the VarArgsFrameIndex slot into the
11240     // memory location argument.
11241     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11242                                    getPointerTy());
11243     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11244                         MachinePointerInfo(SV), false, false, 0);
11245   }
11246
11247   // __va_list_tag:
11248   //   gp_offset         (0 - 6 * 8)
11249   //   fp_offset         (48 - 48 + 8 * 16)
11250   //   overflow_arg_area (point to parameters coming in memory).
11251   //   reg_save_area
11252   SmallVector<SDValue, 8> MemOps;
11253   SDValue FIN = Op.getOperand(1);
11254   // Store gp_offset
11255   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11256                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11257                                                MVT::i32),
11258                                FIN, MachinePointerInfo(SV), false, false, 0);
11259   MemOps.push_back(Store);
11260
11261   // Store fp_offset
11262   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11263                     FIN, DAG.getIntPtrConstant(4));
11264   Store = DAG.getStore(Op.getOperand(0), DL,
11265                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11266                                        MVT::i32),
11267                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11268   MemOps.push_back(Store);
11269
11270   // Store ptr to overflow_arg_area
11271   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11272                     FIN, DAG.getIntPtrConstant(4));
11273   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11274                                     getPointerTy());
11275   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11276                        MachinePointerInfo(SV, 8),
11277                        false, false, 0);
11278   MemOps.push_back(Store);
11279
11280   // Store ptr to reg_save_area.
11281   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11282                     FIN, DAG.getIntPtrConstant(8));
11283   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11284                                     getPointerTy());
11285   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11286                        MachinePointerInfo(SV, 16), false, false, 0);
11287   MemOps.push_back(Store);
11288   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11289                      &MemOps[0], MemOps.size());
11290 }
11291
11292 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11293   assert(Subtarget->is64Bit() &&
11294          "LowerVAARG only handles 64-bit va_arg!");
11295   assert((Subtarget->isTargetLinux() ||
11296           Subtarget->isTargetDarwin()) &&
11297           "Unhandled target in LowerVAARG");
11298   assert(Op.getNode()->getNumOperands() == 4);
11299   SDValue Chain = Op.getOperand(0);
11300   SDValue SrcPtr = Op.getOperand(1);
11301   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11302   unsigned Align = Op.getConstantOperandVal(3);
11303   SDLoc dl(Op);
11304
11305   EVT ArgVT = Op.getNode()->getValueType(0);
11306   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11307   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11308   uint8_t ArgMode;
11309
11310   // Decide which area this value should be read from.
11311   // TODO: Implement the AMD64 ABI in its entirety. This simple
11312   // selection mechanism works only for the basic types.
11313   if (ArgVT == MVT::f80) {
11314     llvm_unreachable("va_arg for f80 not yet implemented");
11315   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11316     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11317   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11318     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11319   } else {
11320     llvm_unreachable("Unhandled argument type in LowerVAARG");
11321   }
11322
11323   if (ArgMode == 2) {
11324     // Sanity Check: Make sure using fp_offset makes sense.
11325     assert(!getTargetMachine().Options.UseSoftFloat &&
11326            !(DAG.getMachineFunction()
11327                 .getFunction()->getAttributes()
11328                 .hasAttribute(AttributeSet::FunctionIndex,
11329                               Attribute::NoImplicitFloat)) &&
11330            Subtarget->hasSSE1());
11331   }
11332
11333   // Insert VAARG_64 node into the DAG
11334   // VAARG_64 returns two values: Variable Argument Address, Chain
11335   SmallVector<SDValue, 11> InstOps;
11336   InstOps.push_back(Chain);
11337   InstOps.push_back(SrcPtr);
11338   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11339   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11340   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11341   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11342   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11343                                           VTs, &InstOps[0], InstOps.size(),
11344                                           MVT::i64,
11345                                           MachinePointerInfo(SV),
11346                                           /*Align=*/0,
11347                                           /*Volatile=*/false,
11348                                           /*ReadMem=*/true,
11349                                           /*WriteMem=*/true);
11350   Chain = VAARG.getValue(1);
11351
11352   // Load the next argument and return it
11353   return DAG.getLoad(ArgVT, dl,
11354                      Chain,
11355                      VAARG,
11356                      MachinePointerInfo(),
11357                      false, false, false, 0);
11358 }
11359
11360 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11361                            SelectionDAG &DAG) {
11362   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11363   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11364   SDValue Chain = Op.getOperand(0);
11365   SDValue DstPtr = Op.getOperand(1);
11366   SDValue SrcPtr = Op.getOperand(2);
11367   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11368   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11369   SDLoc DL(Op);
11370
11371   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11372                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11373                        false,
11374                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11375 }
11376
11377 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11378 // amount is a constant. Takes immediate version of shift as input.
11379 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11380                                           SDValue SrcOp, uint64_t ShiftAmt,
11381                                           SelectionDAG &DAG) {
11382   MVT ElementType = VT.getVectorElementType();
11383
11384   // Check for ShiftAmt >= element width
11385   if (ShiftAmt >= ElementType.getSizeInBits()) {
11386     if (Opc == X86ISD::VSRAI)
11387       ShiftAmt = ElementType.getSizeInBits() - 1;
11388     else
11389       return DAG.getConstant(0, VT);
11390   }
11391
11392   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11393          && "Unknown target vector shift-by-constant node");
11394
11395   // Fold this packed vector shift into a build vector if SrcOp is a
11396   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11397   if (VT == SrcOp.getSimpleValueType() &&
11398       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11399     SmallVector<SDValue, 8> Elts;
11400     unsigned NumElts = SrcOp->getNumOperands();
11401     ConstantSDNode *ND;
11402
11403     switch(Opc) {
11404     default: llvm_unreachable(0);
11405     case X86ISD::VSHLI:
11406       for (unsigned i=0; i!=NumElts; ++i) {
11407         SDValue CurrentOp = SrcOp->getOperand(i);
11408         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11409           Elts.push_back(CurrentOp);
11410           continue;
11411         }
11412         ND = cast<ConstantSDNode>(CurrentOp);
11413         const APInt &C = ND->getAPIntValue();
11414         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11415       }
11416       break;
11417     case X86ISD::VSRLI:
11418       for (unsigned i=0; i!=NumElts; ++i) {
11419         SDValue CurrentOp = SrcOp->getOperand(i);
11420         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11421           Elts.push_back(CurrentOp);
11422           continue;
11423         }
11424         ND = cast<ConstantSDNode>(CurrentOp);
11425         const APInt &C = ND->getAPIntValue();
11426         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11427       }
11428       break;
11429     case X86ISD::VSRAI:
11430       for (unsigned i=0; i!=NumElts; ++i) {
11431         SDValue CurrentOp = SrcOp->getOperand(i);
11432         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11433           Elts.push_back(CurrentOp);
11434           continue;
11435         }
11436         ND = cast<ConstantSDNode>(CurrentOp);
11437         const APInt &C = ND->getAPIntValue();
11438         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11439       }
11440       break;
11441     }
11442
11443     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11444   }
11445
11446   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11447 }
11448
11449 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11450 // may or may not be a constant. Takes immediate version of shift as input.
11451 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11452                                    SDValue SrcOp, SDValue ShAmt,
11453                                    SelectionDAG &DAG) {
11454   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11455
11456   // Catch shift-by-constant.
11457   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11458     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11459                                       CShAmt->getZExtValue(), DAG);
11460
11461   // Change opcode to non-immediate version
11462   switch (Opc) {
11463     default: llvm_unreachable("Unknown target vector shift node");
11464     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11465     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11466     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11467   }
11468
11469   // Need to build a vector containing shift amount
11470   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11471   SDValue ShOps[4];
11472   ShOps[0] = ShAmt;
11473   ShOps[1] = DAG.getConstant(0, MVT::i32);
11474   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11475   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11476
11477   // The return type has to be a 128-bit type with the same element
11478   // type as the input type.
11479   MVT EltVT = VT.getVectorElementType();
11480   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11481
11482   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11483   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11484 }
11485
11486 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11487   SDLoc dl(Op);
11488   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11489   switch (IntNo) {
11490   default: return SDValue();    // Don't custom lower most intrinsics.
11491   // Comparison intrinsics.
11492   case Intrinsic::x86_sse_comieq_ss:
11493   case Intrinsic::x86_sse_comilt_ss:
11494   case Intrinsic::x86_sse_comile_ss:
11495   case Intrinsic::x86_sse_comigt_ss:
11496   case Intrinsic::x86_sse_comige_ss:
11497   case Intrinsic::x86_sse_comineq_ss:
11498   case Intrinsic::x86_sse_ucomieq_ss:
11499   case Intrinsic::x86_sse_ucomilt_ss:
11500   case Intrinsic::x86_sse_ucomile_ss:
11501   case Intrinsic::x86_sse_ucomigt_ss:
11502   case Intrinsic::x86_sse_ucomige_ss:
11503   case Intrinsic::x86_sse_ucomineq_ss:
11504   case Intrinsic::x86_sse2_comieq_sd:
11505   case Intrinsic::x86_sse2_comilt_sd:
11506   case Intrinsic::x86_sse2_comile_sd:
11507   case Intrinsic::x86_sse2_comigt_sd:
11508   case Intrinsic::x86_sse2_comige_sd:
11509   case Intrinsic::x86_sse2_comineq_sd:
11510   case Intrinsic::x86_sse2_ucomieq_sd:
11511   case Intrinsic::x86_sse2_ucomilt_sd:
11512   case Intrinsic::x86_sse2_ucomile_sd:
11513   case Intrinsic::x86_sse2_ucomigt_sd:
11514   case Intrinsic::x86_sse2_ucomige_sd:
11515   case Intrinsic::x86_sse2_ucomineq_sd: {
11516     unsigned Opc;
11517     ISD::CondCode CC;
11518     switch (IntNo) {
11519     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11520     case Intrinsic::x86_sse_comieq_ss:
11521     case Intrinsic::x86_sse2_comieq_sd:
11522       Opc = X86ISD::COMI;
11523       CC = ISD::SETEQ;
11524       break;
11525     case Intrinsic::x86_sse_comilt_ss:
11526     case Intrinsic::x86_sse2_comilt_sd:
11527       Opc = X86ISD::COMI;
11528       CC = ISD::SETLT;
11529       break;
11530     case Intrinsic::x86_sse_comile_ss:
11531     case Intrinsic::x86_sse2_comile_sd:
11532       Opc = X86ISD::COMI;
11533       CC = ISD::SETLE;
11534       break;
11535     case Intrinsic::x86_sse_comigt_ss:
11536     case Intrinsic::x86_sse2_comigt_sd:
11537       Opc = X86ISD::COMI;
11538       CC = ISD::SETGT;
11539       break;
11540     case Intrinsic::x86_sse_comige_ss:
11541     case Intrinsic::x86_sse2_comige_sd:
11542       Opc = X86ISD::COMI;
11543       CC = ISD::SETGE;
11544       break;
11545     case Intrinsic::x86_sse_comineq_ss:
11546     case Intrinsic::x86_sse2_comineq_sd:
11547       Opc = X86ISD::COMI;
11548       CC = ISD::SETNE;
11549       break;
11550     case Intrinsic::x86_sse_ucomieq_ss:
11551     case Intrinsic::x86_sse2_ucomieq_sd:
11552       Opc = X86ISD::UCOMI;
11553       CC = ISD::SETEQ;
11554       break;
11555     case Intrinsic::x86_sse_ucomilt_ss:
11556     case Intrinsic::x86_sse2_ucomilt_sd:
11557       Opc = X86ISD::UCOMI;
11558       CC = ISD::SETLT;
11559       break;
11560     case Intrinsic::x86_sse_ucomile_ss:
11561     case Intrinsic::x86_sse2_ucomile_sd:
11562       Opc = X86ISD::UCOMI;
11563       CC = ISD::SETLE;
11564       break;
11565     case Intrinsic::x86_sse_ucomigt_ss:
11566     case Intrinsic::x86_sse2_ucomigt_sd:
11567       Opc = X86ISD::UCOMI;
11568       CC = ISD::SETGT;
11569       break;
11570     case Intrinsic::x86_sse_ucomige_ss:
11571     case Intrinsic::x86_sse2_ucomige_sd:
11572       Opc = X86ISD::UCOMI;
11573       CC = ISD::SETGE;
11574       break;
11575     case Intrinsic::x86_sse_ucomineq_ss:
11576     case Intrinsic::x86_sse2_ucomineq_sd:
11577       Opc = X86ISD::UCOMI;
11578       CC = ISD::SETNE;
11579       break;
11580     }
11581
11582     SDValue LHS = Op.getOperand(1);
11583     SDValue RHS = Op.getOperand(2);
11584     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11585     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11586     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11587     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11588                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11589     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11590   }
11591
11592   // Arithmetic intrinsics.
11593   case Intrinsic::x86_sse2_pmulu_dq:
11594   case Intrinsic::x86_avx2_pmulu_dq:
11595     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11596                        Op.getOperand(1), Op.getOperand(2));
11597
11598   // SSE2/AVX2 sub with unsigned saturation intrinsics
11599   case Intrinsic::x86_sse2_psubus_b:
11600   case Intrinsic::x86_sse2_psubus_w:
11601   case Intrinsic::x86_avx2_psubus_b:
11602   case Intrinsic::x86_avx2_psubus_w:
11603     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11604                        Op.getOperand(1), Op.getOperand(2));
11605
11606   // SSE3/AVX horizontal add/sub intrinsics
11607   case Intrinsic::x86_sse3_hadd_ps:
11608   case Intrinsic::x86_sse3_hadd_pd:
11609   case Intrinsic::x86_avx_hadd_ps_256:
11610   case Intrinsic::x86_avx_hadd_pd_256:
11611   case Intrinsic::x86_sse3_hsub_ps:
11612   case Intrinsic::x86_sse3_hsub_pd:
11613   case Intrinsic::x86_avx_hsub_ps_256:
11614   case Intrinsic::x86_avx_hsub_pd_256:
11615   case Intrinsic::x86_ssse3_phadd_w_128:
11616   case Intrinsic::x86_ssse3_phadd_d_128:
11617   case Intrinsic::x86_avx2_phadd_w:
11618   case Intrinsic::x86_avx2_phadd_d:
11619   case Intrinsic::x86_ssse3_phsub_w_128:
11620   case Intrinsic::x86_ssse3_phsub_d_128:
11621   case Intrinsic::x86_avx2_phsub_w:
11622   case Intrinsic::x86_avx2_phsub_d: {
11623     unsigned Opcode;
11624     switch (IntNo) {
11625     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11626     case Intrinsic::x86_sse3_hadd_ps:
11627     case Intrinsic::x86_sse3_hadd_pd:
11628     case Intrinsic::x86_avx_hadd_ps_256:
11629     case Intrinsic::x86_avx_hadd_pd_256:
11630       Opcode = X86ISD::FHADD;
11631       break;
11632     case Intrinsic::x86_sse3_hsub_ps:
11633     case Intrinsic::x86_sse3_hsub_pd:
11634     case Intrinsic::x86_avx_hsub_ps_256:
11635     case Intrinsic::x86_avx_hsub_pd_256:
11636       Opcode = X86ISD::FHSUB;
11637       break;
11638     case Intrinsic::x86_ssse3_phadd_w_128:
11639     case Intrinsic::x86_ssse3_phadd_d_128:
11640     case Intrinsic::x86_avx2_phadd_w:
11641     case Intrinsic::x86_avx2_phadd_d:
11642       Opcode = X86ISD::HADD;
11643       break;
11644     case Intrinsic::x86_ssse3_phsub_w_128:
11645     case Intrinsic::x86_ssse3_phsub_d_128:
11646     case Intrinsic::x86_avx2_phsub_w:
11647     case Intrinsic::x86_avx2_phsub_d:
11648       Opcode = X86ISD::HSUB;
11649       break;
11650     }
11651     return DAG.getNode(Opcode, dl, Op.getValueType(),
11652                        Op.getOperand(1), Op.getOperand(2));
11653   }
11654
11655   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11656   case Intrinsic::x86_sse2_pmaxu_b:
11657   case Intrinsic::x86_sse41_pmaxuw:
11658   case Intrinsic::x86_sse41_pmaxud:
11659   case Intrinsic::x86_avx2_pmaxu_b:
11660   case Intrinsic::x86_avx2_pmaxu_w:
11661   case Intrinsic::x86_avx2_pmaxu_d:
11662   case Intrinsic::x86_sse2_pminu_b:
11663   case Intrinsic::x86_sse41_pminuw:
11664   case Intrinsic::x86_sse41_pminud:
11665   case Intrinsic::x86_avx2_pminu_b:
11666   case Intrinsic::x86_avx2_pminu_w:
11667   case Intrinsic::x86_avx2_pminu_d:
11668   case Intrinsic::x86_sse41_pmaxsb:
11669   case Intrinsic::x86_sse2_pmaxs_w:
11670   case Intrinsic::x86_sse41_pmaxsd:
11671   case Intrinsic::x86_avx2_pmaxs_b:
11672   case Intrinsic::x86_avx2_pmaxs_w:
11673   case Intrinsic::x86_avx2_pmaxs_d:
11674   case Intrinsic::x86_sse41_pminsb:
11675   case Intrinsic::x86_sse2_pmins_w:
11676   case Intrinsic::x86_sse41_pminsd:
11677   case Intrinsic::x86_avx2_pmins_b:
11678   case Intrinsic::x86_avx2_pmins_w:
11679   case Intrinsic::x86_avx2_pmins_d: {
11680     unsigned Opcode;
11681     switch (IntNo) {
11682     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11683     case Intrinsic::x86_sse2_pmaxu_b:
11684     case Intrinsic::x86_sse41_pmaxuw:
11685     case Intrinsic::x86_sse41_pmaxud:
11686     case Intrinsic::x86_avx2_pmaxu_b:
11687     case Intrinsic::x86_avx2_pmaxu_w:
11688     case Intrinsic::x86_avx2_pmaxu_d:
11689       Opcode = X86ISD::UMAX;
11690       break;
11691     case Intrinsic::x86_sse2_pminu_b:
11692     case Intrinsic::x86_sse41_pminuw:
11693     case Intrinsic::x86_sse41_pminud:
11694     case Intrinsic::x86_avx2_pminu_b:
11695     case Intrinsic::x86_avx2_pminu_w:
11696     case Intrinsic::x86_avx2_pminu_d:
11697       Opcode = X86ISD::UMIN;
11698       break;
11699     case Intrinsic::x86_sse41_pmaxsb:
11700     case Intrinsic::x86_sse2_pmaxs_w:
11701     case Intrinsic::x86_sse41_pmaxsd:
11702     case Intrinsic::x86_avx2_pmaxs_b:
11703     case Intrinsic::x86_avx2_pmaxs_w:
11704     case Intrinsic::x86_avx2_pmaxs_d:
11705       Opcode = X86ISD::SMAX;
11706       break;
11707     case Intrinsic::x86_sse41_pminsb:
11708     case Intrinsic::x86_sse2_pmins_w:
11709     case Intrinsic::x86_sse41_pminsd:
11710     case Intrinsic::x86_avx2_pmins_b:
11711     case Intrinsic::x86_avx2_pmins_w:
11712     case Intrinsic::x86_avx2_pmins_d:
11713       Opcode = X86ISD::SMIN;
11714       break;
11715     }
11716     return DAG.getNode(Opcode, dl, Op.getValueType(),
11717                        Op.getOperand(1), Op.getOperand(2));
11718   }
11719
11720   // SSE/SSE2/AVX floating point max/min intrinsics.
11721   case Intrinsic::x86_sse_max_ps:
11722   case Intrinsic::x86_sse2_max_pd:
11723   case Intrinsic::x86_avx_max_ps_256:
11724   case Intrinsic::x86_avx_max_pd_256:
11725   case Intrinsic::x86_sse_min_ps:
11726   case Intrinsic::x86_sse2_min_pd:
11727   case Intrinsic::x86_avx_min_ps_256:
11728   case Intrinsic::x86_avx_min_pd_256: {
11729     unsigned Opcode;
11730     switch (IntNo) {
11731     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11732     case Intrinsic::x86_sse_max_ps:
11733     case Intrinsic::x86_sse2_max_pd:
11734     case Intrinsic::x86_avx_max_ps_256:
11735     case Intrinsic::x86_avx_max_pd_256:
11736       Opcode = X86ISD::FMAX;
11737       break;
11738     case Intrinsic::x86_sse_min_ps:
11739     case Intrinsic::x86_sse2_min_pd:
11740     case Intrinsic::x86_avx_min_ps_256:
11741     case Intrinsic::x86_avx_min_pd_256:
11742       Opcode = X86ISD::FMIN;
11743       break;
11744     }
11745     return DAG.getNode(Opcode, dl, Op.getValueType(),
11746                        Op.getOperand(1), Op.getOperand(2));
11747   }
11748
11749   // AVX2 variable shift intrinsics
11750   case Intrinsic::x86_avx2_psllv_d:
11751   case Intrinsic::x86_avx2_psllv_q:
11752   case Intrinsic::x86_avx2_psllv_d_256:
11753   case Intrinsic::x86_avx2_psllv_q_256:
11754   case Intrinsic::x86_avx2_psrlv_d:
11755   case Intrinsic::x86_avx2_psrlv_q:
11756   case Intrinsic::x86_avx2_psrlv_d_256:
11757   case Intrinsic::x86_avx2_psrlv_q_256:
11758   case Intrinsic::x86_avx2_psrav_d:
11759   case Intrinsic::x86_avx2_psrav_d_256: {
11760     unsigned Opcode;
11761     switch (IntNo) {
11762     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11763     case Intrinsic::x86_avx2_psllv_d:
11764     case Intrinsic::x86_avx2_psllv_q:
11765     case Intrinsic::x86_avx2_psllv_d_256:
11766     case Intrinsic::x86_avx2_psllv_q_256:
11767       Opcode = ISD::SHL;
11768       break;
11769     case Intrinsic::x86_avx2_psrlv_d:
11770     case Intrinsic::x86_avx2_psrlv_q:
11771     case Intrinsic::x86_avx2_psrlv_d_256:
11772     case Intrinsic::x86_avx2_psrlv_q_256:
11773       Opcode = ISD::SRL;
11774       break;
11775     case Intrinsic::x86_avx2_psrav_d:
11776     case Intrinsic::x86_avx2_psrav_d_256:
11777       Opcode = ISD::SRA;
11778       break;
11779     }
11780     return DAG.getNode(Opcode, dl, Op.getValueType(),
11781                        Op.getOperand(1), Op.getOperand(2));
11782   }
11783
11784   case Intrinsic::x86_ssse3_pshuf_b_128:
11785   case Intrinsic::x86_avx2_pshuf_b:
11786     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11787                        Op.getOperand(1), Op.getOperand(2));
11788
11789   case Intrinsic::x86_ssse3_psign_b_128:
11790   case Intrinsic::x86_ssse3_psign_w_128:
11791   case Intrinsic::x86_ssse3_psign_d_128:
11792   case Intrinsic::x86_avx2_psign_b:
11793   case Intrinsic::x86_avx2_psign_w:
11794   case Intrinsic::x86_avx2_psign_d:
11795     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11796                        Op.getOperand(1), Op.getOperand(2));
11797
11798   case Intrinsic::x86_sse41_insertps:
11799     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11800                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11801
11802   case Intrinsic::x86_avx_vperm2f128_ps_256:
11803   case Intrinsic::x86_avx_vperm2f128_pd_256:
11804   case Intrinsic::x86_avx_vperm2f128_si_256:
11805   case Intrinsic::x86_avx2_vperm2i128:
11806     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11807                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11808
11809   case Intrinsic::x86_avx2_permd:
11810   case Intrinsic::x86_avx2_permps:
11811     // Operands intentionally swapped. Mask is last operand to intrinsic,
11812     // but second operand for node/instruction.
11813     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11814                        Op.getOperand(2), Op.getOperand(1));
11815
11816   case Intrinsic::x86_sse_sqrt_ps:
11817   case Intrinsic::x86_sse2_sqrt_pd:
11818   case Intrinsic::x86_avx_sqrt_ps_256:
11819   case Intrinsic::x86_avx_sqrt_pd_256:
11820     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11821
11822   // ptest and testp intrinsics. The intrinsic these come from are designed to
11823   // return an integer value, not just an instruction so lower it to the ptest
11824   // or testp pattern and a setcc for the result.
11825   case Intrinsic::x86_sse41_ptestz:
11826   case Intrinsic::x86_sse41_ptestc:
11827   case Intrinsic::x86_sse41_ptestnzc:
11828   case Intrinsic::x86_avx_ptestz_256:
11829   case Intrinsic::x86_avx_ptestc_256:
11830   case Intrinsic::x86_avx_ptestnzc_256:
11831   case Intrinsic::x86_avx_vtestz_ps:
11832   case Intrinsic::x86_avx_vtestc_ps:
11833   case Intrinsic::x86_avx_vtestnzc_ps:
11834   case Intrinsic::x86_avx_vtestz_pd:
11835   case Intrinsic::x86_avx_vtestc_pd:
11836   case Intrinsic::x86_avx_vtestnzc_pd:
11837   case Intrinsic::x86_avx_vtestz_ps_256:
11838   case Intrinsic::x86_avx_vtestc_ps_256:
11839   case Intrinsic::x86_avx_vtestnzc_ps_256:
11840   case Intrinsic::x86_avx_vtestz_pd_256:
11841   case Intrinsic::x86_avx_vtestc_pd_256:
11842   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11843     bool IsTestPacked = false;
11844     unsigned X86CC;
11845     switch (IntNo) {
11846     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11847     case Intrinsic::x86_avx_vtestz_ps:
11848     case Intrinsic::x86_avx_vtestz_pd:
11849     case Intrinsic::x86_avx_vtestz_ps_256:
11850     case Intrinsic::x86_avx_vtestz_pd_256:
11851       IsTestPacked = true; // Fallthrough
11852     case Intrinsic::x86_sse41_ptestz:
11853     case Intrinsic::x86_avx_ptestz_256:
11854       // ZF = 1
11855       X86CC = X86::COND_E;
11856       break;
11857     case Intrinsic::x86_avx_vtestc_ps:
11858     case Intrinsic::x86_avx_vtestc_pd:
11859     case Intrinsic::x86_avx_vtestc_ps_256:
11860     case Intrinsic::x86_avx_vtestc_pd_256:
11861       IsTestPacked = true; // Fallthrough
11862     case Intrinsic::x86_sse41_ptestc:
11863     case Intrinsic::x86_avx_ptestc_256:
11864       // CF = 1
11865       X86CC = X86::COND_B;
11866       break;
11867     case Intrinsic::x86_avx_vtestnzc_ps:
11868     case Intrinsic::x86_avx_vtestnzc_pd:
11869     case Intrinsic::x86_avx_vtestnzc_ps_256:
11870     case Intrinsic::x86_avx_vtestnzc_pd_256:
11871       IsTestPacked = true; // Fallthrough
11872     case Intrinsic::x86_sse41_ptestnzc:
11873     case Intrinsic::x86_avx_ptestnzc_256:
11874       // ZF and CF = 0
11875       X86CC = X86::COND_A;
11876       break;
11877     }
11878
11879     SDValue LHS = Op.getOperand(1);
11880     SDValue RHS = Op.getOperand(2);
11881     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11882     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11883     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11884     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11885     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11886   }
11887   case Intrinsic::x86_avx512_kortestz_w:
11888   case Intrinsic::x86_avx512_kortestc_w: {
11889     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11890     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11891     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11892     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11893     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11894     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11895     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11896   }
11897
11898   // SSE/AVX shift intrinsics
11899   case Intrinsic::x86_sse2_psll_w:
11900   case Intrinsic::x86_sse2_psll_d:
11901   case Intrinsic::x86_sse2_psll_q:
11902   case Intrinsic::x86_avx2_psll_w:
11903   case Intrinsic::x86_avx2_psll_d:
11904   case Intrinsic::x86_avx2_psll_q:
11905   case Intrinsic::x86_sse2_psrl_w:
11906   case Intrinsic::x86_sse2_psrl_d:
11907   case Intrinsic::x86_sse2_psrl_q:
11908   case Intrinsic::x86_avx2_psrl_w:
11909   case Intrinsic::x86_avx2_psrl_d:
11910   case Intrinsic::x86_avx2_psrl_q:
11911   case Intrinsic::x86_sse2_psra_w:
11912   case Intrinsic::x86_sse2_psra_d:
11913   case Intrinsic::x86_avx2_psra_w:
11914   case Intrinsic::x86_avx2_psra_d: {
11915     unsigned Opcode;
11916     switch (IntNo) {
11917     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11918     case Intrinsic::x86_sse2_psll_w:
11919     case Intrinsic::x86_sse2_psll_d:
11920     case Intrinsic::x86_sse2_psll_q:
11921     case Intrinsic::x86_avx2_psll_w:
11922     case Intrinsic::x86_avx2_psll_d:
11923     case Intrinsic::x86_avx2_psll_q:
11924       Opcode = X86ISD::VSHL;
11925       break;
11926     case Intrinsic::x86_sse2_psrl_w:
11927     case Intrinsic::x86_sse2_psrl_d:
11928     case Intrinsic::x86_sse2_psrl_q:
11929     case Intrinsic::x86_avx2_psrl_w:
11930     case Intrinsic::x86_avx2_psrl_d:
11931     case Intrinsic::x86_avx2_psrl_q:
11932       Opcode = X86ISD::VSRL;
11933       break;
11934     case Intrinsic::x86_sse2_psra_w:
11935     case Intrinsic::x86_sse2_psra_d:
11936     case Intrinsic::x86_avx2_psra_w:
11937     case Intrinsic::x86_avx2_psra_d:
11938       Opcode = X86ISD::VSRA;
11939       break;
11940     }
11941     return DAG.getNode(Opcode, dl, Op.getValueType(),
11942                        Op.getOperand(1), Op.getOperand(2));
11943   }
11944
11945   // SSE/AVX immediate shift intrinsics
11946   case Intrinsic::x86_sse2_pslli_w:
11947   case Intrinsic::x86_sse2_pslli_d:
11948   case Intrinsic::x86_sse2_pslli_q:
11949   case Intrinsic::x86_avx2_pslli_w:
11950   case Intrinsic::x86_avx2_pslli_d:
11951   case Intrinsic::x86_avx2_pslli_q:
11952   case Intrinsic::x86_sse2_psrli_w:
11953   case Intrinsic::x86_sse2_psrli_d:
11954   case Intrinsic::x86_sse2_psrli_q:
11955   case Intrinsic::x86_avx2_psrli_w:
11956   case Intrinsic::x86_avx2_psrli_d:
11957   case Intrinsic::x86_avx2_psrli_q:
11958   case Intrinsic::x86_sse2_psrai_w:
11959   case Intrinsic::x86_sse2_psrai_d:
11960   case Intrinsic::x86_avx2_psrai_w:
11961   case Intrinsic::x86_avx2_psrai_d: {
11962     unsigned Opcode;
11963     switch (IntNo) {
11964     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11965     case Intrinsic::x86_sse2_pslli_w:
11966     case Intrinsic::x86_sse2_pslli_d:
11967     case Intrinsic::x86_sse2_pslli_q:
11968     case Intrinsic::x86_avx2_pslli_w:
11969     case Intrinsic::x86_avx2_pslli_d:
11970     case Intrinsic::x86_avx2_pslli_q:
11971       Opcode = X86ISD::VSHLI;
11972       break;
11973     case Intrinsic::x86_sse2_psrli_w:
11974     case Intrinsic::x86_sse2_psrli_d:
11975     case Intrinsic::x86_sse2_psrli_q:
11976     case Intrinsic::x86_avx2_psrli_w:
11977     case Intrinsic::x86_avx2_psrli_d:
11978     case Intrinsic::x86_avx2_psrli_q:
11979       Opcode = X86ISD::VSRLI;
11980       break;
11981     case Intrinsic::x86_sse2_psrai_w:
11982     case Intrinsic::x86_sse2_psrai_d:
11983     case Intrinsic::x86_avx2_psrai_w:
11984     case Intrinsic::x86_avx2_psrai_d:
11985       Opcode = X86ISD::VSRAI;
11986       break;
11987     }
11988     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11989                                Op.getOperand(1), Op.getOperand(2), DAG);
11990   }
11991
11992   case Intrinsic::x86_sse42_pcmpistria128:
11993   case Intrinsic::x86_sse42_pcmpestria128:
11994   case Intrinsic::x86_sse42_pcmpistric128:
11995   case Intrinsic::x86_sse42_pcmpestric128:
11996   case Intrinsic::x86_sse42_pcmpistrio128:
11997   case Intrinsic::x86_sse42_pcmpestrio128:
11998   case Intrinsic::x86_sse42_pcmpistris128:
11999   case Intrinsic::x86_sse42_pcmpestris128:
12000   case Intrinsic::x86_sse42_pcmpistriz128:
12001   case Intrinsic::x86_sse42_pcmpestriz128: {
12002     unsigned Opcode;
12003     unsigned X86CC;
12004     switch (IntNo) {
12005     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12006     case Intrinsic::x86_sse42_pcmpistria128:
12007       Opcode = X86ISD::PCMPISTRI;
12008       X86CC = X86::COND_A;
12009       break;
12010     case Intrinsic::x86_sse42_pcmpestria128:
12011       Opcode = X86ISD::PCMPESTRI;
12012       X86CC = X86::COND_A;
12013       break;
12014     case Intrinsic::x86_sse42_pcmpistric128:
12015       Opcode = X86ISD::PCMPISTRI;
12016       X86CC = X86::COND_B;
12017       break;
12018     case Intrinsic::x86_sse42_pcmpestric128:
12019       Opcode = X86ISD::PCMPESTRI;
12020       X86CC = X86::COND_B;
12021       break;
12022     case Intrinsic::x86_sse42_pcmpistrio128:
12023       Opcode = X86ISD::PCMPISTRI;
12024       X86CC = X86::COND_O;
12025       break;
12026     case Intrinsic::x86_sse42_pcmpestrio128:
12027       Opcode = X86ISD::PCMPESTRI;
12028       X86CC = X86::COND_O;
12029       break;
12030     case Intrinsic::x86_sse42_pcmpistris128:
12031       Opcode = X86ISD::PCMPISTRI;
12032       X86CC = X86::COND_S;
12033       break;
12034     case Intrinsic::x86_sse42_pcmpestris128:
12035       Opcode = X86ISD::PCMPESTRI;
12036       X86CC = X86::COND_S;
12037       break;
12038     case Intrinsic::x86_sse42_pcmpistriz128:
12039       Opcode = X86ISD::PCMPISTRI;
12040       X86CC = X86::COND_E;
12041       break;
12042     case Intrinsic::x86_sse42_pcmpestriz128:
12043       Opcode = X86ISD::PCMPESTRI;
12044       X86CC = X86::COND_E;
12045       break;
12046     }
12047     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12048     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12049     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12050     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12051                                 DAG.getConstant(X86CC, MVT::i8),
12052                                 SDValue(PCMP.getNode(), 1));
12053     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12054   }
12055
12056   case Intrinsic::x86_sse42_pcmpistri128:
12057   case Intrinsic::x86_sse42_pcmpestri128: {
12058     unsigned Opcode;
12059     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12060       Opcode = X86ISD::PCMPISTRI;
12061     else
12062       Opcode = X86ISD::PCMPESTRI;
12063
12064     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12065     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12066     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12067   }
12068   case Intrinsic::x86_fma_vfmadd_ps:
12069   case Intrinsic::x86_fma_vfmadd_pd:
12070   case Intrinsic::x86_fma_vfmsub_ps:
12071   case Intrinsic::x86_fma_vfmsub_pd:
12072   case Intrinsic::x86_fma_vfnmadd_ps:
12073   case Intrinsic::x86_fma_vfnmadd_pd:
12074   case Intrinsic::x86_fma_vfnmsub_ps:
12075   case Intrinsic::x86_fma_vfnmsub_pd:
12076   case Intrinsic::x86_fma_vfmaddsub_ps:
12077   case Intrinsic::x86_fma_vfmaddsub_pd:
12078   case Intrinsic::x86_fma_vfmsubadd_ps:
12079   case Intrinsic::x86_fma_vfmsubadd_pd:
12080   case Intrinsic::x86_fma_vfmadd_ps_256:
12081   case Intrinsic::x86_fma_vfmadd_pd_256:
12082   case Intrinsic::x86_fma_vfmsub_ps_256:
12083   case Intrinsic::x86_fma_vfmsub_pd_256:
12084   case Intrinsic::x86_fma_vfnmadd_ps_256:
12085   case Intrinsic::x86_fma_vfnmadd_pd_256:
12086   case Intrinsic::x86_fma_vfnmsub_ps_256:
12087   case Intrinsic::x86_fma_vfnmsub_pd_256:
12088   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12089   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12090   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12091   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12092   case Intrinsic::x86_fma_vfmadd_ps_512:
12093   case Intrinsic::x86_fma_vfmadd_pd_512:
12094   case Intrinsic::x86_fma_vfmsub_ps_512:
12095   case Intrinsic::x86_fma_vfmsub_pd_512:
12096   case Intrinsic::x86_fma_vfnmadd_ps_512:
12097   case Intrinsic::x86_fma_vfnmadd_pd_512:
12098   case Intrinsic::x86_fma_vfnmsub_ps_512:
12099   case Intrinsic::x86_fma_vfnmsub_pd_512:
12100   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12101   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12102   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12103   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12104     unsigned Opc;
12105     switch (IntNo) {
12106     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12107     case Intrinsic::x86_fma_vfmadd_ps:
12108     case Intrinsic::x86_fma_vfmadd_pd:
12109     case Intrinsic::x86_fma_vfmadd_ps_256:
12110     case Intrinsic::x86_fma_vfmadd_pd_256:
12111     case Intrinsic::x86_fma_vfmadd_ps_512:
12112     case Intrinsic::x86_fma_vfmadd_pd_512:
12113       Opc = X86ISD::FMADD;
12114       break;
12115     case Intrinsic::x86_fma_vfmsub_ps:
12116     case Intrinsic::x86_fma_vfmsub_pd:
12117     case Intrinsic::x86_fma_vfmsub_ps_256:
12118     case Intrinsic::x86_fma_vfmsub_pd_256:
12119     case Intrinsic::x86_fma_vfmsub_ps_512:
12120     case Intrinsic::x86_fma_vfmsub_pd_512:
12121       Opc = X86ISD::FMSUB;
12122       break;
12123     case Intrinsic::x86_fma_vfnmadd_ps:
12124     case Intrinsic::x86_fma_vfnmadd_pd:
12125     case Intrinsic::x86_fma_vfnmadd_ps_256:
12126     case Intrinsic::x86_fma_vfnmadd_pd_256:
12127     case Intrinsic::x86_fma_vfnmadd_ps_512:
12128     case Intrinsic::x86_fma_vfnmadd_pd_512:
12129       Opc = X86ISD::FNMADD;
12130       break;
12131     case Intrinsic::x86_fma_vfnmsub_ps:
12132     case Intrinsic::x86_fma_vfnmsub_pd:
12133     case Intrinsic::x86_fma_vfnmsub_ps_256:
12134     case Intrinsic::x86_fma_vfnmsub_pd_256:
12135     case Intrinsic::x86_fma_vfnmsub_ps_512:
12136     case Intrinsic::x86_fma_vfnmsub_pd_512:
12137       Opc = X86ISD::FNMSUB;
12138       break;
12139     case Intrinsic::x86_fma_vfmaddsub_ps:
12140     case Intrinsic::x86_fma_vfmaddsub_pd:
12141     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12142     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12143     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12144     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12145       Opc = X86ISD::FMADDSUB;
12146       break;
12147     case Intrinsic::x86_fma_vfmsubadd_ps:
12148     case Intrinsic::x86_fma_vfmsubadd_pd:
12149     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12150     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12151     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12152     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12153       Opc = X86ISD::FMSUBADD;
12154       break;
12155     }
12156
12157     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12158                        Op.getOperand(2), Op.getOperand(3));
12159   }
12160   }
12161 }
12162
12163 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12164                              SDValue Base, SDValue Index,
12165                              SDValue ScaleOp, SDValue Chain,
12166                              const X86Subtarget * Subtarget) {
12167   SDLoc dl(Op);
12168   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12169   assert(C && "Invalid scale type");
12170   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12171   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12172   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12173                              Index.getSimpleValueType().getVectorNumElements());
12174   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12175   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12176   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12177   SDValue Segment = DAG.getRegister(0, MVT::i32);
12178   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12179   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12180   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12181   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12182 }
12183
12184 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12185                               SDValue Src, SDValue Mask, SDValue Base,
12186                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12187                               const X86Subtarget * Subtarget) {
12188   SDLoc dl(Op);
12189   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12190   assert(C && "Invalid scale type");
12191   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12192   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12193                              Index.getSimpleValueType().getVectorNumElements());
12194   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12195   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12196   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12197   SDValue Segment = DAG.getRegister(0, MVT::i32);
12198   if (Src.getOpcode() == ISD::UNDEF)
12199     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12200   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12201   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12202   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12203   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12204 }
12205
12206 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12207                               SDValue Src, SDValue Base, SDValue Index,
12208                               SDValue ScaleOp, SDValue Chain) {
12209   SDLoc dl(Op);
12210   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12211   assert(C && "Invalid scale type");
12212   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12213   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12214   SDValue Segment = DAG.getRegister(0, MVT::i32);
12215   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12216                              Index.getSimpleValueType().getVectorNumElements());
12217   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12218   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12219   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12220   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12221   return SDValue(Res, 1);
12222 }
12223
12224 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12225                                SDValue Src, SDValue Mask, SDValue Base,
12226                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12227   SDLoc dl(Op);
12228   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12229   assert(C && "Invalid scale type");
12230   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12231   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12232   SDValue Segment = DAG.getRegister(0, MVT::i32);
12233   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12234                              Index.getSimpleValueType().getVectorNumElements());
12235   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12236   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12237   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12238   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12239   return SDValue(Res, 1);
12240 }
12241
12242 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12243                                       SelectionDAG &DAG) {
12244   SDLoc dl(Op);
12245   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12246   switch (IntNo) {
12247   default: return SDValue();    // Don't custom lower most intrinsics.
12248
12249   // RDRAND/RDSEED intrinsics.
12250   case Intrinsic::x86_rdrand_16:
12251   case Intrinsic::x86_rdrand_32:
12252   case Intrinsic::x86_rdrand_64:
12253   case Intrinsic::x86_rdseed_16:
12254   case Intrinsic::x86_rdseed_32:
12255   case Intrinsic::x86_rdseed_64: {
12256     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12257                        IntNo == Intrinsic::x86_rdseed_32 ||
12258                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12259                                                             X86ISD::RDRAND;
12260     // Emit the node with the right value type.
12261     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12262     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12263
12264     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12265     // Otherwise return the value from Rand, which is always 0, casted to i32.
12266     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12267                       DAG.getConstant(1, Op->getValueType(1)),
12268                       DAG.getConstant(X86::COND_B, MVT::i32),
12269                       SDValue(Result.getNode(), 1) };
12270     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12271                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12272                                   Ops, array_lengthof(Ops));
12273
12274     // Return { result, isValid, chain }.
12275     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12276                        SDValue(Result.getNode(), 2));
12277   }
12278   //int_gather(index, base, scale);
12279   case Intrinsic::x86_avx512_gather_qpd_512:
12280   case Intrinsic::x86_avx512_gather_qps_512:
12281   case Intrinsic::x86_avx512_gather_dpd_512:
12282   case Intrinsic::x86_avx512_gather_qpi_512:
12283   case Intrinsic::x86_avx512_gather_qpq_512:
12284   case Intrinsic::x86_avx512_gather_dpq_512:
12285   case Intrinsic::x86_avx512_gather_dps_512:
12286   case Intrinsic::x86_avx512_gather_dpi_512: {
12287     unsigned Opc;
12288     switch (IntNo) {
12289     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12290     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12291     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12292     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12293     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12294     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12295     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12296     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12297     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12298     }
12299     SDValue Chain = Op.getOperand(0);
12300     SDValue Index = Op.getOperand(2);
12301     SDValue Base  = Op.getOperand(3);
12302     SDValue Scale = Op.getOperand(4);
12303     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12304   }
12305   //int_gather_mask(v1, mask, index, base, scale);
12306   case Intrinsic::x86_avx512_gather_qps_mask_512:
12307   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12308   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12309   case Intrinsic::x86_avx512_gather_dps_mask_512:
12310   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12311   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12312   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12313   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12314     unsigned Opc;
12315     switch (IntNo) {
12316     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12317     case Intrinsic::x86_avx512_gather_qps_mask_512:
12318       Opc = X86::VGATHERQPSZrm; break;
12319     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12320       Opc = X86::VGATHERQPDZrm; break;
12321     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12322       Opc = X86::VGATHERDPDZrm; break;
12323     case Intrinsic::x86_avx512_gather_dps_mask_512:
12324       Opc = X86::VGATHERDPSZrm; break;
12325     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12326       Opc = X86::VPGATHERQDZrm; break;
12327     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12328       Opc = X86::VPGATHERQQZrm; break;
12329     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12330       Opc = X86::VPGATHERDDZrm; break;
12331     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12332       Opc = X86::VPGATHERDQZrm; break;
12333     }
12334     SDValue Chain = Op.getOperand(0);
12335     SDValue Src   = Op.getOperand(2);
12336     SDValue Mask  = Op.getOperand(3);
12337     SDValue Index = Op.getOperand(4);
12338     SDValue Base  = Op.getOperand(5);
12339     SDValue Scale = Op.getOperand(6);
12340     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12341                           Subtarget);
12342   }
12343   //int_scatter(base, index, v1, scale);
12344   case Intrinsic::x86_avx512_scatter_qpd_512:
12345   case Intrinsic::x86_avx512_scatter_qps_512:
12346   case Intrinsic::x86_avx512_scatter_dpd_512:
12347   case Intrinsic::x86_avx512_scatter_qpi_512:
12348   case Intrinsic::x86_avx512_scatter_qpq_512:
12349   case Intrinsic::x86_avx512_scatter_dpq_512:
12350   case Intrinsic::x86_avx512_scatter_dps_512:
12351   case Intrinsic::x86_avx512_scatter_dpi_512: {
12352     unsigned Opc;
12353     switch (IntNo) {
12354     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12355     case Intrinsic::x86_avx512_scatter_qpd_512:
12356       Opc = X86::VSCATTERQPDZmr; break;
12357     case Intrinsic::x86_avx512_scatter_qps_512:
12358       Opc = X86::VSCATTERQPSZmr; break;
12359     case Intrinsic::x86_avx512_scatter_dpd_512:
12360       Opc = X86::VSCATTERDPDZmr; break;
12361     case Intrinsic::x86_avx512_scatter_dps_512:
12362       Opc = X86::VSCATTERDPSZmr; break;
12363     case Intrinsic::x86_avx512_scatter_qpi_512:
12364       Opc = X86::VPSCATTERQDZmr; break;
12365     case Intrinsic::x86_avx512_scatter_qpq_512:
12366       Opc = X86::VPSCATTERQQZmr; break;
12367     case Intrinsic::x86_avx512_scatter_dpq_512:
12368       Opc = X86::VPSCATTERDQZmr; break;
12369     case Intrinsic::x86_avx512_scatter_dpi_512:
12370       Opc = X86::VPSCATTERDDZmr; break;
12371     }
12372     SDValue Chain = Op.getOperand(0);
12373     SDValue Base  = Op.getOperand(2);
12374     SDValue Index = Op.getOperand(3);
12375     SDValue Src   = Op.getOperand(4);
12376     SDValue Scale = Op.getOperand(5);
12377     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12378   }
12379   //int_scatter_mask(base, mask, index, v1, scale);
12380   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12381   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12382   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12383   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12384   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12385   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12386   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12387   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12388     unsigned Opc;
12389     switch (IntNo) {
12390     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12391     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12392       Opc = X86::VSCATTERQPDZmr; break;
12393     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12394       Opc = X86::VSCATTERQPSZmr; break;
12395     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12396       Opc = X86::VSCATTERDPDZmr; break;
12397     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12398       Opc = X86::VSCATTERDPSZmr; break;
12399     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12400       Opc = X86::VPSCATTERQDZmr; break;
12401     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12402       Opc = X86::VPSCATTERQQZmr; break;
12403     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12404       Opc = X86::VPSCATTERDQZmr; break;
12405     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12406       Opc = X86::VPSCATTERDDZmr; break;
12407     }
12408     SDValue Chain = Op.getOperand(0);
12409     SDValue Base  = Op.getOperand(2);
12410     SDValue Mask  = Op.getOperand(3);
12411     SDValue Index = Op.getOperand(4);
12412     SDValue Src   = Op.getOperand(5);
12413     SDValue Scale = Op.getOperand(6);
12414     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12415   }
12416   // XTEST intrinsics.
12417   case Intrinsic::x86_xtest: {
12418     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12419     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12420     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12421                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12422                                 InTrans);
12423     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12424     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12425                        Ret, SDValue(InTrans.getNode(), 1));
12426   }
12427   }
12428 }
12429
12430 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12431                                            SelectionDAG &DAG) const {
12432   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12433   MFI->setReturnAddressIsTaken(true);
12434
12435   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12436     return SDValue();
12437
12438   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12439   SDLoc dl(Op);
12440   EVT PtrVT = getPointerTy();
12441
12442   if (Depth > 0) {
12443     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12444     const X86RegisterInfo *RegInfo =
12445       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12446     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12447     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12448                        DAG.getNode(ISD::ADD, dl, PtrVT,
12449                                    FrameAddr, Offset),
12450                        MachinePointerInfo(), false, false, false, 0);
12451   }
12452
12453   // Just load the return address.
12454   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12455   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12456                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12457 }
12458
12459 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12460   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12461   MFI->setFrameAddressIsTaken(true);
12462
12463   EVT VT = Op.getValueType();
12464   SDLoc dl(Op);  // FIXME probably not meaningful
12465   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12466   const X86RegisterInfo *RegInfo =
12467     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12468   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12469   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12470           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12471          "Invalid Frame Register!");
12472   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12473   while (Depth--)
12474     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12475                             MachinePointerInfo(),
12476                             false, false, false, 0);
12477   return FrameAddr;
12478 }
12479
12480 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12481                                                      SelectionDAG &DAG) const {
12482   const X86RegisterInfo *RegInfo =
12483     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12484   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12485 }
12486
12487 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12488   SDValue Chain     = Op.getOperand(0);
12489   SDValue Offset    = Op.getOperand(1);
12490   SDValue Handler   = Op.getOperand(2);
12491   SDLoc dl      (Op);
12492
12493   EVT PtrVT = getPointerTy();
12494   const X86RegisterInfo *RegInfo =
12495     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12496   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12497   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12498           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12499          "Invalid Frame Register!");
12500   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12501   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12502
12503   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12504                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12505   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12506   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12507                        false, false, 0);
12508   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12509
12510   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12511                      DAG.getRegister(StoreAddrReg, PtrVT));
12512 }
12513
12514 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12515                                                SelectionDAG &DAG) const {
12516   SDLoc DL(Op);
12517   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12518                      DAG.getVTList(MVT::i32, MVT::Other),
12519                      Op.getOperand(0), Op.getOperand(1));
12520 }
12521
12522 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12523                                                 SelectionDAG &DAG) const {
12524   SDLoc DL(Op);
12525   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12526                      Op.getOperand(0), Op.getOperand(1));
12527 }
12528
12529 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12530   return Op.getOperand(0);
12531 }
12532
12533 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12534                                                 SelectionDAG &DAG) const {
12535   SDValue Root = Op.getOperand(0);
12536   SDValue Trmp = Op.getOperand(1); // trampoline
12537   SDValue FPtr = Op.getOperand(2); // nested function
12538   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12539   SDLoc dl (Op);
12540
12541   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12542   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12543
12544   if (Subtarget->is64Bit()) {
12545     SDValue OutChains[6];
12546
12547     // Large code-model.
12548     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12549     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12550
12551     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12552     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12553
12554     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12555
12556     // Load the pointer to the nested function into R11.
12557     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12558     SDValue Addr = Trmp;
12559     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12560                                 Addr, MachinePointerInfo(TrmpAddr),
12561                                 false, false, 0);
12562
12563     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12564                        DAG.getConstant(2, MVT::i64));
12565     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12566                                 MachinePointerInfo(TrmpAddr, 2),
12567                                 false, false, 2);
12568
12569     // Load the 'nest' parameter value into R10.
12570     // R10 is specified in X86CallingConv.td
12571     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12572     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12573                        DAG.getConstant(10, MVT::i64));
12574     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12575                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12576                                 false, false, 0);
12577
12578     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12579                        DAG.getConstant(12, MVT::i64));
12580     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12581                                 MachinePointerInfo(TrmpAddr, 12),
12582                                 false, false, 2);
12583
12584     // Jump to the nested function.
12585     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12586     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12587                        DAG.getConstant(20, MVT::i64));
12588     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12589                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12590                                 false, false, 0);
12591
12592     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12593     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12594                        DAG.getConstant(22, MVT::i64));
12595     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12596                                 MachinePointerInfo(TrmpAddr, 22),
12597                                 false, false, 0);
12598
12599     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12600   } else {
12601     const Function *Func =
12602       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12603     CallingConv::ID CC = Func->getCallingConv();
12604     unsigned NestReg;
12605
12606     switch (CC) {
12607     default:
12608       llvm_unreachable("Unsupported calling convention");
12609     case CallingConv::C:
12610     case CallingConv::X86_StdCall: {
12611       // Pass 'nest' parameter in ECX.
12612       // Must be kept in sync with X86CallingConv.td
12613       NestReg = X86::ECX;
12614
12615       // Check that ECX wasn't needed by an 'inreg' parameter.
12616       FunctionType *FTy = Func->getFunctionType();
12617       const AttributeSet &Attrs = Func->getAttributes();
12618
12619       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12620         unsigned InRegCount = 0;
12621         unsigned Idx = 1;
12622
12623         for (FunctionType::param_iterator I = FTy->param_begin(),
12624              E = FTy->param_end(); I != E; ++I, ++Idx)
12625           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12626             // FIXME: should only count parameters that are lowered to integers.
12627             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12628
12629         if (InRegCount > 2) {
12630           report_fatal_error("Nest register in use - reduce number of inreg"
12631                              " parameters!");
12632         }
12633       }
12634       break;
12635     }
12636     case CallingConv::X86_FastCall:
12637     case CallingConv::X86_ThisCall:
12638     case CallingConv::Fast:
12639       // Pass 'nest' parameter in EAX.
12640       // Must be kept in sync with X86CallingConv.td
12641       NestReg = X86::EAX;
12642       break;
12643     }
12644
12645     SDValue OutChains[4];
12646     SDValue Addr, Disp;
12647
12648     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12649                        DAG.getConstant(10, MVT::i32));
12650     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12651
12652     // This is storing the opcode for MOV32ri.
12653     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12654     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12655     OutChains[0] = DAG.getStore(Root, dl,
12656                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12657                                 Trmp, MachinePointerInfo(TrmpAddr),
12658                                 false, false, 0);
12659
12660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12661                        DAG.getConstant(1, MVT::i32));
12662     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12663                                 MachinePointerInfo(TrmpAddr, 1),
12664                                 false, false, 1);
12665
12666     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12668                        DAG.getConstant(5, MVT::i32));
12669     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12670                                 MachinePointerInfo(TrmpAddr, 5),
12671                                 false, false, 1);
12672
12673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12674                        DAG.getConstant(6, MVT::i32));
12675     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12676                                 MachinePointerInfo(TrmpAddr, 6),
12677                                 false, false, 1);
12678
12679     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12680   }
12681 }
12682
12683 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12684                                             SelectionDAG &DAG) const {
12685   /*
12686    The rounding mode is in bits 11:10 of FPSR, and has the following
12687    settings:
12688      00 Round to nearest
12689      01 Round to -inf
12690      10 Round to +inf
12691      11 Round to 0
12692
12693   FLT_ROUNDS, on the other hand, expects the following:
12694     -1 Undefined
12695      0 Round to 0
12696      1 Round to nearest
12697      2 Round to +inf
12698      3 Round to -inf
12699
12700   To perform the conversion, we do:
12701     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12702   */
12703
12704   MachineFunction &MF = DAG.getMachineFunction();
12705   const TargetMachine &TM = MF.getTarget();
12706   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12707   unsigned StackAlignment = TFI.getStackAlignment();
12708   MVT VT = Op.getSimpleValueType();
12709   SDLoc DL(Op);
12710
12711   // Save FP Control Word to stack slot
12712   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12713   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12714
12715   MachineMemOperand *MMO =
12716    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12717                            MachineMemOperand::MOStore, 2, 2);
12718
12719   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12720   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12721                                           DAG.getVTList(MVT::Other),
12722                                           Ops, array_lengthof(Ops), MVT::i16,
12723                                           MMO);
12724
12725   // Load FP Control Word from stack slot
12726   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12727                             MachinePointerInfo(), false, false, false, 0);
12728
12729   // Transform as necessary
12730   SDValue CWD1 =
12731     DAG.getNode(ISD::SRL, DL, MVT::i16,
12732                 DAG.getNode(ISD::AND, DL, MVT::i16,
12733                             CWD, DAG.getConstant(0x800, MVT::i16)),
12734                 DAG.getConstant(11, MVT::i8));
12735   SDValue CWD2 =
12736     DAG.getNode(ISD::SRL, DL, MVT::i16,
12737                 DAG.getNode(ISD::AND, DL, MVT::i16,
12738                             CWD, DAG.getConstant(0x400, MVT::i16)),
12739                 DAG.getConstant(9, MVT::i8));
12740
12741   SDValue RetVal =
12742     DAG.getNode(ISD::AND, DL, MVT::i16,
12743                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12744                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12745                             DAG.getConstant(1, MVT::i16)),
12746                 DAG.getConstant(3, MVT::i16));
12747
12748   return DAG.getNode((VT.getSizeInBits() < 16 ?
12749                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12750 }
12751
12752 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12753   MVT VT = Op.getSimpleValueType();
12754   EVT OpVT = VT;
12755   unsigned NumBits = VT.getSizeInBits();
12756   SDLoc dl(Op);
12757
12758   Op = Op.getOperand(0);
12759   if (VT == MVT::i8) {
12760     // Zero extend to i32 since there is not an i8 bsr.
12761     OpVT = MVT::i32;
12762     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12763   }
12764
12765   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12766   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12767   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12768
12769   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12770   SDValue Ops[] = {
12771     Op,
12772     DAG.getConstant(NumBits+NumBits-1, OpVT),
12773     DAG.getConstant(X86::COND_E, MVT::i8),
12774     Op.getValue(1)
12775   };
12776   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12777
12778   // Finally xor with NumBits-1.
12779   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12780
12781   if (VT == MVT::i8)
12782     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12783   return Op;
12784 }
12785
12786 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12787   MVT VT = Op.getSimpleValueType();
12788   EVT OpVT = VT;
12789   unsigned NumBits = VT.getSizeInBits();
12790   SDLoc dl(Op);
12791
12792   Op = Op.getOperand(0);
12793   if (VT == MVT::i8) {
12794     // Zero extend to i32 since there is not an i8 bsr.
12795     OpVT = MVT::i32;
12796     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12797   }
12798
12799   // Issue a bsr (scan bits in reverse).
12800   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12801   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12802
12803   // And xor with NumBits-1.
12804   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12805
12806   if (VT == MVT::i8)
12807     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12808   return Op;
12809 }
12810
12811 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12812   MVT VT = Op.getSimpleValueType();
12813   unsigned NumBits = VT.getSizeInBits();
12814   SDLoc dl(Op);
12815   Op = Op.getOperand(0);
12816
12817   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12818   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12819   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12820
12821   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12822   SDValue Ops[] = {
12823     Op,
12824     DAG.getConstant(NumBits, VT),
12825     DAG.getConstant(X86::COND_E, MVT::i8),
12826     Op.getValue(1)
12827   };
12828   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12829 }
12830
12831 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12832 // ones, and then concatenate the result back.
12833 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12834   MVT VT = Op.getSimpleValueType();
12835
12836   assert(VT.is256BitVector() && VT.isInteger() &&
12837          "Unsupported value type for operation");
12838
12839   unsigned NumElems = VT.getVectorNumElements();
12840   SDLoc dl(Op);
12841
12842   // Extract the LHS vectors
12843   SDValue LHS = Op.getOperand(0);
12844   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12845   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12846
12847   // Extract the RHS vectors
12848   SDValue RHS = Op.getOperand(1);
12849   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12850   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12851
12852   MVT EltVT = VT.getVectorElementType();
12853   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12854
12855   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12856                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12857                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12858 }
12859
12860 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12861   assert(Op.getSimpleValueType().is256BitVector() &&
12862          Op.getSimpleValueType().isInteger() &&
12863          "Only handle AVX 256-bit vector integer operation");
12864   return Lower256IntArith(Op, DAG);
12865 }
12866
12867 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12868   assert(Op.getSimpleValueType().is256BitVector() &&
12869          Op.getSimpleValueType().isInteger() &&
12870          "Only handle AVX 256-bit vector integer operation");
12871   return Lower256IntArith(Op, DAG);
12872 }
12873
12874 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12875                         SelectionDAG &DAG) {
12876   SDLoc dl(Op);
12877   MVT VT = Op.getSimpleValueType();
12878
12879   // Decompose 256-bit ops into smaller 128-bit ops.
12880   if (VT.is256BitVector() && !Subtarget->hasInt256())
12881     return Lower256IntArith(Op, DAG);
12882
12883   SDValue A = Op.getOperand(0);
12884   SDValue B = Op.getOperand(1);
12885
12886   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12887   if (VT == MVT::v4i32) {
12888     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12889            "Should not custom lower when pmuldq is available!");
12890
12891     // Extract the odd parts.
12892     static const int UnpackMask[] = { 1, -1, 3, -1 };
12893     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12894     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12895
12896     // Multiply the even parts.
12897     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12898     // Now multiply odd parts.
12899     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12900
12901     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12902     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12903
12904     // Merge the two vectors back together with a shuffle. This expands into 2
12905     // shuffles.
12906     static const int ShufMask[] = { 0, 4, 2, 6 };
12907     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12908   }
12909
12910   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12911          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12912
12913   //  Ahi = psrlqi(a, 32);
12914   //  Bhi = psrlqi(b, 32);
12915   //
12916   //  AloBlo = pmuludq(a, b);
12917   //  AloBhi = pmuludq(a, Bhi);
12918   //  AhiBlo = pmuludq(Ahi, b);
12919
12920   //  AloBhi = psllqi(AloBhi, 32);
12921   //  AhiBlo = psllqi(AhiBlo, 32);
12922   //  return AloBlo + AloBhi + AhiBlo;
12923
12924   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12925   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12926
12927   // Bit cast to 32-bit vectors for MULUDQ
12928   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12929                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12930   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12931   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12932   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12933   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12934
12935   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12936   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12937   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12938
12939   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12940   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12941
12942   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12943   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12944 }
12945
12946 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12947   MVT VT = Op.getSimpleValueType();
12948   MVT EltTy = VT.getVectorElementType();
12949   unsigned NumElts = VT.getVectorNumElements();
12950   SDValue N0 = Op.getOperand(0);
12951   SDLoc dl(Op);
12952
12953   // Lower sdiv X, pow2-const.
12954   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12955   if (!C)
12956     return SDValue();
12957
12958   APInt SplatValue, SplatUndef;
12959   unsigned SplatBitSize;
12960   bool HasAnyUndefs;
12961   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12962                           HasAnyUndefs) ||
12963       EltTy.getSizeInBits() < SplatBitSize)
12964     return SDValue();
12965
12966   if ((SplatValue != 0) &&
12967       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12968     unsigned Lg2 = SplatValue.countTrailingZeros();
12969     // Splat the sign bit.
12970     SmallVector<SDValue, 16> Sz(NumElts,
12971                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12972                                                 EltTy));
12973     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12974                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12975                                           NumElts));
12976     // Add (N0 < 0) ? abs2 - 1 : 0;
12977     SmallVector<SDValue, 16> Amt(NumElts,
12978                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12979                                                  EltTy));
12980     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12981                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12982                                           NumElts));
12983     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12984     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12985     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12986                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12987                                           NumElts));
12988
12989     // If we're dividing by a positive value, we're done.  Otherwise, we must
12990     // negate the result.
12991     if (SplatValue.isNonNegative())
12992       return SRA;
12993
12994     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12995     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12996     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12997   }
12998   return SDValue();
12999 }
13000
13001 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13002                                          const X86Subtarget *Subtarget) {
13003   MVT VT = Op.getSimpleValueType();
13004   SDLoc dl(Op);
13005   SDValue R = Op.getOperand(0);
13006   SDValue Amt = Op.getOperand(1);
13007
13008   // Optimize shl/srl/sra with constant shift amount.
13009   if (isSplatVector(Amt.getNode())) {
13010     SDValue SclrAmt = Amt->getOperand(0);
13011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13012       uint64_t ShiftAmt = C->getZExtValue();
13013
13014       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13015           (Subtarget->hasInt256() &&
13016            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13017           (Subtarget->hasAVX512() &&
13018            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13019         if (Op.getOpcode() == ISD::SHL)
13020           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13021                                             DAG);
13022         if (Op.getOpcode() == ISD::SRL)
13023           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13024                                             DAG);
13025         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13026           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13027                                             DAG);
13028       }
13029
13030       if (VT == MVT::v16i8) {
13031         if (Op.getOpcode() == ISD::SHL) {
13032           // Make a large shift.
13033           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13034                                                    MVT::v8i16, R, ShiftAmt,
13035                                                    DAG);
13036           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13037           // Zero out the rightmost bits.
13038           SmallVector<SDValue, 16> V(16,
13039                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13040                                                      MVT::i8));
13041           return DAG.getNode(ISD::AND, dl, VT, SHL,
13042                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13043         }
13044         if (Op.getOpcode() == ISD::SRL) {
13045           // Make a large shift.
13046           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13047                                                    MVT::v8i16, R, ShiftAmt,
13048                                                    DAG);
13049           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13050           // Zero out the leftmost bits.
13051           SmallVector<SDValue, 16> V(16,
13052                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13053                                                      MVT::i8));
13054           return DAG.getNode(ISD::AND, dl, VT, SRL,
13055                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13056         }
13057         if (Op.getOpcode() == ISD::SRA) {
13058           if (ShiftAmt == 7) {
13059             // R s>> 7  ===  R s< 0
13060             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13061             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13062           }
13063
13064           // R s>> a === ((R u>> a) ^ m) - m
13065           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13066           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13067                                                          MVT::i8));
13068           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13069           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13070           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13071           return Res;
13072         }
13073         llvm_unreachable("Unknown shift opcode.");
13074       }
13075
13076       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13077         if (Op.getOpcode() == ISD::SHL) {
13078           // Make a large shift.
13079           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13080                                                    MVT::v16i16, R, ShiftAmt,
13081                                                    DAG);
13082           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13083           // Zero out the rightmost bits.
13084           SmallVector<SDValue, 32> V(32,
13085                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13086                                                      MVT::i8));
13087           return DAG.getNode(ISD::AND, dl, VT, SHL,
13088                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13089         }
13090         if (Op.getOpcode() == ISD::SRL) {
13091           // Make a large shift.
13092           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13093                                                    MVT::v16i16, R, ShiftAmt,
13094                                                    DAG);
13095           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13096           // Zero out the leftmost bits.
13097           SmallVector<SDValue, 32> V(32,
13098                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13099                                                      MVT::i8));
13100           return DAG.getNode(ISD::AND, dl, VT, SRL,
13101                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13102         }
13103         if (Op.getOpcode() == ISD::SRA) {
13104           if (ShiftAmt == 7) {
13105             // R s>> 7  ===  R s< 0
13106             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13107             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13108           }
13109
13110           // R s>> a === ((R u>> a) ^ m) - m
13111           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13112           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13113                                                          MVT::i8));
13114           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13115           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13116           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13117           return Res;
13118         }
13119         llvm_unreachable("Unknown shift opcode.");
13120       }
13121     }
13122   }
13123
13124   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13125   if (!Subtarget->is64Bit() &&
13126       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13127       Amt.getOpcode() == ISD::BITCAST &&
13128       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13129     Amt = Amt.getOperand(0);
13130     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13131                      VT.getVectorNumElements();
13132     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13133     uint64_t ShiftAmt = 0;
13134     for (unsigned i = 0; i != Ratio; ++i) {
13135       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13136       if (C == 0)
13137         return SDValue();
13138       // 6 == Log2(64)
13139       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13140     }
13141     // Check remaining shift amounts.
13142     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13143       uint64_t ShAmt = 0;
13144       for (unsigned j = 0; j != Ratio; ++j) {
13145         ConstantSDNode *C =
13146           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13147         if (C == 0)
13148           return SDValue();
13149         // 6 == Log2(64)
13150         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13151       }
13152       if (ShAmt != ShiftAmt)
13153         return SDValue();
13154     }
13155     switch (Op.getOpcode()) {
13156     default:
13157       llvm_unreachable("Unknown shift opcode!");
13158     case ISD::SHL:
13159       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13160                                         DAG);
13161     case ISD::SRL:
13162       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13163                                         DAG);
13164     case ISD::SRA:
13165       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13166                                         DAG);
13167     }
13168   }
13169
13170   return SDValue();
13171 }
13172
13173 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13174                                         const X86Subtarget* Subtarget) {
13175   MVT VT = Op.getSimpleValueType();
13176   SDLoc dl(Op);
13177   SDValue R = Op.getOperand(0);
13178   SDValue Amt = Op.getOperand(1);
13179
13180   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13181       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13182       (Subtarget->hasInt256() &&
13183        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13184         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13185        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13186     SDValue BaseShAmt;
13187     EVT EltVT = VT.getVectorElementType();
13188
13189     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13190       unsigned NumElts = VT.getVectorNumElements();
13191       unsigned i, j;
13192       for (i = 0; i != NumElts; ++i) {
13193         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13194           continue;
13195         break;
13196       }
13197       for (j = i; j != NumElts; ++j) {
13198         SDValue Arg = Amt.getOperand(j);
13199         if (Arg.getOpcode() == ISD::UNDEF) continue;
13200         if (Arg != Amt.getOperand(i))
13201           break;
13202       }
13203       if (i != NumElts && j == NumElts)
13204         BaseShAmt = Amt.getOperand(i);
13205     } else {
13206       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13207         Amt = Amt.getOperand(0);
13208       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13209                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13210         SDValue InVec = Amt.getOperand(0);
13211         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13212           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13213           unsigned i = 0;
13214           for (; i != NumElts; ++i) {
13215             SDValue Arg = InVec.getOperand(i);
13216             if (Arg.getOpcode() == ISD::UNDEF) continue;
13217             BaseShAmt = Arg;
13218             break;
13219           }
13220         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13221            if (ConstantSDNode *C =
13222                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13223              unsigned SplatIdx =
13224                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13225              if (C->getZExtValue() == SplatIdx)
13226                BaseShAmt = InVec.getOperand(1);
13227            }
13228         }
13229         if (BaseShAmt.getNode() == 0)
13230           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13231                                   DAG.getIntPtrConstant(0));
13232       }
13233     }
13234
13235     if (BaseShAmt.getNode()) {
13236       if (EltVT.bitsGT(MVT::i32))
13237         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13238       else if (EltVT.bitsLT(MVT::i32))
13239         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13240
13241       switch (Op.getOpcode()) {
13242       default:
13243         llvm_unreachable("Unknown shift opcode!");
13244       case ISD::SHL:
13245         switch (VT.SimpleTy) {
13246         default: return SDValue();
13247         case MVT::v2i64:
13248         case MVT::v4i32:
13249         case MVT::v8i16:
13250         case MVT::v4i64:
13251         case MVT::v8i32:
13252         case MVT::v16i16:
13253         case MVT::v16i32:
13254         case MVT::v8i64:
13255           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13256         }
13257       case ISD::SRA:
13258         switch (VT.SimpleTy) {
13259         default: return SDValue();
13260         case MVT::v4i32:
13261         case MVT::v8i16:
13262         case MVT::v8i32:
13263         case MVT::v16i16:
13264         case MVT::v16i32:
13265         case MVT::v8i64:
13266           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13267         }
13268       case ISD::SRL:
13269         switch (VT.SimpleTy) {
13270         default: return SDValue();
13271         case MVT::v2i64:
13272         case MVT::v4i32:
13273         case MVT::v8i16:
13274         case MVT::v4i64:
13275         case MVT::v8i32:
13276         case MVT::v16i16:
13277         case MVT::v16i32:
13278         case MVT::v8i64:
13279           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13280         }
13281       }
13282     }
13283   }
13284
13285   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13286   if (!Subtarget->is64Bit() &&
13287       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13288       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13289       Amt.getOpcode() == ISD::BITCAST &&
13290       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13291     Amt = Amt.getOperand(0);
13292     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13293                      VT.getVectorNumElements();
13294     std::vector<SDValue> Vals(Ratio);
13295     for (unsigned i = 0; i != Ratio; ++i)
13296       Vals[i] = Amt.getOperand(i);
13297     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13298       for (unsigned j = 0; j != Ratio; ++j)
13299         if (Vals[j] != Amt.getOperand(i + j))
13300           return SDValue();
13301     }
13302     switch (Op.getOpcode()) {
13303     default:
13304       llvm_unreachable("Unknown shift opcode!");
13305     case ISD::SHL:
13306       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13307     case ISD::SRL:
13308       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13309     case ISD::SRA:
13310       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13311     }
13312   }
13313
13314   return SDValue();
13315 }
13316
13317 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13318                           SelectionDAG &DAG) {
13319
13320   MVT VT = Op.getSimpleValueType();
13321   SDLoc dl(Op);
13322   SDValue R = Op.getOperand(0);
13323   SDValue Amt = Op.getOperand(1);
13324   SDValue V;
13325
13326   if (!Subtarget->hasSSE2())
13327     return SDValue();
13328
13329   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13330   if (V.getNode())
13331     return V;
13332
13333   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13334   if (V.getNode())
13335       return V;
13336
13337   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13338     return Op;
13339   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13340   if (Subtarget->hasInt256()) {
13341     if (Op.getOpcode() == ISD::SRL &&
13342         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13343          VT == MVT::v4i64 || VT == MVT::v8i32))
13344       return Op;
13345     if (Op.getOpcode() == ISD::SHL &&
13346         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13347          VT == MVT::v4i64 || VT == MVT::v8i32))
13348       return Op;
13349     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13350       return Op;
13351   }
13352
13353   // If possible, lower this packed shift into a vector multiply instead of
13354   // expanding it into a sequence of scalar shifts.
13355   // Do this only if the vector shift count is a constant build_vector.
13356   if (Op.getOpcode() == ISD::SHL && 
13357       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13358        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13359       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13360     SmallVector<SDValue, 8> Elts;
13361     EVT SVT = VT.getScalarType();
13362     unsigned SVTBits = SVT.getSizeInBits();
13363     const APInt &One = APInt(SVTBits, 1);
13364     unsigned NumElems = VT.getVectorNumElements();
13365
13366     for (unsigned i=0; i !=NumElems; ++i) {
13367       SDValue Op = Amt->getOperand(i);
13368       if (Op->getOpcode() == ISD::UNDEF) {
13369         Elts.push_back(Op);
13370         continue;
13371       }
13372
13373       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13374       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13375       uint64_t ShAmt = C.getZExtValue();
13376       if (ShAmt >= SVTBits) {
13377         Elts.push_back(DAG.getUNDEF(SVT));
13378         continue;
13379       }
13380       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13381     }
13382     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13383     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13384   }
13385
13386   // Lower SHL with variable shift amount.
13387   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13388     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13389
13390     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13391     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13392     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13393     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13394   }
13395
13396   // If possible, lower this shift as a sequence of two shifts by
13397   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13398   // Example:
13399   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13400   //
13401   // Could be rewritten as:
13402   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13403   //
13404   // The advantage is that the two shifts from the example would be
13405   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13406   // the vector shift into four scalar shifts plus four pairs of vector
13407   // insert/extract.
13408   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13409       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13410     unsigned TargetOpcode = X86ISD::MOVSS;
13411     bool CanBeSimplified;
13412     // The splat value for the first packed shift (the 'X' from the example).
13413     SDValue Amt1 = Amt->getOperand(0);
13414     // The splat value for the second packed shift (the 'Y' from the example).
13415     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13416                                         Amt->getOperand(2);
13417
13418     // See if it is possible to replace this node with a sequence of
13419     // two shifts followed by a MOVSS/MOVSD
13420     if (VT == MVT::v4i32) {
13421       // Check if it is legal to use a MOVSS.
13422       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13423                         Amt2 == Amt->getOperand(3);
13424       if (!CanBeSimplified) {
13425         // Otherwise, check if we can still simplify this node using a MOVSD.
13426         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13427                           Amt->getOperand(2) == Amt->getOperand(3);
13428         TargetOpcode = X86ISD::MOVSD;
13429         Amt2 = Amt->getOperand(2);
13430       }
13431     } else {
13432       // Do similar checks for the case where the machine value type
13433       // is MVT::v8i16.
13434       CanBeSimplified = Amt1 == Amt->getOperand(1);
13435       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13436         CanBeSimplified = Amt2 == Amt->getOperand(i);
13437
13438       if (!CanBeSimplified) {
13439         TargetOpcode = X86ISD::MOVSD;
13440         CanBeSimplified = true;
13441         Amt2 = Amt->getOperand(4);
13442         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13443           CanBeSimplified = Amt1 == Amt->getOperand(i);
13444         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13445           CanBeSimplified = Amt2 == Amt->getOperand(j);
13446       }
13447     }
13448     
13449     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13450         isa<ConstantSDNode>(Amt2)) {
13451       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13452       EVT CastVT = MVT::v4i32;
13453       SDValue Splat1 = 
13454         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13455       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13456       SDValue Splat2 = 
13457         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13458       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13459       if (TargetOpcode == X86ISD::MOVSD)
13460         CastVT = MVT::v2i64;
13461       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13462       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13463       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13464                                             BitCast1, DAG);
13465       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13466     }
13467   }
13468
13469   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13470     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13471
13472     // a = a << 5;
13473     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13474     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13475
13476     // Turn 'a' into a mask suitable for VSELECT
13477     SDValue VSelM = DAG.getConstant(0x80, VT);
13478     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13479     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13480
13481     SDValue CM1 = DAG.getConstant(0x0f, VT);
13482     SDValue CM2 = DAG.getConstant(0x3f, VT);
13483
13484     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13485     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13486     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13487     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13488     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13489
13490     // a += a
13491     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13492     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13493     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13494
13495     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13496     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13497     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13498     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13499     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13500
13501     // a += a
13502     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13503     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13504     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13505
13506     // return VSELECT(r, r+r, a);
13507     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13508                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13509     return R;
13510   }
13511
13512   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13513   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13514   // solution better.
13515   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13516     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13517     unsigned ExtOpc =
13518         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13519     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13520     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13521     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13522                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13523     }
13524
13525   // Decompose 256-bit shifts into smaller 128-bit shifts.
13526   if (VT.is256BitVector()) {
13527     unsigned NumElems = VT.getVectorNumElements();
13528     MVT EltVT = VT.getVectorElementType();
13529     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13530
13531     // Extract the two vectors
13532     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13533     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13534
13535     // Recreate the shift amount vectors
13536     SDValue Amt1, Amt2;
13537     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13538       // Constant shift amount
13539       SmallVector<SDValue, 4> Amt1Csts;
13540       SmallVector<SDValue, 4> Amt2Csts;
13541       for (unsigned i = 0; i != NumElems/2; ++i)
13542         Amt1Csts.push_back(Amt->getOperand(i));
13543       for (unsigned i = NumElems/2; i != NumElems; ++i)
13544         Amt2Csts.push_back(Amt->getOperand(i));
13545
13546       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13547                                  &Amt1Csts[0], NumElems/2);
13548       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13549                                  &Amt2Csts[0], NumElems/2);
13550     } else {
13551       // Variable shift amount
13552       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13553       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13554     }
13555
13556     // Issue new vector shifts for the smaller types
13557     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13558     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13559
13560     // Concatenate the result back
13561     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13562   }
13563
13564   return SDValue();
13565 }
13566
13567 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13568   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13569   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13570   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13571   // has only one use.
13572   SDNode *N = Op.getNode();
13573   SDValue LHS = N->getOperand(0);
13574   SDValue RHS = N->getOperand(1);
13575   unsigned BaseOp = 0;
13576   unsigned Cond = 0;
13577   SDLoc DL(Op);
13578   switch (Op.getOpcode()) {
13579   default: llvm_unreachable("Unknown ovf instruction!");
13580   case ISD::SADDO:
13581     // A subtract of one will be selected as a INC. Note that INC doesn't
13582     // set CF, so we can't do this for UADDO.
13583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13584       if (C->isOne()) {
13585         BaseOp = X86ISD::INC;
13586         Cond = X86::COND_O;
13587         break;
13588       }
13589     BaseOp = X86ISD::ADD;
13590     Cond = X86::COND_O;
13591     break;
13592   case ISD::UADDO:
13593     BaseOp = X86ISD::ADD;
13594     Cond = X86::COND_B;
13595     break;
13596   case ISD::SSUBO:
13597     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13598     // set CF, so we can't do this for USUBO.
13599     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13600       if (C->isOne()) {
13601         BaseOp = X86ISD::DEC;
13602         Cond = X86::COND_O;
13603         break;
13604       }
13605     BaseOp = X86ISD::SUB;
13606     Cond = X86::COND_O;
13607     break;
13608   case ISD::USUBO:
13609     BaseOp = X86ISD::SUB;
13610     Cond = X86::COND_B;
13611     break;
13612   case ISD::SMULO:
13613     BaseOp = X86ISD::SMUL;
13614     Cond = X86::COND_O;
13615     break;
13616   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13617     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13618                                  MVT::i32);
13619     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13620
13621     SDValue SetCC =
13622       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13623                   DAG.getConstant(X86::COND_O, MVT::i32),
13624                   SDValue(Sum.getNode(), 2));
13625
13626     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13627   }
13628   }
13629
13630   // Also sets EFLAGS.
13631   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13632   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13633
13634   SDValue SetCC =
13635     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13636                 DAG.getConstant(Cond, MVT::i32),
13637                 SDValue(Sum.getNode(), 1));
13638
13639   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13640 }
13641
13642 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13643                                                   SelectionDAG &DAG) const {
13644   SDLoc dl(Op);
13645   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13646   MVT VT = Op.getSimpleValueType();
13647
13648   if (!Subtarget->hasSSE2() || !VT.isVector())
13649     return SDValue();
13650
13651   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13652                       ExtraVT.getScalarType().getSizeInBits();
13653
13654   switch (VT.SimpleTy) {
13655     default: return SDValue();
13656     case MVT::v8i32:
13657     case MVT::v16i16:
13658       if (!Subtarget->hasFp256())
13659         return SDValue();
13660       if (!Subtarget->hasInt256()) {
13661         // needs to be split
13662         unsigned NumElems = VT.getVectorNumElements();
13663
13664         // Extract the LHS vectors
13665         SDValue LHS = Op.getOperand(0);
13666         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13667         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13668
13669         MVT EltVT = VT.getVectorElementType();
13670         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13671
13672         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13673         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13674         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13675                                    ExtraNumElems/2);
13676         SDValue Extra = DAG.getValueType(ExtraVT);
13677
13678         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13679         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13680
13681         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13682       }
13683       // fall through
13684     case MVT::v4i32:
13685     case MVT::v8i16: {
13686       SDValue Op0 = Op.getOperand(0);
13687       SDValue Op00 = Op0.getOperand(0);
13688       SDValue Tmp1;
13689       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13690       if (Op0.getOpcode() == ISD::BITCAST &&
13691           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13692         // (sext (vzext x)) -> (vsext x)
13693         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13694         if (Tmp1.getNode()) {
13695           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13696           // This folding is only valid when the in-reg type is a vector of i8,
13697           // i16, or i32.
13698           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13699               ExtraEltVT == MVT::i32) {
13700             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13701             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13702                    "This optimization is invalid without a VZEXT.");
13703             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13704           }
13705           Op0 = Tmp1;
13706         }
13707       }
13708
13709       // If the above didn't work, then just use Shift-Left + Shift-Right.
13710       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13711                                         DAG);
13712       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13713                                         DAG);
13714     }
13715   }
13716 }
13717
13718 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13719                                  SelectionDAG &DAG) {
13720   SDLoc dl(Op);
13721   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13722     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13723   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13724     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13725
13726   // The only fence that needs an instruction is a sequentially-consistent
13727   // cross-thread fence.
13728   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13729     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13730     // no-sse2). There isn't any reason to disable it if the target processor
13731     // supports it.
13732     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13733       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13734
13735     SDValue Chain = Op.getOperand(0);
13736     SDValue Zero = DAG.getConstant(0, MVT::i32);
13737     SDValue Ops[] = {
13738       DAG.getRegister(X86::ESP, MVT::i32), // Base
13739       DAG.getTargetConstant(1, MVT::i8),   // Scale
13740       DAG.getRegister(0, MVT::i32),        // Index
13741       DAG.getTargetConstant(0, MVT::i32),  // Disp
13742       DAG.getRegister(0, MVT::i32),        // Segment.
13743       Zero,
13744       Chain
13745     };
13746     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13747     return SDValue(Res, 0);
13748   }
13749
13750   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13751   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13752 }
13753
13754 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13755                              SelectionDAG &DAG) {
13756   MVT T = Op.getSimpleValueType();
13757   SDLoc DL(Op);
13758   unsigned Reg = 0;
13759   unsigned size = 0;
13760   switch(T.SimpleTy) {
13761   default: llvm_unreachable("Invalid value type!");
13762   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13763   case MVT::i16: Reg = X86::AX;  size = 2; break;
13764   case MVT::i32: Reg = X86::EAX; size = 4; break;
13765   case MVT::i64:
13766     assert(Subtarget->is64Bit() && "Node not type legal!");
13767     Reg = X86::RAX; size = 8;
13768     break;
13769   }
13770   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13771                                     Op.getOperand(2), SDValue());
13772   SDValue Ops[] = { cpIn.getValue(0),
13773                     Op.getOperand(1),
13774                     Op.getOperand(3),
13775                     DAG.getTargetConstant(size, MVT::i8),
13776                     cpIn.getValue(1) };
13777   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13778   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13779   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13780                                            Ops, array_lengthof(Ops), T, MMO);
13781   SDValue cpOut =
13782     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13783   return cpOut;
13784 }
13785
13786 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13787                                      SelectionDAG &DAG) {
13788   assert(Subtarget->is64Bit() && "Result not type legalized?");
13789   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13790   SDValue TheChain = Op.getOperand(0);
13791   SDLoc dl(Op);
13792   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13793   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13794   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13795                                    rax.getValue(2));
13796   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13797                             DAG.getConstant(32, MVT::i8));
13798   SDValue Ops[] = {
13799     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13800     rdx.getValue(1)
13801   };
13802   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13803 }
13804
13805 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13806                             SelectionDAG &DAG) {
13807   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13808   MVT DstVT = Op.getSimpleValueType();
13809   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13810          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13811   assert((DstVT == MVT::i64 ||
13812           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13813          "Unexpected custom BITCAST");
13814   // i64 <=> MMX conversions are Legal.
13815   if (SrcVT==MVT::i64 && DstVT.isVector())
13816     return Op;
13817   if (DstVT==MVT::i64 && SrcVT.isVector())
13818     return Op;
13819   // MMX <=> MMX conversions are Legal.
13820   if (SrcVT.isVector() && DstVT.isVector())
13821     return Op;
13822   // All other conversions need to be expanded.
13823   return SDValue();
13824 }
13825
13826 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13827   SDNode *Node = Op.getNode();
13828   SDLoc dl(Node);
13829   EVT T = Node->getValueType(0);
13830   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13831                               DAG.getConstant(0, T), Node->getOperand(2));
13832   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13833                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13834                        Node->getOperand(0),
13835                        Node->getOperand(1), negOp,
13836                        cast<AtomicSDNode>(Node)->getMemOperand(),
13837                        cast<AtomicSDNode>(Node)->getOrdering(),
13838                        cast<AtomicSDNode>(Node)->getSynchScope());
13839 }
13840
13841 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13842   SDNode *Node = Op.getNode();
13843   SDLoc dl(Node);
13844   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13845
13846   // Convert seq_cst store -> xchg
13847   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13848   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13849   //        (The only way to get a 16-byte store is cmpxchg16b)
13850   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13851   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13852       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13853     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13854                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13855                                  Node->getOperand(0),
13856                                  Node->getOperand(1), Node->getOperand(2),
13857                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13858                                  cast<AtomicSDNode>(Node)->getOrdering(),
13859                                  cast<AtomicSDNode>(Node)->getSynchScope());
13860     return Swap.getValue(1);
13861   }
13862   // Other atomic stores have a simple pattern.
13863   return Op;
13864 }
13865
13866 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13867   EVT VT = Op.getNode()->getSimpleValueType(0);
13868
13869   // Let legalize expand this if it isn't a legal type yet.
13870   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13871     return SDValue();
13872
13873   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13874
13875   unsigned Opc;
13876   bool ExtraOp = false;
13877   switch (Op.getOpcode()) {
13878   default: llvm_unreachable("Invalid code");
13879   case ISD::ADDC: Opc = X86ISD::ADD; break;
13880   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13881   case ISD::SUBC: Opc = X86ISD::SUB; break;
13882   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13883   }
13884
13885   if (!ExtraOp)
13886     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13887                        Op.getOperand(1));
13888   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13889                      Op.getOperand(1), Op.getOperand(2));
13890 }
13891
13892 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13893                             SelectionDAG &DAG) {
13894   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13895
13896   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13897   // which returns the values as { float, float } (in XMM0) or
13898   // { double, double } (which is returned in XMM0, XMM1).
13899   SDLoc dl(Op);
13900   SDValue Arg = Op.getOperand(0);
13901   EVT ArgVT = Arg.getValueType();
13902   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13903
13904   TargetLowering::ArgListTy Args;
13905   TargetLowering::ArgListEntry Entry;
13906
13907   Entry.Node = Arg;
13908   Entry.Ty = ArgTy;
13909   Entry.isSExt = false;
13910   Entry.isZExt = false;
13911   Args.push_back(Entry);
13912
13913   bool isF64 = ArgVT == MVT::f64;
13914   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13915   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13916   // the results are returned via SRet in memory.
13917   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13919   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13920
13921   Type *RetTy = isF64
13922     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13923     : (Type*)VectorType::get(ArgTy, 4);
13924   TargetLowering::
13925     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13926                          false, false, false, false, 0,
13927                          CallingConv::C, /*isTaillCall=*/false,
13928                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13929                          Callee, Args, DAG, dl);
13930   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13931
13932   if (isF64)
13933     // Returned in xmm0 and xmm1.
13934     return CallResult.first;
13935
13936   // Returned in bits 0:31 and 32:64 xmm0.
13937   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13938                                CallResult.first, DAG.getIntPtrConstant(0));
13939   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13940                                CallResult.first, DAG.getIntPtrConstant(1));
13941   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13942   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13943 }
13944
13945 /// LowerOperation - Provide custom lowering hooks for some operations.
13946 ///
13947 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13948   switch (Op.getOpcode()) {
13949   default: llvm_unreachable("Should not custom lower this!");
13950   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13951   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13952   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13953   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13954   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13955   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13956   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13957   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13958   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13959   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13960   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13961   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13962   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13963   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13964   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13965   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13966   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13967   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13968   case ISD::SHL_PARTS:
13969   case ISD::SRA_PARTS:
13970   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13971   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13972   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13973   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13974   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13975   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13976   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13977   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13978   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13979   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13980   case ISD::FABS:               return LowerFABS(Op, DAG);
13981   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13982   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13983   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13984   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13985   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13986   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13987   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13988   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13989   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13990   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13991   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13992   case ISD::INTRINSIC_VOID:
13993   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13994   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13995   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13996   case ISD::FRAME_TO_ARGS_OFFSET:
13997                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13998   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13999   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14000   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14001   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14002   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14003   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14004   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14005   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14006   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14007   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14008   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14009   case ISD::SRA:
14010   case ISD::SRL:
14011   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14012   case ISD::SADDO:
14013   case ISD::UADDO:
14014   case ISD::SSUBO:
14015   case ISD::USUBO:
14016   case ISD::SMULO:
14017   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14018   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14019   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14020   case ISD::ADDC:
14021   case ISD::ADDE:
14022   case ISD::SUBC:
14023   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14024   case ISD::ADD:                return LowerADD(Op, DAG);
14025   case ISD::SUB:                return LowerSUB(Op, DAG);
14026   case ISD::SDIV:               return LowerSDIV(Op, DAG);
14027   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14028   }
14029 }
14030
14031 static void ReplaceATOMIC_LOAD(SDNode *Node,
14032                                   SmallVectorImpl<SDValue> &Results,
14033                                   SelectionDAG &DAG) {
14034   SDLoc dl(Node);
14035   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14036
14037   // Convert wide load -> cmpxchg8b/cmpxchg16b
14038   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14039   //        (The only way to get a 16-byte load is cmpxchg16b)
14040   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14041   SDValue Zero = DAG.getConstant(0, VT);
14042   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14043                                Node->getOperand(0),
14044                                Node->getOperand(1), Zero, Zero,
14045                                cast<AtomicSDNode>(Node)->getMemOperand(),
14046                                cast<AtomicSDNode>(Node)->getOrdering(),
14047                                cast<AtomicSDNode>(Node)->getOrdering(),
14048                                cast<AtomicSDNode>(Node)->getSynchScope());
14049   Results.push_back(Swap.getValue(0));
14050   Results.push_back(Swap.getValue(1));
14051 }
14052
14053 static void
14054 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14055                         SelectionDAG &DAG, unsigned NewOp) {
14056   SDLoc dl(Node);
14057   assert (Node->getValueType(0) == MVT::i64 &&
14058           "Only know how to expand i64 atomics");
14059
14060   SDValue Chain = Node->getOperand(0);
14061   SDValue In1 = Node->getOperand(1);
14062   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14063                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14064   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14065                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14066   SDValue Ops[] = { Chain, In1, In2L, In2H };
14067   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14068   SDValue Result =
14069     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14070                             cast<MemSDNode>(Node)->getMemOperand());
14071   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14072   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14073   Results.push_back(Result.getValue(2));
14074 }
14075
14076 /// ReplaceNodeResults - Replace a node with an illegal result type
14077 /// with a new node built out of custom code.
14078 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14079                                            SmallVectorImpl<SDValue>&Results,
14080                                            SelectionDAG &DAG) const {
14081   SDLoc dl(N);
14082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14083   switch (N->getOpcode()) {
14084   default:
14085     llvm_unreachable("Do not know how to custom type legalize this operation!");
14086   case ISD::SIGN_EXTEND_INREG:
14087   case ISD::ADDC:
14088   case ISD::ADDE:
14089   case ISD::SUBC:
14090   case ISD::SUBE:
14091     // We don't want to expand or promote these.
14092     return;
14093   case ISD::FP_TO_SINT:
14094   case ISD::FP_TO_UINT: {
14095     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14096
14097     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14098       return;
14099
14100     std::pair<SDValue,SDValue> Vals =
14101         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14102     SDValue FIST = Vals.first, StackSlot = Vals.second;
14103     if (FIST.getNode() != 0) {
14104       EVT VT = N->getValueType(0);
14105       // Return a load from the stack slot.
14106       if (StackSlot.getNode() != 0)
14107         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14108                                       MachinePointerInfo(),
14109                                       false, false, false, 0));
14110       else
14111         Results.push_back(FIST);
14112     }
14113     return;
14114   }
14115   case ISD::UINT_TO_FP: {
14116     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14117     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14118         N->getValueType(0) != MVT::v2f32)
14119       return;
14120     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14121                                  N->getOperand(0));
14122     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14123                                      MVT::f64);
14124     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14125     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14126                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14127     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14128     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14129     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14130     return;
14131   }
14132   case ISD::FP_ROUND: {
14133     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14134         return;
14135     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14136     Results.push_back(V);
14137     return;
14138   }
14139   case ISD::READCYCLECOUNTER: {
14140     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14141     SDValue TheChain = N->getOperand(0);
14142     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
14143     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
14144                                      rd.getValue(1));
14145     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
14146                                      eax.getValue(2));
14147     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14148     SDValue Ops[] = { eax, edx };
14149     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
14150                                   array_lengthof(Ops)));
14151     Results.push_back(edx.getValue(1));
14152     return;
14153   }
14154   case ISD::ATOMIC_CMP_SWAP: {
14155     EVT T = N->getValueType(0);
14156     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14157     bool Regs64bit = T == MVT::i128;
14158     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14159     SDValue cpInL, cpInH;
14160     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14161                         DAG.getConstant(0, HalfT));
14162     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14163                         DAG.getConstant(1, HalfT));
14164     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14165                              Regs64bit ? X86::RAX : X86::EAX,
14166                              cpInL, SDValue());
14167     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14168                              Regs64bit ? X86::RDX : X86::EDX,
14169                              cpInH, cpInL.getValue(1));
14170     SDValue swapInL, swapInH;
14171     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14172                           DAG.getConstant(0, HalfT));
14173     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14174                           DAG.getConstant(1, HalfT));
14175     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14176                                Regs64bit ? X86::RBX : X86::EBX,
14177                                swapInL, cpInH.getValue(1));
14178     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14179                                Regs64bit ? X86::RCX : X86::ECX,
14180                                swapInH, swapInL.getValue(1));
14181     SDValue Ops[] = { swapInH.getValue(0),
14182                       N->getOperand(1),
14183                       swapInH.getValue(1) };
14184     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14185     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14186     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14187                                   X86ISD::LCMPXCHG8_DAG;
14188     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14189                                              Ops, array_lengthof(Ops), T, MMO);
14190     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14191                                         Regs64bit ? X86::RAX : X86::EAX,
14192                                         HalfT, Result.getValue(1));
14193     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14194                                         Regs64bit ? X86::RDX : X86::EDX,
14195                                         HalfT, cpOutL.getValue(2));
14196     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14197     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14198     Results.push_back(cpOutH.getValue(1));
14199     return;
14200   }
14201   case ISD::ATOMIC_LOAD_ADD:
14202   case ISD::ATOMIC_LOAD_AND:
14203   case ISD::ATOMIC_LOAD_NAND:
14204   case ISD::ATOMIC_LOAD_OR:
14205   case ISD::ATOMIC_LOAD_SUB:
14206   case ISD::ATOMIC_LOAD_XOR:
14207   case ISD::ATOMIC_LOAD_MAX:
14208   case ISD::ATOMIC_LOAD_MIN:
14209   case ISD::ATOMIC_LOAD_UMAX:
14210   case ISD::ATOMIC_LOAD_UMIN:
14211   case ISD::ATOMIC_SWAP: {
14212     unsigned Opc;
14213     switch (N->getOpcode()) {
14214     default: llvm_unreachable("Unexpected opcode");
14215     case ISD::ATOMIC_LOAD_ADD:
14216       Opc = X86ISD::ATOMADD64_DAG;
14217       break;
14218     case ISD::ATOMIC_LOAD_AND:
14219       Opc = X86ISD::ATOMAND64_DAG;
14220       break;
14221     case ISD::ATOMIC_LOAD_NAND:
14222       Opc = X86ISD::ATOMNAND64_DAG;
14223       break;
14224     case ISD::ATOMIC_LOAD_OR:
14225       Opc = X86ISD::ATOMOR64_DAG;
14226       break;
14227     case ISD::ATOMIC_LOAD_SUB:
14228       Opc = X86ISD::ATOMSUB64_DAG;
14229       break;
14230     case ISD::ATOMIC_LOAD_XOR:
14231       Opc = X86ISD::ATOMXOR64_DAG;
14232       break;
14233     case ISD::ATOMIC_LOAD_MAX:
14234       Opc = X86ISD::ATOMMAX64_DAG;
14235       break;
14236     case ISD::ATOMIC_LOAD_MIN:
14237       Opc = X86ISD::ATOMMIN64_DAG;
14238       break;
14239     case ISD::ATOMIC_LOAD_UMAX:
14240       Opc = X86ISD::ATOMUMAX64_DAG;
14241       break;
14242     case ISD::ATOMIC_LOAD_UMIN:
14243       Opc = X86ISD::ATOMUMIN64_DAG;
14244       break;
14245     case ISD::ATOMIC_SWAP:
14246       Opc = X86ISD::ATOMSWAP64_DAG;
14247       break;
14248     }
14249     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14250     return;
14251   }
14252   case ISD::ATOMIC_LOAD:
14253     ReplaceATOMIC_LOAD(N, Results, DAG);
14254   }
14255 }
14256
14257 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14258   switch (Opcode) {
14259   default: return NULL;
14260   case X86ISD::BSF:                return "X86ISD::BSF";
14261   case X86ISD::BSR:                return "X86ISD::BSR";
14262   case X86ISD::SHLD:               return "X86ISD::SHLD";
14263   case X86ISD::SHRD:               return "X86ISD::SHRD";
14264   case X86ISD::FAND:               return "X86ISD::FAND";
14265   case X86ISD::FANDN:              return "X86ISD::FANDN";
14266   case X86ISD::FOR:                return "X86ISD::FOR";
14267   case X86ISD::FXOR:               return "X86ISD::FXOR";
14268   case X86ISD::FSRL:               return "X86ISD::FSRL";
14269   case X86ISD::FILD:               return "X86ISD::FILD";
14270   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14271   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14272   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14273   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14274   case X86ISD::FLD:                return "X86ISD::FLD";
14275   case X86ISD::FST:                return "X86ISD::FST";
14276   case X86ISD::CALL:               return "X86ISD::CALL";
14277   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14278   case X86ISD::BT:                 return "X86ISD::BT";
14279   case X86ISD::CMP:                return "X86ISD::CMP";
14280   case X86ISD::COMI:               return "X86ISD::COMI";
14281   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14282   case X86ISD::CMPM:               return "X86ISD::CMPM";
14283   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14284   case X86ISD::SETCC:              return "X86ISD::SETCC";
14285   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14286   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14287   case X86ISD::CMOV:               return "X86ISD::CMOV";
14288   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14289   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14290   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14291   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14292   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14293   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14294   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14295   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14296   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14297   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14298   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14299   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14300   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14301   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14302   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14303   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14304   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14305   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14306   case X86ISD::HADD:               return "X86ISD::HADD";
14307   case X86ISD::HSUB:               return "X86ISD::HSUB";
14308   case X86ISD::FHADD:              return "X86ISD::FHADD";
14309   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14310   case X86ISD::UMAX:               return "X86ISD::UMAX";
14311   case X86ISD::UMIN:               return "X86ISD::UMIN";
14312   case X86ISD::SMAX:               return "X86ISD::SMAX";
14313   case X86ISD::SMIN:               return "X86ISD::SMIN";
14314   case X86ISD::FMAX:               return "X86ISD::FMAX";
14315   case X86ISD::FMIN:               return "X86ISD::FMIN";
14316   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14317   case X86ISD::FMINC:              return "X86ISD::FMINC";
14318   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14319   case X86ISD::FRCP:               return "X86ISD::FRCP";
14320   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14321   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14322   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14323   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14324   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14325   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14326   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14327   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14328   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14329   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14330   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14331   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14332   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14333   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14334   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14335   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14336   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14337   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14338   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14339   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14340   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14341   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14342   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14343   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14344   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14345   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14346   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14347   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14348   case X86ISD::VSHL:               return "X86ISD::VSHL";
14349   case X86ISD::VSRL:               return "X86ISD::VSRL";
14350   case X86ISD::VSRA:               return "X86ISD::VSRA";
14351   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14352   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14353   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14354   case X86ISD::CMPP:               return "X86ISD::CMPP";
14355   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14356   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14357   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14358   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14359   case X86ISD::ADD:                return "X86ISD::ADD";
14360   case X86ISD::SUB:                return "X86ISD::SUB";
14361   case X86ISD::ADC:                return "X86ISD::ADC";
14362   case X86ISD::SBB:                return "X86ISD::SBB";
14363   case X86ISD::SMUL:               return "X86ISD::SMUL";
14364   case X86ISD::UMUL:               return "X86ISD::UMUL";
14365   case X86ISD::INC:                return "X86ISD::INC";
14366   case X86ISD::DEC:                return "X86ISD::DEC";
14367   case X86ISD::OR:                 return "X86ISD::OR";
14368   case X86ISD::XOR:                return "X86ISD::XOR";
14369   case X86ISD::AND:                return "X86ISD::AND";
14370   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14371   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14372   case X86ISD::PTEST:              return "X86ISD::PTEST";
14373   case X86ISD::TESTP:              return "X86ISD::TESTP";
14374   case X86ISD::TESTM:              return "X86ISD::TESTM";
14375   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14376   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14377   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14378   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14379   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14380   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14381   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14382   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14383   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14384   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14385   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14386   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14387   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14388   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14389   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14390   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14391   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14392   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14393   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14394   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14395   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14396   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14397   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14398   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14399   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14400   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14401   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14402   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14403   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14404   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14405   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14406   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14407   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14408   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14409   case X86ISD::SAHF:               return "X86ISD::SAHF";
14410   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14411   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14412   case X86ISD::FMADD:              return "X86ISD::FMADD";
14413   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14414   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14415   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14416   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14417   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14418   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14419   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14420   case X86ISD::XTEST:              return "X86ISD::XTEST";
14421   }
14422 }
14423
14424 // isLegalAddressingMode - Return true if the addressing mode represented
14425 // by AM is legal for this target, for a load/store of the specified type.
14426 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14427                                               Type *Ty) const {
14428   // X86 supports extremely general addressing modes.
14429   CodeModel::Model M = getTargetMachine().getCodeModel();
14430   Reloc::Model R = getTargetMachine().getRelocationModel();
14431
14432   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14433   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14434     return false;
14435
14436   if (AM.BaseGV) {
14437     unsigned GVFlags =
14438       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14439
14440     // If a reference to this global requires an extra load, we can't fold it.
14441     if (isGlobalStubReference(GVFlags))
14442       return false;
14443
14444     // If BaseGV requires a register for the PIC base, we cannot also have a
14445     // BaseReg specified.
14446     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14447       return false;
14448
14449     // If lower 4G is not available, then we must use rip-relative addressing.
14450     if ((M != CodeModel::Small || R != Reloc::Static) &&
14451         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14452       return false;
14453   }
14454
14455   switch (AM.Scale) {
14456   case 0:
14457   case 1:
14458   case 2:
14459   case 4:
14460   case 8:
14461     // These scales always work.
14462     break;
14463   case 3:
14464   case 5:
14465   case 9:
14466     // These scales are formed with basereg+scalereg.  Only accept if there is
14467     // no basereg yet.
14468     if (AM.HasBaseReg)
14469       return false;
14470     break;
14471   default:  // Other stuff never works.
14472     return false;
14473   }
14474
14475   return true;
14476 }
14477
14478 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14479   unsigned Bits = Ty->getScalarSizeInBits();
14480
14481   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14482   // particularly cheaper than those without.
14483   if (Bits == 8)
14484     return false;
14485
14486   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14487   // variable shifts just as cheap as scalar ones.
14488   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14489     return false;
14490
14491   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14492   // fully general vector.
14493   return true;
14494 }
14495
14496 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14497   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14498     return false;
14499   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14500   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14501   return NumBits1 > NumBits2;
14502 }
14503
14504 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14505   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14506     return false;
14507
14508   if (!isTypeLegal(EVT::getEVT(Ty1)))
14509     return false;
14510
14511   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14512
14513   // Assuming the caller doesn't have a zeroext or signext return parameter,
14514   // truncation all the way down to i1 is valid.
14515   return true;
14516 }
14517
14518 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14519   return isInt<32>(Imm);
14520 }
14521
14522 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14523   // Can also use sub to handle negated immediates.
14524   return isInt<32>(Imm);
14525 }
14526
14527 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14528   if (!VT1.isInteger() || !VT2.isInteger())
14529     return false;
14530   unsigned NumBits1 = VT1.getSizeInBits();
14531   unsigned NumBits2 = VT2.getSizeInBits();
14532   return NumBits1 > NumBits2;
14533 }
14534
14535 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14536   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14537   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14538 }
14539
14540 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14541   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14542   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14543 }
14544
14545 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14546   EVT VT1 = Val.getValueType();
14547   if (isZExtFree(VT1, VT2))
14548     return true;
14549
14550   if (Val.getOpcode() != ISD::LOAD)
14551     return false;
14552
14553   if (!VT1.isSimple() || !VT1.isInteger() ||
14554       !VT2.isSimple() || !VT2.isInteger())
14555     return false;
14556
14557   switch (VT1.getSimpleVT().SimpleTy) {
14558   default: break;
14559   case MVT::i8:
14560   case MVT::i16:
14561   case MVT::i32:
14562     // X86 has 8, 16, and 32-bit zero-extending loads.
14563     return true;
14564   }
14565
14566   return false;
14567 }
14568
14569 bool
14570 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14571   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14572     return false;
14573
14574   VT = VT.getScalarType();
14575
14576   if (!VT.isSimple())
14577     return false;
14578
14579   switch (VT.getSimpleVT().SimpleTy) {
14580   case MVT::f32:
14581   case MVT::f64:
14582     return true;
14583   default:
14584     break;
14585   }
14586
14587   return false;
14588 }
14589
14590 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14591   // i16 instructions are longer (0x66 prefix) and potentially slower.
14592   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14593 }
14594
14595 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14596 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14597 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14598 /// are assumed to be legal.
14599 bool
14600 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14601                                       EVT VT) const {
14602   if (!VT.isSimple())
14603     return false;
14604
14605   MVT SVT = VT.getSimpleVT();
14606
14607   // Very little shuffling can be done for 64-bit vectors right now.
14608   if (VT.getSizeInBits() == 64)
14609     return false;
14610
14611   // FIXME: pshufb, blends, shifts.
14612   return (SVT.getVectorNumElements() == 2 ||
14613           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14614           isMOVLMask(M, SVT) ||
14615           isSHUFPMask(M, SVT) ||
14616           isPSHUFDMask(M, SVT) ||
14617           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14618           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14619           isPALIGNRMask(M, SVT, Subtarget) ||
14620           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14621           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14622           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14623           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14624 }
14625
14626 bool
14627 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14628                                           EVT VT) const {
14629   if (!VT.isSimple())
14630     return false;
14631
14632   MVT SVT = VT.getSimpleVT();
14633   unsigned NumElts = SVT.getVectorNumElements();
14634   // FIXME: This collection of masks seems suspect.
14635   if (NumElts == 2)
14636     return true;
14637   if (NumElts == 4 && SVT.is128BitVector()) {
14638     return (isMOVLMask(Mask, SVT)  ||
14639             isCommutedMOVLMask(Mask, SVT, true) ||
14640             isSHUFPMask(Mask, SVT) ||
14641             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14642   }
14643   return false;
14644 }
14645
14646 //===----------------------------------------------------------------------===//
14647 //                           X86 Scheduler Hooks
14648 //===----------------------------------------------------------------------===//
14649
14650 /// Utility function to emit xbegin specifying the start of an RTM region.
14651 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14652                                      const TargetInstrInfo *TII) {
14653   DebugLoc DL = MI->getDebugLoc();
14654
14655   const BasicBlock *BB = MBB->getBasicBlock();
14656   MachineFunction::iterator I = MBB;
14657   ++I;
14658
14659   // For the v = xbegin(), we generate
14660   //
14661   // thisMBB:
14662   //  xbegin sinkMBB
14663   //
14664   // mainMBB:
14665   //  eax = -1
14666   //
14667   // sinkMBB:
14668   //  v = eax
14669
14670   MachineBasicBlock *thisMBB = MBB;
14671   MachineFunction *MF = MBB->getParent();
14672   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14673   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14674   MF->insert(I, mainMBB);
14675   MF->insert(I, sinkMBB);
14676
14677   // Transfer the remainder of BB and its successor edges to sinkMBB.
14678   sinkMBB->splice(sinkMBB->begin(), MBB,
14679                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14680   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14681
14682   // thisMBB:
14683   //  xbegin sinkMBB
14684   //  # fallthrough to mainMBB
14685   //  # abortion to sinkMBB
14686   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14687   thisMBB->addSuccessor(mainMBB);
14688   thisMBB->addSuccessor(sinkMBB);
14689
14690   // mainMBB:
14691   //  EAX = -1
14692   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14693   mainMBB->addSuccessor(sinkMBB);
14694
14695   // sinkMBB:
14696   // EAX is live into the sinkMBB
14697   sinkMBB->addLiveIn(X86::EAX);
14698   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14699           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14700     .addReg(X86::EAX);
14701
14702   MI->eraseFromParent();
14703   return sinkMBB;
14704 }
14705
14706 // Get CMPXCHG opcode for the specified data type.
14707 static unsigned getCmpXChgOpcode(EVT VT) {
14708   switch (VT.getSimpleVT().SimpleTy) {
14709   case MVT::i8:  return X86::LCMPXCHG8;
14710   case MVT::i16: return X86::LCMPXCHG16;
14711   case MVT::i32: return X86::LCMPXCHG32;
14712   case MVT::i64: return X86::LCMPXCHG64;
14713   default:
14714     break;
14715   }
14716   llvm_unreachable("Invalid operand size!");
14717 }
14718
14719 // Get LOAD opcode for the specified data type.
14720 static unsigned getLoadOpcode(EVT VT) {
14721   switch (VT.getSimpleVT().SimpleTy) {
14722   case MVT::i8:  return X86::MOV8rm;
14723   case MVT::i16: return X86::MOV16rm;
14724   case MVT::i32: return X86::MOV32rm;
14725   case MVT::i64: return X86::MOV64rm;
14726   default:
14727     break;
14728   }
14729   llvm_unreachable("Invalid operand size!");
14730 }
14731
14732 // Get opcode of the non-atomic one from the specified atomic instruction.
14733 static unsigned getNonAtomicOpcode(unsigned Opc) {
14734   switch (Opc) {
14735   case X86::ATOMAND8:  return X86::AND8rr;
14736   case X86::ATOMAND16: return X86::AND16rr;
14737   case X86::ATOMAND32: return X86::AND32rr;
14738   case X86::ATOMAND64: return X86::AND64rr;
14739   case X86::ATOMOR8:   return X86::OR8rr;
14740   case X86::ATOMOR16:  return X86::OR16rr;
14741   case X86::ATOMOR32:  return X86::OR32rr;
14742   case X86::ATOMOR64:  return X86::OR64rr;
14743   case X86::ATOMXOR8:  return X86::XOR8rr;
14744   case X86::ATOMXOR16: return X86::XOR16rr;
14745   case X86::ATOMXOR32: return X86::XOR32rr;
14746   case X86::ATOMXOR64: return X86::XOR64rr;
14747   }
14748   llvm_unreachable("Unhandled atomic-load-op opcode!");
14749 }
14750
14751 // Get opcode of the non-atomic one from the specified atomic instruction with
14752 // extra opcode.
14753 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14754                                                unsigned &ExtraOpc) {
14755   switch (Opc) {
14756   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14757   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14758   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14759   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14760   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14761   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14762   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14763   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14764   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14765   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14766   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14767   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14768   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14769   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14770   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14771   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14772   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14773   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14774   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14775   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14776   }
14777   llvm_unreachable("Unhandled atomic-load-op opcode!");
14778 }
14779
14780 // Get opcode of the non-atomic one from the specified atomic instruction for
14781 // 64-bit data type on 32-bit target.
14782 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14783   switch (Opc) {
14784   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14785   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14786   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14787   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14788   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14789   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14790   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14791   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14792   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14793   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14794   }
14795   llvm_unreachable("Unhandled atomic-load-op opcode!");
14796 }
14797
14798 // Get opcode of the non-atomic one from the specified atomic instruction for
14799 // 64-bit data type on 32-bit target with extra opcode.
14800 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14801                                                    unsigned &HiOpc,
14802                                                    unsigned &ExtraOpc) {
14803   switch (Opc) {
14804   case X86::ATOMNAND6432:
14805     ExtraOpc = X86::NOT32r;
14806     HiOpc = X86::AND32rr;
14807     return X86::AND32rr;
14808   }
14809   llvm_unreachable("Unhandled atomic-load-op opcode!");
14810 }
14811
14812 // Get pseudo CMOV opcode from the specified data type.
14813 static unsigned getPseudoCMOVOpc(EVT VT) {
14814   switch (VT.getSimpleVT().SimpleTy) {
14815   case MVT::i8:  return X86::CMOV_GR8;
14816   case MVT::i16: return X86::CMOV_GR16;
14817   case MVT::i32: return X86::CMOV_GR32;
14818   default:
14819     break;
14820   }
14821   llvm_unreachable("Unknown CMOV opcode!");
14822 }
14823
14824 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14825 // They will be translated into a spin-loop or compare-exchange loop from
14826 //
14827 //    ...
14828 //    dst = atomic-fetch-op MI.addr, MI.val
14829 //    ...
14830 //
14831 // to
14832 //
14833 //    ...
14834 //    t1 = LOAD MI.addr
14835 // loop:
14836 //    t4 = phi(t1, t3 / loop)
14837 //    t2 = OP MI.val, t4
14838 //    EAX = t4
14839 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14840 //    t3 = EAX
14841 //    JNE loop
14842 // sink:
14843 //    dst = t3
14844 //    ...
14845 MachineBasicBlock *
14846 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14847                                        MachineBasicBlock *MBB) const {
14848   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14849   DebugLoc DL = MI->getDebugLoc();
14850
14851   MachineFunction *MF = MBB->getParent();
14852   MachineRegisterInfo &MRI = MF->getRegInfo();
14853
14854   const BasicBlock *BB = MBB->getBasicBlock();
14855   MachineFunction::iterator I = MBB;
14856   ++I;
14857
14858   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14859          "Unexpected number of operands");
14860
14861   assert(MI->hasOneMemOperand() &&
14862          "Expected atomic-load-op to have one memoperand");
14863
14864   // Memory Reference
14865   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14866   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14867
14868   unsigned DstReg, SrcReg;
14869   unsigned MemOpndSlot;
14870
14871   unsigned CurOp = 0;
14872
14873   DstReg = MI->getOperand(CurOp++).getReg();
14874   MemOpndSlot = CurOp;
14875   CurOp += X86::AddrNumOperands;
14876   SrcReg = MI->getOperand(CurOp++).getReg();
14877
14878   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14879   MVT::SimpleValueType VT = *RC->vt_begin();
14880   unsigned t1 = MRI.createVirtualRegister(RC);
14881   unsigned t2 = MRI.createVirtualRegister(RC);
14882   unsigned t3 = MRI.createVirtualRegister(RC);
14883   unsigned t4 = MRI.createVirtualRegister(RC);
14884   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14885
14886   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14887   unsigned LOADOpc = getLoadOpcode(VT);
14888
14889   // For the atomic load-arith operator, we generate
14890   //
14891   //  thisMBB:
14892   //    t1 = LOAD [MI.addr]
14893   //  mainMBB:
14894   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14895   //    t1 = OP MI.val, EAX
14896   //    EAX = t4
14897   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14898   //    t3 = EAX
14899   //    JNE mainMBB
14900   //  sinkMBB:
14901   //    dst = t3
14902
14903   MachineBasicBlock *thisMBB = MBB;
14904   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14905   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14906   MF->insert(I, mainMBB);
14907   MF->insert(I, sinkMBB);
14908
14909   MachineInstrBuilder MIB;
14910
14911   // Transfer the remainder of BB and its successor edges to sinkMBB.
14912   sinkMBB->splice(sinkMBB->begin(), MBB,
14913                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14914   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14915
14916   // thisMBB:
14917   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14918   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14919     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14920     if (NewMO.isReg())
14921       NewMO.setIsKill(false);
14922     MIB.addOperand(NewMO);
14923   }
14924   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14925     unsigned flags = (*MMOI)->getFlags();
14926     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14927     MachineMemOperand *MMO =
14928       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14929                                (*MMOI)->getSize(),
14930                                (*MMOI)->getBaseAlignment(),
14931                                (*MMOI)->getTBAAInfo(),
14932                                (*MMOI)->getRanges());
14933     MIB.addMemOperand(MMO);
14934   }
14935
14936   thisMBB->addSuccessor(mainMBB);
14937
14938   // mainMBB:
14939   MachineBasicBlock *origMainMBB = mainMBB;
14940
14941   // Add a PHI.
14942   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14943                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14944
14945   unsigned Opc = MI->getOpcode();
14946   switch (Opc) {
14947   default:
14948     llvm_unreachable("Unhandled atomic-load-op opcode!");
14949   case X86::ATOMAND8:
14950   case X86::ATOMAND16:
14951   case X86::ATOMAND32:
14952   case X86::ATOMAND64:
14953   case X86::ATOMOR8:
14954   case X86::ATOMOR16:
14955   case X86::ATOMOR32:
14956   case X86::ATOMOR64:
14957   case X86::ATOMXOR8:
14958   case X86::ATOMXOR16:
14959   case X86::ATOMXOR32:
14960   case X86::ATOMXOR64: {
14961     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14962     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14963       .addReg(t4);
14964     break;
14965   }
14966   case X86::ATOMNAND8:
14967   case X86::ATOMNAND16:
14968   case X86::ATOMNAND32:
14969   case X86::ATOMNAND64: {
14970     unsigned Tmp = MRI.createVirtualRegister(RC);
14971     unsigned NOTOpc;
14972     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14973     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14974       .addReg(t4);
14975     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14976     break;
14977   }
14978   case X86::ATOMMAX8:
14979   case X86::ATOMMAX16:
14980   case X86::ATOMMAX32:
14981   case X86::ATOMMAX64:
14982   case X86::ATOMMIN8:
14983   case X86::ATOMMIN16:
14984   case X86::ATOMMIN32:
14985   case X86::ATOMMIN64:
14986   case X86::ATOMUMAX8:
14987   case X86::ATOMUMAX16:
14988   case X86::ATOMUMAX32:
14989   case X86::ATOMUMAX64:
14990   case X86::ATOMUMIN8:
14991   case X86::ATOMUMIN16:
14992   case X86::ATOMUMIN32:
14993   case X86::ATOMUMIN64: {
14994     unsigned CMPOpc;
14995     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14996
14997     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14998       .addReg(SrcReg)
14999       .addReg(t4);
15000
15001     if (Subtarget->hasCMov()) {
15002       if (VT != MVT::i8) {
15003         // Native support
15004         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15005           .addReg(SrcReg)
15006           .addReg(t4);
15007       } else {
15008         // Promote i8 to i32 to use CMOV32
15009         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15010         const TargetRegisterClass *RC32 =
15011           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15012         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15013         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15014         unsigned Tmp = MRI.createVirtualRegister(RC32);
15015
15016         unsigned Undef = MRI.createVirtualRegister(RC32);
15017         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15018
15019         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15020           .addReg(Undef)
15021           .addReg(SrcReg)
15022           .addImm(X86::sub_8bit);
15023         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15024           .addReg(Undef)
15025           .addReg(t4)
15026           .addImm(X86::sub_8bit);
15027
15028         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15029           .addReg(SrcReg32)
15030           .addReg(AccReg32);
15031
15032         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15033           .addReg(Tmp, 0, X86::sub_8bit);
15034       }
15035     } else {
15036       // Use pseudo select and lower them.
15037       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15038              "Invalid atomic-load-op transformation!");
15039       unsigned SelOpc = getPseudoCMOVOpc(VT);
15040       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15041       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15042       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15043               .addReg(SrcReg).addReg(t4)
15044               .addImm(CC);
15045       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15046       // Replace the original PHI node as mainMBB is changed after CMOV
15047       // lowering.
15048       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15049         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15050       Phi->eraseFromParent();
15051     }
15052     break;
15053   }
15054   }
15055
15056   // Copy PhyReg back from virtual register.
15057   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15058     .addReg(t4);
15059
15060   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15061   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15062     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15063     if (NewMO.isReg())
15064       NewMO.setIsKill(false);
15065     MIB.addOperand(NewMO);
15066   }
15067   MIB.addReg(t2);
15068   MIB.setMemRefs(MMOBegin, MMOEnd);
15069
15070   // Copy PhyReg back to virtual register.
15071   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15072     .addReg(PhyReg);
15073
15074   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15075
15076   mainMBB->addSuccessor(origMainMBB);
15077   mainMBB->addSuccessor(sinkMBB);
15078
15079   // sinkMBB:
15080   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15081           TII->get(TargetOpcode::COPY), DstReg)
15082     .addReg(t3);
15083
15084   MI->eraseFromParent();
15085   return sinkMBB;
15086 }
15087
15088 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15089 // instructions. They will be translated into a spin-loop or compare-exchange
15090 // loop from
15091 //
15092 //    ...
15093 //    dst = atomic-fetch-op MI.addr, MI.val
15094 //    ...
15095 //
15096 // to
15097 //
15098 //    ...
15099 //    t1L = LOAD [MI.addr + 0]
15100 //    t1H = LOAD [MI.addr + 4]
15101 // loop:
15102 //    t4L = phi(t1L, t3L / loop)
15103 //    t4H = phi(t1H, t3H / loop)
15104 //    t2L = OP MI.val.lo, t4L
15105 //    t2H = OP MI.val.hi, t4H
15106 //    EAX = t4L
15107 //    EDX = t4H
15108 //    EBX = t2L
15109 //    ECX = t2H
15110 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15111 //    t3L = EAX
15112 //    t3H = EDX
15113 //    JNE loop
15114 // sink:
15115 //    dstL = t3L
15116 //    dstH = t3H
15117 //    ...
15118 MachineBasicBlock *
15119 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15120                                            MachineBasicBlock *MBB) const {
15121   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15122   DebugLoc DL = MI->getDebugLoc();
15123
15124   MachineFunction *MF = MBB->getParent();
15125   MachineRegisterInfo &MRI = MF->getRegInfo();
15126
15127   const BasicBlock *BB = MBB->getBasicBlock();
15128   MachineFunction::iterator I = MBB;
15129   ++I;
15130
15131   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15132          "Unexpected number of operands");
15133
15134   assert(MI->hasOneMemOperand() &&
15135          "Expected atomic-load-op32 to have one memoperand");
15136
15137   // Memory Reference
15138   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15139   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15140
15141   unsigned DstLoReg, DstHiReg;
15142   unsigned SrcLoReg, SrcHiReg;
15143   unsigned MemOpndSlot;
15144
15145   unsigned CurOp = 0;
15146
15147   DstLoReg = MI->getOperand(CurOp++).getReg();
15148   DstHiReg = MI->getOperand(CurOp++).getReg();
15149   MemOpndSlot = CurOp;
15150   CurOp += X86::AddrNumOperands;
15151   SrcLoReg = MI->getOperand(CurOp++).getReg();
15152   SrcHiReg = MI->getOperand(CurOp++).getReg();
15153
15154   const TargetRegisterClass *RC = &X86::GR32RegClass;
15155   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15156
15157   unsigned t1L = MRI.createVirtualRegister(RC);
15158   unsigned t1H = MRI.createVirtualRegister(RC);
15159   unsigned t2L = MRI.createVirtualRegister(RC);
15160   unsigned t2H = MRI.createVirtualRegister(RC);
15161   unsigned t3L = MRI.createVirtualRegister(RC);
15162   unsigned t3H = MRI.createVirtualRegister(RC);
15163   unsigned t4L = MRI.createVirtualRegister(RC);
15164   unsigned t4H = MRI.createVirtualRegister(RC);
15165
15166   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15167   unsigned LOADOpc = X86::MOV32rm;
15168
15169   // For the atomic load-arith operator, we generate
15170   //
15171   //  thisMBB:
15172   //    t1L = LOAD [MI.addr + 0]
15173   //    t1H = LOAD [MI.addr + 4]
15174   //  mainMBB:
15175   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15176   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15177   //    t2L = OP MI.val.lo, t4L
15178   //    t2H = OP MI.val.hi, t4H
15179   //    EBX = t2L
15180   //    ECX = t2H
15181   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15182   //    t3L = EAX
15183   //    t3H = EDX
15184   //    JNE loop
15185   //  sinkMBB:
15186   //    dstL = t3L
15187   //    dstH = t3H
15188
15189   MachineBasicBlock *thisMBB = MBB;
15190   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15191   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15192   MF->insert(I, mainMBB);
15193   MF->insert(I, sinkMBB);
15194
15195   MachineInstrBuilder MIB;
15196
15197   // Transfer the remainder of BB and its successor edges to sinkMBB.
15198   sinkMBB->splice(sinkMBB->begin(), MBB,
15199                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15200   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15201
15202   // thisMBB:
15203   // Lo
15204   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15205   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15206     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15207     if (NewMO.isReg())
15208       NewMO.setIsKill(false);
15209     MIB.addOperand(NewMO);
15210   }
15211   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15212     unsigned flags = (*MMOI)->getFlags();
15213     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15214     MachineMemOperand *MMO =
15215       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15216                                (*MMOI)->getSize(),
15217                                (*MMOI)->getBaseAlignment(),
15218                                (*MMOI)->getTBAAInfo(),
15219                                (*MMOI)->getRanges());
15220     MIB.addMemOperand(MMO);
15221   };
15222   MachineInstr *LowMI = MIB;
15223
15224   // Hi
15225   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15227     if (i == X86::AddrDisp) {
15228       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15229     } else {
15230       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15231       if (NewMO.isReg())
15232         NewMO.setIsKill(false);
15233       MIB.addOperand(NewMO);
15234     }
15235   }
15236   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15237
15238   thisMBB->addSuccessor(mainMBB);
15239
15240   // mainMBB:
15241   MachineBasicBlock *origMainMBB = mainMBB;
15242
15243   // Add PHIs.
15244   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15245                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15246   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15247                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15248
15249   unsigned Opc = MI->getOpcode();
15250   switch (Opc) {
15251   default:
15252     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15253   case X86::ATOMAND6432:
15254   case X86::ATOMOR6432:
15255   case X86::ATOMXOR6432:
15256   case X86::ATOMADD6432:
15257   case X86::ATOMSUB6432: {
15258     unsigned HiOpc;
15259     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15260     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15261       .addReg(SrcLoReg);
15262     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15263       .addReg(SrcHiReg);
15264     break;
15265   }
15266   case X86::ATOMNAND6432: {
15267     unsigned HiOpc, NOTOpc;
15268     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15269     unsigned TmpL = MRI.createVirtualRegister(RC);
15270     unsigned TmpH = MRI.createVirtualRegister(RC);
15271     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15272       .addReg(t4L);
15273     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15274       .addReg(t4H);
15275     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15276     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15277     break;
15278   }
15279   case X86::ATOMMAX6432:
15280   case X86::ATOMMIN6432:
15281   case X86::ATOMUMAX6432:
15282   case X86::ATOMUMIN6432: {
15283     unsigned HiOpc;
15284     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15285     unsigned cL = MRI.createVirtualRegister(RC8);
15286     unsigned cH = MRI.createVirtualRegister(RC8);
15287     unsigned cL32 = MRI.createVirtualRegister(RC);
15288     unsigned cH32 = MRI.createVirtualRegister(RC);
15289     unsigned cc = MRI.createVirtualRegister(RC);
15290     // cl := cmp src_lo, lo
15291     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15292       .addReg(SrcLoReg).addReg(t4L);
15293     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15294     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15295     // ch := cmp src_hi, hi
15296     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15297       .addReg(SrcHiReg).addReg(t4H);
15298     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15299     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15300     // cc := if (src_hi == hi) ? cl : ch;
15301     if (Subtarget->hasCMov()) {
15302       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15303         .addReg(cH32).addReg(cL32);
15304     } else {
15305       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15306               .addReg(cH32).addReg(cL32)
15307               .addImm(X86::COND_E);
15308       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15309     }
15310     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15311     if (Subtarget->hasCMov()) {
15312       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15313         .addReg(SrcLoReg).addReg(t4L);
15314       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15315         .addReg(SrcHiReg).addReg(t4H);
15316     } else {
15317       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15318               .addReg(SrcLoReg).addReg(t4L)
15319               .addImm(X86::COND_NE);
15320       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15321       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15322       // 2nd CMOV lowering.
15323       mainMBB->addLiveIn(X86::EFLAGS);
15324       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15325               .addReg(SrcHiReg).addReg(t4H)
15326               .addImm(X86::COND_NE);
15327       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15328       // Replace the original PHI node as mainMBB is changed after CMOV
15329       // lowering.
15330       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15331         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15332       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15333         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15334       PhiL->eraseFromParent();
15335       PhiH->eraseFromParent();
15336     }
15337     break;
15338   }
15339   case X86::ATOMSWAP6432: {
15340     unsigned HiOpc;
15341     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15342     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15343     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15344     break;
15345   }
15346   }
15347
15348   // Copy EDX:EAX back from HiReg:LoReg
15349   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15350   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15351   // Copy ECX:EBX from t1H:t1L
15352   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15353   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15354
15355   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15356   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15357     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15358     if (NewMO.isReg())
15359       NewMO.setIsKill(false);
15360     MIB.addOperand(NewMO);
15361   }
15362   MIB.setMemRefs(MMOBegin, MMOEnd);
15363
15364   // Copy EDX:EAX back to t3H:t3L
15365   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15366   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15367
15368   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15369
15370   mainMBB->addSuccessor(origMainMBB);
15371   mainMBB->addSuccessor(sinkMBB);
15372
15373   // sinkMBB:
15374   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15375           TII->get(TargetOpcode::COPY), DstLoReg)
15376     .addReg(t3L);
15377   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15378           TII->get(TargetOpcode::COPY), DstHiReg)
15379     .addReg(t3H);
15380
15381   MI->eraseFromParent();
15382   return sinkMBB;
15383 }
15384
15385 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15386 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15387 // in the .td file.
15388 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15389                                        const TargetInstrInfo *TII) {
15390   unsigned Opc;
15391   switch (MI->getOpcode()) {
15392   default: llvm_unreachable("illegal opcode!");
15393   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15394   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15395   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15396   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15397   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15398   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15399   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15400   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15401   }
15402
15403   DebugLoc dl = MI->getDebugLoc();
15404   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15405
15406   unsigned NumArgs = MI->getNumOperands();
15407   for (unsigned i = 1; i < NumArgs; ++i) {
15408     MachineOperand &Op = MI->getOperand(i);
15409     if (!(Op.isReg() && Op.isImplicit()))
15410       MIB.addOperand(Op);
15411   }
15412   if (MI->hasOneMemOperand())
15413     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15414
15415   BuildMI(*BB, MI, dl,
15416     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15417     .addReg(X86::XMM0);
15418
15419   MI->eraseFromParent();
15420   return BB;
15421 }
15422
15423 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15424 // defs in an instruction pattern
15425 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15426                                        const TargetInstrInfo *TII) {
15427   unsigned Opc;
15428   switch (MI->getOpcode()) {
15429   default: llvm_unreachable("illegal opcode!");
15430   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15431   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15432   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15433   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15434   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15435   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15436   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15437   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15438   }
15439
15440   DebugLoc dl = MI->getDebugLoc();
15441   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15442
15443   unsigned NumArgs = MI->getNumOperands(); // remove the results
15444   for (unsigned i = 1; i < NumArgs; ++i) {
15445     MachineOperand &Op = MI->getOperand(i);
15446     if (!(Op.isReg() && Op.isImplicit()))
15447       MIB.addOperand(Op);
15448   }
15449   if (MI->hasOneMemOperand())
15450     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15451
15452   BuildMI(*BB, MI, dl,
15453     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15454     .addReg(X86::ECX);
15455
15456   MI->eraseFromParent();
15457   return BB;
15458 }
15459
15460 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15461                                        const TargetInstrInfo *TII,
15462                                        const X86Subtarget* Subtarget) {
15463   DebugLoc dl = MI->getDebugLoc();
15464
15465   // Address into RAX/EAX, other two args into ECX, EDX.
15466   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15467   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15468   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15469   for (int i = 0; i < X86::AddrNumOperands; ++i)
15470     MIB.addOperand(MI->getOperand(i));
15471
15472   unsigned ValOps = X86::AddrNumOperands;
15473   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15474     .addReg(MI->getOperand(ValOps).getReg());
15475   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15476     .addReg(MI->getOperand(ValOps+1).getReg());
15477
15478   // The instruction doesn't actually take any operands though.
15479   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15480
15481   MI->eraseFromParent(); // The pseudo is gone now.
15482   return BB;
15483 }
15484
15485 MachineBasicBlock *
15486 X86TargetLowering::EmitVAARG64WithCustomInserter(
15487                    MachineInstr *MI,
15488                    MachineBasicBlock *MBB) const {
15489   // Emit va_arg instruction on X86-64.
15490
15491   // Operands to this pseudo-instruction:
15492   // 0  ) Output        : destination address (reg)
15493   // 1-5) Input         : va_list address (addr, i64mem)
15494   // 6  ) ArgSize       : Size (in bytes) of vararg type
15495   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15496   // 8  ) Align         : Alignment of type
15497   // 9  ) EFLAGS (implicit-def)
15498
15499   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15500   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15501
15502   unsigned DestReg = MI->getOperand(0).getReg();
15503   MachineOperand &Base = MI->getOperand(1);
15504   MachineOperand &Scale = MI->getOperand(2);
15505   MachineOperand &Index = MI->getOperand(3);
15506   MachineOperand &Disp = MI->getOperand(4);
15507   MachineOperand &Segment = MI->getOperand(5);
15508   unsigned ArgSize = MI->getOperand(6).getImm();
15509   unsigned ArgMode = MI->getOperand(7).getImm();
15510   unsigned Align = MI->getOperand(8).getImm();
15511
15512   // Memory Reference
15513   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15514   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15515   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15516
15517   // Machine Information
15518   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15519   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15520   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15521   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15522   DebugLoc DL = MI->getDebugLoc();
15523
15524   // struct va_list {
15525   //   i32   gp_offset
15526   //   i32   fp_offset
15527   //   i64   overflow_area (address)
15528   //   i64   reg_save_area (address)
15529   // }
15530   // sizeof(va_list) = 24
15531   // alignment(va_list) = 8
15532
15533   unsigned TotalNumIntRegs = 6;
15534   unsigned TotalNumXMMRegs = 8;
15535   bool UseGPOffset = (ArgMode == 1);
15536   bool UseFPOffset = (ArgMode == 2);
15537   unsigned MaxOffset = TotalNumIntRegs * 8 +
15538                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15539
15540   /* Align ArgSize to a multiple of 8 */
15541   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15542   bool NeedsAlign = (Align > 8);
15543
15544   MachineBasicBlock *thisMBB = MBB;
15545   MachineBasicBlock *overflowMBB;
15546   MachineBasicBlock *offsetMBB;
15547   MachineBasicBlock *endMBB;
15548
15549   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15550   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15551   unsigned OffsetReg = 0;
15552
15553   if (!UseGPOffset && !UseFPOffset) {
15554     // If we only pull from the overflow region, we don't create a branch.
15555     // We don't need to alter control flow.
15556     OffsetDestReg = 0; // unused
15557     OverflowDestReg = DestReg;
15558
15559     offsetMBB = NULL;
15560     overflowMBB = thisMBB;
15561     endMBB = thisMBB;
15562   } else {
15563     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15564     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15565     // If not, pull from overflow_area. (branch to overflowMBB)
15566     //
15567     //       thisMBB
15568     //         |     .
15569     //         |        .
15570     //     offsetMBB   overflowMBB
15571     //         |        .
15572     //         |     .
15573     //        endMBB
15574
15575     // Registers for the PHI in endMBB
15576     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15577     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15578
15579     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15580     MachineFunction *MF = MBB->getParent();
15581     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15582     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15583     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15584
15585     MachineFunction::iterator MBBIter = MBB;
15586     ++MBBIter;
15587
15588     // Insert the new basic blocks
15589     MF->insert(MBBIter, offsetMBB);
15590     MF->insert(MBBIter, overflowMBB);
15591     MF->insert(MBBIter, endMBB);
15592
15593     // Transfer the remainder of MBB and its successor edges to endMBB.
15594     endMBB->splice(endMBB->begin(), thisMBB,
15595                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15596     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15597
15598     // Make offsetMBB and overflowMBB successors of thisMBB
15599     thisMBB->addSuccessor(offsetMBB);
15600     thisMBB->addSuccessor(overflowMBB);
15601
15602     // endMBB is a successor of both offsetMBB and overflowMBB
15603     offsetMBB->addSuccessor(endMBB);
15604     overflowMBB->addSuccessor(endMBB);
15605
15606     // Load the offset value into a register
15607     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15608     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15609       .addOperand(Base)
15610       .addOperand(Scale)
15611       .addOperand(Index)
15612       .addDisp(Disp, UseFPOffset ? 4 : 0)
15613       .addOperand(Segment)
15614       .setMemRefs(MMOBegin, MMOEnd);
15615
15616     // Check if there is enough room left to pull this argument.
15617     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15618       .addReg(OffsetReg)
15619       .addImm(MaxOffset + 8 - ArgSizeA8);
15620
15621     // Branch to "overflowMBB" if offset >= max
15622     // Fall through to "offsetMBB" otherwise
15623     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15624       .addMBB(overflowMBB);
15625   }
15626
15627   // In offsetMBB, emit code to use the reg_save_area.
15628   if (offsetMBB) {
15629     assert(OffsetReg != 0);
15630
15631     // Read the reg_save_area address.
15632     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15633     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15634       .addOperand(Base)
15635       .addOperand(Scale)
15636       .addOperand(Index)
15637       .addDisp(Disp, 16)
15638       .addOperand(Segment)
15639       .setMemRefs(MMOBegin, MMOEnd);
15640
15641     // Zero-extend the offset
15642     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15643       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15644         .addImm(0)
15645         .addReg(OffsetReg)
15646         .addImm(X86::sub_32bit);
15647
15648     // Add the offset to the reg_save_area to get the final address.
15649     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15650       .addReg(OffsetReg64)
15651       .addReg(RegSaveReg);
15652
15653     // Compute the offset for the next argument
15654     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15655     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15656       .addReg(OffsetReg)
15657       .addImm(UseFPOffset ? 16 : 8);
15658
15659     // Store it back into the va_list.
15660     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15661       .addOperand(Base)
15662       .addOperand(Scale)
15663       .addOperand(Index)
15664       .addDisp(Disp, UseFPOffset ? 4 : 0)
15665       .addOperand(Segment)
15666       .addReg(NextOffsetReg)
15667       .setMemRefs(MMOBegin, MMOEnd);
15668
15669     // Jump to endMBB
15670     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15671       .addMBB(endMBB);
15672   }
15673
15674   //
15675   // Emit code to use overflow area
15676   //
15677
15678   // Load the overflow_area address into a register.
15679   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15680   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15681     .addOperand(Base)
15682     .addOperand(Scale)
15683     .addOperand(Index)
15684     .addDisp(Disp, 8)
15685     .addOperand(Segment)
15686     .setMemRefs(MMOBegin, MMOEnd);
15687
15688   // If we need to align it, do so. Otherwise, just copy the address
15689   // to OverflowDestReg.
15690   if (NeedsAlign) {
15691     // Align the overflow address
15692     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15693     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15694
15695     // aligned_addr = (addr + (align-1)) & ~(align-1)
15696     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15697       .addReg(OverflowAddrReg)
15698       .addImm(Align-1);
15699
15700     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15701       .addReg(TmpReg)
15702       .addImm(~(uint64_t)(Align-1));
15703   } else {
15704     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15705       .addReg(OverflowAddrReg);
15706   }
15707
15708   // Compute the next overflow address after this argument.
15709   // (the overflow address should be kept 8-byte aligned)
15710   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15711   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15712     .addReg(OverflowDestReg)
15713     .addImm(ArgSizeA8);
15714
15715   // Store the new overflow address.
15716   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15717     .addOperand(Base)
15718     .addOperand(Scale)
15719     .addOperand(Index)
15720     .addDisp(Disp, 8)
15721     .addOperand(Segment)
15722     .addReg(NextAddrReg)
15723     .setMemRefs(MMOBegin, MMOEnd);
15724
15725   // If we branched, emit the PHI to the front of endMBB.
15726   if (offsetMBB) {
15727     BuildMI(*endMBB, endMBB->begin(), DL,
15728             TII->get(X86::PHI), DestReg)
15729       .addReg(OffsetDestReg).addMBB(offsetMBB)
15730       .addReg(OverflowDestReg).addMBB(overflowMBB);
15731   }
15732
15733   // Erase the pseudo instruction
15734   MI->eraseFromParent();
15735
15736   return endMBB;
15737 }
15738
15739 MachineBasicBlock *
15740 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15741                                                  MachineInstr *MI,
15742                                                  MachineBasicBlock *MBB) const {
15743   // Emit code to save XMM registers to the stack. The ABI says that the
15744   // number of registers to save is given in %al, so it's theoretically
15745   // possible to do an indirect jump trick to avoid saving all of them,
15746   // however this code takes a simpler approach and just executes all
15747   // of the stores if %al is non-zero. It's less code, and it's probably
15748   // easier on the hardware branch predictor, and stores aren't all that
15749   // expensive anyway.
15750
15751   // Create the new basic blocks. One block contains all the XMM stores,
15752   // and one block is the final destination regardless of whether any
15753   // stores were performed.
15754   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15755   MachineFunction *F = MBB->getParent();
15756   MachineFunction::iterator MBBIter = MBB;
15757   ++MBBIter;
15758   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15759   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15760   F->insert(MBBIter, XMMSaveMBB);
15761   F->insert(MBBIter, EndMBB);
15762
15763   // Transfer the remainder of MBB and its successor edges to EndMBB.
15764   EndMBB->splice(EndMBB->begin(), MBB,
15765                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15766   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15767
15768   // The original block will now fall through to the XMM save block.
15769   MBB->addSuccessor(XMMSaveMBB);
15770   // The XMMSaveMBB will fall through to the end block.
15771   XMMSaveMBB->addSuccessor(EndMBB);
15772
15773   // Now add the instructions.
15774   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15775   DebugLoc DL = MI->getDebugLoc();
15776
15777   unsigned CountReg = MI->getOperand(0).getReg();
15778   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15779   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15780
15781   if (!Subtarget->isTargetWin64()) {
15782     // If %al is 0, branch around the XMM save block.
15783     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15784     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15785     MBB->addSuccessor(EndMBB);
15786   }
15787
15788   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15789   // that was just emitted, but clearly shouldn't be "saved".
15790   assert((MI->getNumOperands() <= 3 ||
15791           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15792           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15793          && "Expected last argument to be EFLAGS");
15794   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15795   // In the XMM save block, save all the XMM argument registers.
15796   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15797     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15798     MachineMemOperand *MMO =
15799       F->getMachineMemOperand(
15800           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15801         MachineMemOperand::MOStore,
15802         /*Size=*/16, /*Align=*/16);
15803     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15804       .addFrameIndex(RegSaveFrameIndex)
15805       .addImm(/*Scale=*/1)
15806       .addReg(/*IndexReg=*/0)
15807       .addImm(/*Disp=*/Offset)
15808       .addReg(/*Segment=*/0)
15809       .addReg(MI->getOperand(i).getReg())
15810       .addMemOperand(MMO);
15811   }
15812
15813   MI->eraseFromParent();   // The pseudo instruction is gone now.
15814
15815   return EndMBB;
15816 }
15817
15818 // The EFLAGS operand of SelectItr might be missing a kill marker
15819 // because there were multiple uses of EFLAGS, and ISel didn't know
15820 // which to mark. Figure out whether SelectItr should have had a
15821 // kill marker, and set it if it should. Returns the correct kill
15822 // marker value.
15823 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15824                                      MachineBasicBlock* BB,
15825                                      const TargetRegisterInfo* TRI) {
15826   // Scan forward through BB for a use/def of EFLAGS.
15827   MachineBasicBlock::iterator miI(std::next(SelectItr));
15828   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15829     const MachineInstr& mi = *miI;
15830     if (mi.readsRegister(X86::EFLAGS))
15831       return false;
15832     if (mi.definesRegister(X86::EFLAGS))
15833       break; // Should have kill-flag - update below.
15834   }
15835
15836   // If we hit the end of the block, check whether EFLAGS is live into a
15837   // successor.
15838   if (miI == BB->end()) {
15839     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15840                                           sEnd = BB->succ_end();
15841          sItr != sEnd; ++sItr) {
15842       MachineBasicBlock* succ = *sItr;
15843       if (succ->isLiveIn(X86::EFLAGS))
15844         return false;
15845     }
15846   }
15847
15848   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15849   // out. SelectMI should have a kill flag on EFLAGS.
15850   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15851   return true;
15852 }
15853
15854 MachineBasicBlock *
15855 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15856                                      MachineBasicBlock *BB) const {
15857   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15858   DebugLoc DL = MI->getDebugLoc();
15859
15860   // To "insert" a SELECT_CC instruction, we actually have to insert the
15861   // diamond control-flow pattern.  The incoming instruction knows the
15862   // destination vreg to set, the condition code register to branch on, the
15863   // true/false values to select between, and a branch opcode to use.
15864   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15865   MachineFunction::iterator It = BB;
15866   ++It;
15867
15868   //  thisMBB:
15869   //  ...
15870   //   TrueVal = ...
15871   //   cmpTY ccX, r1, r2
15872   //   bCC copy1MBB
15873   //   fallthrough --> copy0MBB
15874   MachineBasicBlock *thisMBB = BB;
15875   MachineFunction *F = BB->getParent();
15876   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15877   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15878   F->insert(It, copy0MBB);
15879   F->insert(It, sinkMBB);
15880
15881   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15882   // live into the sink and copy blocks.
15883   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15884   if (!MI->killsRegister(X86::EFLAGS) &&
15885       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15886     copy0MBB->addLiveIn(X86::EFLAGS);
15887     sinkMBB->addLiveIn(X86::EFLAGS);
15888   }
15889
15890   // Transfer the remainder of BB and its successor edges to sinkMBB.
15891   sinkMBB->splice(sinkMBB->begin(), BB,
15892                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15893   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15894
15895   // Add the true and fallthrough blocks as its successors.
15896   BB->addSuccessor(copy0MBB);
15897   BB->addSuccessor(sinkMBB);
15898
15899   // Create the conditional branch instruction.
15900   unsigned Opc =
15901     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15902   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15903
15904   //  copy0MBB:
15905   //   %FalseValue = ...
15906   //   # fallthrough to sinkMBB
15907   copy0MBB->addSuccessor(sinkMBB);
15908
15909   //  sinkMBB:
15910   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15911   //  ...
15912   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15913           TII->get(X86::PHI), MI->getOperand(0).getReg())
15914     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15915     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15916
15917   MI->eraseFromParent();   // The pseudo instruction is gone now.
15918   return sinkMBB;
15919 }
15920
15921 MachineBasicBlock *
15922 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15923                                         bool Is64Bit) const {
15924   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15925   DebugLoc DL = MI->getDebugLoc();
15926   MachineFunction *MF = BB->getParent();
15927   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15928
15929   assert(MF->shouldSplitStack());
15930
15931   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15932   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15933
15934   // BB:
15935   //  ... [Till the alloca]
15936   // If stacklet is not large enough, jump to mallocMBB
15937   //
15938   // bumpMBB:
15939   //  Allocate by subtracting from RSP
15940   //  Jump to continueMBB
15941   //
15942   // mallocMBB:
15943   //  Allocate by call to runtime
15944   //
15945   // continueMBB:
15946   //  ...
15947   //  [rest of original BB]
15948   //
15949
15950   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15951   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15952   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15953
15954   MachineRegisterInfo &MRI = MF->getRegInfo();
15955   const TargetRegisterClass *AddrRegClass =
15956     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15957
15958   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15959     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15960     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15961     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15962     sizeVReg = MI->getOperand(1).getReg(),
15963     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15964
15965   MachineFunction::iterator MBBIter = BB;
15966   ++MBBIter;
15967
15968   MF->insert(MBBIter, bumpMBB);
15969   MF->insert(MBBIter, mallocMBB);
15970   MF->insert(MBBIter, continueMBB);
15971
15972   continueMBB->splice(continueMBB->begin(), BB,
15973                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
15974   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15975
15976   // Add code to the main basic block to check if the stack limit has been hit,
15977   // and if so, jump to mallocMBB otherwise to bumpMBB.
15978   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15979   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15980     .addReg(tmpSPVReg).addReg(sizeVReg);
15981   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15982     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15983     .addReg(SPLimitVReg);
15984   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15985
15986   // bumpMBB simply decreases the stack pointer, since we know the current
15987   // stacklet has enough space.
15988   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15989     .addReg(SPLimitVReg);
15990   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15991     .addReg(SPLimitVReg);
15992   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15993
15994   // Calls into a routine in libgcc to allocate more space from the heap.
15995   const uint32_t *RegMask =
15996     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15997   if (Is64Bit) {
15998     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15999       .addReg(sizeVReg);
16000     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16001       .addExternalSymbol("__morestack_allocate_stack_space")
16002       .addRegMask(RegMask)
16003       .addReg(X86::RDI, RegState::Implicit)
16004       .addReg(X86::RAX, RegState::ImplicitDefine);
16005   } else {
16006     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16007       .addImm(12);
16008     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16009     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16010       .addExternalSymbol("__morestack_allocate_stack_space")
16011       .addRegMask(RegMask)
16012       .addReg(X86::EAX, RegState::ImplicitDefine);
16013   }
16014
16015   if (!Is64Bit)
16016     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16017       .addImm(16);
16018
16019   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16020     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16021   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16022
16023   // Set up the CFG correctly.
16024   BB->addSuccessor(bumpMBB);
16025   BB->addSuccessor(mallocMBB);
16026   mallocMBB->addSuccessor(continueMBB);
16027   bumpMBB->addSuccessor(continueMBB);
16028
16029   // Take care of the PHI nodes.
16030   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16031           MI->getOperand(0).getReg())
16032     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16033     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16034
16035   // Delete the original pseudo instruction.
16036   MI->eraseFromParent();
16037
16038   // And we're done.
16039   return continueMBB;
16040 }
16041
16042 MachineBasicBlock *
16043 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16044                                           MachineBasicBlock *BB) const {
16045   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16046   DebugLoc DL = MI->getDebugLoc();
16047
16048   assert(!Subtarget->isTargetMacho());
16049
16050   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16051   // non-trivial part is impdef of ESP.
16052
16053   if (Subtarget->isTargetWin64()) {
16054     if (Subtarget->isTargetCygMing()) {
16055       // ___chkstk(Mingw64):
16056       // Clobbers R10, R11, RAX and EFLAGS.
16057       // Updates RSP.
16058       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16059         .addExternalSymbol("___chkstk")
16060         .addReg(X86::RAX, RegState::Implicit)
16061         .addReg(X86::RSP, RegState::Implicit)
16062         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16063         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16064         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16065     } else {
16066       // __chkstk(MSVCRT): does not update stack pointer.
16067       // Clobbers R10, R11 and EFLAGS.
16068       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16069         .addExternalSymbol("__chkstk")
16070         .addReg(X86::RAX, RegState::Implicit)
16071         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16072       // RAX has the offset to be subtracted from RSP.
16073       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16074         .addReg(X86::RSP)
16075         .addReg(X86::RAX);
16076     }
16077   } else {
16078     const char *StackProbeSymbol =
16079       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16080
16081     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16082       .addExternalSymbol(StackProbeSymbol)
16083       .addReg(X86::EAX, RegState::Implicit)
16084       .addReg(X86::ESP, RegState::Implicit)
16085       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16086       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16087       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16088   }
16089
16090   MI->eraseFromParent();   // The pseudo instruction is gone now.
16091   return BB;
16092 }
16093
16094 MachineBasicBlock *
16095 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16096                                       MachineBasicBlock *BB) const {
16097   // This is pretty easy.  We're taking the value that we received from
16098   // our load from the relocation, sticking it in either RDI (x86-64)
16099   // or EAX and doing an indirect call.  The return value will then
16100   // be in the normal return register.
16101   const X86InstrInfo *TII
16102     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16103   DebugLoc DL = MI->getDebugLoc();
16104   MachineFunction *F = BB->getParent();
16105
16106   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16107   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16108
16109   // Get a register mask for the lowered call.
16110   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16111   // proper register mask.
16112   const uint32_t *RegMask =
16113     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16114   if (Subtarget->is64Bit()) {
16115     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16116                                       TII->get(X86::MOV64rm), X86::RDI)
16117     .addReg(X86::RIP)
16118     .addImm(0).addReg(0)
16119     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16120                       MI->getOperand(3).getTargetFlags())
16121     .addReg(0);
16122     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16123     addDirectMem(MIB, X86::RDI);
16124     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16125   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16126     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16127                                       TII->get(X86::MOV32rm), X86::EAX)
16128     .addReg(0)
16129     .addImm(0).addReg(0)
16130     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16131                       MI->getOperand(3).getTargetFlags())
16132     .addReg(0);
16133     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16134     addDirectMem(MIB, X86::EAX);
16135     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16136   } else {
16137     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16138                                       TII->get(X86::MOV32rm), X86::EAX)
16139     .addReg(TII->getGlobalBaseReg(F))
16140     .addImm(0).addReg(0)
16141     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16142                       MI->getOperand(3).getTargetFlags())
16143     .addReg(0);
16144     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16145     addDirectMem(MIB, X86::EAX);
16146     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16147   }
16148
16149   MI->eraseFromParent(); // The pseudo instruction is gone now.
16150   return BB;
16151 }
16152
16153 MachineBasicBlock *
16154 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16155                                     MachineBasicBlock *MBB) const {
16156   DebugLoc DL = MI->getDebugLoc();
16157   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16158
16159   MachineFunction *MF = MBB->getParent();
16160   MachineRegisterInfo &MRI = MF->getRegInfo();
16161
16162   const BasicBlock *BB = MBB->getBasicBlock();
16163   MachineFunction::iterator I = MBB;
16164   ++I;
16165
16166   // Memory Reference
16167   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16168   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16169
16170   unsigned DstReg;
16171   unsigned MemOpndSlot = 0;
16172
16173   unsigned CurOp = 0;
16174
16175   DstReg = MI->getOperand(CurOp++).getReg();
16176   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16177   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16178   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16179   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16180
16181   MemOpndSlot = CurOp;
16182
16183   MVT PVT = getPointerTy();
16184   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16185          "Invalid Pointer Size!");
16186
16187   // For v = setjmp(buf), we generate
16188   //
16189   // thisMBB:
16190   //  buf[LabelOffset] = restoreMBB
16191   //  SjLjSetup restoreMBB
16192   //
16193   // mainMBB:
16194   //  v_main = 0
16195   //
16196   // sinkMBB:
16197   //  v = phi(main, restore)
16198   //
16199   // restoreMBB:
16200   //  v_restore = 1
16201
16202   MachineBasicBlock *thisMBB = MBB;
16203   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16204   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16205   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16206   MF->insert(I, mainMBB);
16207   MF->insert(I, sinkMBB);
16208   MF->push_back(restoreMBB);
16209
16210   MachineInstrBuilder MIB;
16211
16212   // Transfer the remainder of BB and its successor edges to sinkMBB.
16213   sinkMBB->splice(sinkMBB->begin(), MBB,
16214                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16215   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16216
16217   // thisMBB:
16218   unsigned PtrStoreOpc = 0;
16219   unsigned LabelReg = 0;
16220   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16221   Reloc::Model RM = getTargetMachine().getRelocationModel();
16222   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16223                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16224
16225   // Prepare IP either in reg or imm.
16226   if (!UseImmLabel) {
16227     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16228     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16229     LabelReg = MRI.createVirtualRegister(PtrRC);
16230     if (Subtarget->is64Bit()) {
16231       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16232               .addReg(X86::RIP)
16233               .addImm(0)
16234               .addReg(0)
16235               .addMBB(restoreMBB)
16236               .addReg(0);
16237     } else {
16238       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16239       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16240               .addReg(XII->getGlobalBaseReg(MF))
16241               .addImm(0)
16242               .addReg(0)
16243               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16244               .addReg(0);
16245     }
16246   } else
16247     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16248   // Store IP
16249   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16250   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16251     if (i == X86::AddrDisp)
16252       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16253     else
16254       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16255   }
16256   if (!UseImmLabel)
16257     MIB.addReg(LabelReg);
16258   else
16259     MIB.addMBB(restoreMBB);
16260   MIB.setMemRefs(MMOBegin, MMOEnd);
16261   // Setup
16262   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16263           .addMBB(restoreMBB);
16264
16265   const X86RegisterInfo *RegInfo =
16266     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16267   MIB.addRegMask(RegInfo->getNoPreservedMask());
16268   thisMBB->addSuccessor(mainMBB);
16269   thisMBB->addSuccessor(restoreMBB);
16270
16271   // mainMBB:
16272   //  EAX = 0
16273   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16274   mainMBB->addSuccessor(sinkMBB);
16275
16276   // sinkMBB:
16277   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16278           TII->get(X86::PHI), DstReg)
16279     .addReg(mainDstReg).addMBB(mainMBB)
16280     .addReg(restoreDstReg).addMBB(restoreMBB);
16281
16282   // restoreMBB:
16283   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16284   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16285   restoreMBB->addSuccessor(sinkMBB);
16286
16287   MI->eraseFromParent();
16288   return sinkMBB;
16289 }
16290
16291 MachineBasicBlock *
16292 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16293                                      MachineBasicBlock *MBB) const {
16294   DebugLoc DL = MI->getDebugLoc();
16295   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16296
16297   MachineFunction *MF = MBB->getParent();
16298   MachineRegisterInfo &MRI = MF->getRegInfo();
16299
16300   // Memory Reference
16301   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16302   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16303
16304   MVT PVT = getPointerTy();
16305   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16306          "Invalid Pointer Size!");
16307
16308   const TargetRegisterClass *RC =
16309     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16310   unsigned Tmp = MRI.createVirtualRegister(RC);
16311   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16312   const X86RegisterInfo *RegInfo =
16313     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16314   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16315   unsigned SP = RegInfo->getStackRegister();
16316
16317   MachineInstrBuilder MIB;
16318
16319   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16320   const int64_t SPOffset = 2 * PVT.getStoreSize();
16321
16322   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16323   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16324
16325   // Reload FP
16326   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16327   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16328     MIB.addOperand(MI->getOperand(i));
16329   MIB.setMemRefs(MMOBegin, MMOEnd);
16330   // Reload IP
16331   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16332   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16333     if (i == X86::AddrDisp)
16334       MIB.addDisp(MI->getOperand(i), LabelOffset);
16335     else
16336       MIB.addOperand(MI->getOperand(i));
16337   }
16338   MIB.setMemRefs(MMOBegin, MMOEnd);
16339   // Reload SP
16340   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16341   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16342     if (i == X86::AddrDisp)
16343       MIB.addDisp(MI->getOperand(i), SPOffset);
16344     else
16345       MIB.addOperand(MI->getOperand(i));
16346   }
16347   MIB.setMemRefs(MMOBegin, MMOEnd);
16348   // Jump
16349   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16350
16351   MI->eraseFromParent();
16352   return MBB;
16353 }
16354
16355 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16356 // accumulator loops. Writing back to the accumulator allows the coalescer
16357 // to remove extra copies in the loop.   
16358 MachineBasicBlock *
16359 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16360                                  MachineBasicBlock *MBB) const {
16361   MachineOperand &AddendOp = MI->getOperand(3);
16362
16363   // Bail out early if the addend isn't a register - we can't switch these.
16364   if (!AddendOp.isReg())
16365     return MBB;
16366
16367   MachineFunction &MF = *MBB->getParent();
16368   MachineRegisterInfo &MRI = MF.getRegInfo();
16369
16370   // Check whether the addend is defined by a PHI:
16371   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16372   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16373   if (!AddendDef.isPHI())
16374     return MBB;
16375
16376   // Look for the following pattern:
16377   // loop:
16378   //   %addend = phi [%entry, 0], [%loop, %result]
16379   //   ...
16380   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16381
16382   // Replace with:
16383   //   loop:
16384   //   %addend = phi [%entry, 0], [%loop, %result]
16385   //   ...
16386   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16387
16388   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16389     assert(AddendDef.getOperand(i).isReg());
16390     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16391     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16392     if (&PHISrcInst == MI) {
16393       // Found a matching instruction.
16394       unsigned NewFMAOpc = 0;
16395       switch (MI->getOpcode()) {
16396         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16397         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16398         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16399         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16400         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16401         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16402         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16403         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16404         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16405         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16406         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16407         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16408         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16409         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16410         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16411         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16412         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16413         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16414         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16415         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16416         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16417         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16418         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16419         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16420         default: llvm_unreachable("Unrecognized FMA variant.");
16421       }
16422
16423       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16424       MachineInstrBuilder MIB =
16425         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16426         .addOperand(MI->getOperand(0))
16427         .addOperand(MI->getOperand(3))
16428         .addOperand(MI->getOperand(2))
16429         .addOperand(MI->getOperand(1));
16430       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16431       MI->eraseFromParent();
16432     }
16433   }
16434
16435   return MBB;
16436 }
16437
16438 MachineBasicBlock *
16439 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16440                                                MachineBasicBlock *BB) const {
16441   switch (MI->getOpcode()) {
16442   default: llvm_unreachable("Unexpected instr type to insert");
16443   case X86::TAILJMPd64:
16444   case X86::TAILJMPr64:
16445   case X86::TAILJMPm64:
16446     llvm_unreachable("TAILJMP64 would not be touched here.");
16447   case X86::TCRETURNdi64:
16448   case X86::TCRETURNri64:
16449   case X86::TCRETURNmi64:
16450     return BB;
16451   case X86::WIN_ALLOCA:
16452     return EmitLoweredWinAlloca(MI, BB);
16453   case X86::SEG_ALLOCA_32:
16454     return EmitLoweredSegAlloca(MI, BB, false);
16455   case X86::SEG_ALLOCA_64:
16456     return EmitLoweredSegAlloca(MI, BB, true);
16457   case X86::TLSCall_32:
16458   case X86::TLSCall_64:
16459     return EmitLoweredTLSCall(MI, BB);
16460   case X86::CMOV_GR8:
16461   case X86::CMOV_FR32:
16462   case X86::CMOV_FR64:
16463   case X86::CMOV_V4F32:
16464   case X86::CMOV_V2F64:
16465   case X86::CMOV_V2I64:
16466   case X86::CMOV_V8F32:
16467   case X86::CMOV_V4F64:
16468   case X86::CMOV_V4I64:
16469   case X86::CMOV_V16F32:
16470   case X86::CMOV_V8F64:
16471   case X86::CMOV_V8I64:
16472   case X86::CMOV_GR16:
16473   case X86::CMOV_GR32:
16474   case X86::CMOV_RFP32:
16475   case X86::CMOV_RFP64:
16476   case X86::CMOV_RFP80:
16477     return EmitLoweredSelect(MI, BB);
16478
16479   case X86::FP32_TO_INT16_IN_MEM:
16480   case X86::FP32_TO_INT32_IN_MEM:
16481   case X86::FP32_TO_INT64_IN_MEM:
16482   case X86::FP64_TO_INT16_IN_MEM:
16483   case X86::FP64_TO_INT32_IN_MEM:
16484   case X86::FP64_TO_INT64_IN_MEM:
16485   case X86::FP80_TO_INT16_IN_MEM:
16486   case X86::FP80_TO_INT32_IN_MEM:
16487   case X86::FP80_TO_INT64_IN_MEM: {
16488     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16489     DebugLoc DL = MI->getDebugLoc();
16490
16491     // Change the floating point control register to use "round towards zero"
16492     // mode when truncating to an integer value.
16493     MachineFunction *F = BB->getParent();
16494     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16495     addFrameReference(BuildMI(*BB, MI, DL,
16496                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16497
16498     // Load the old value of the high byte of the control word...
16499     unsigned OldCW =
16500       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16501     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16502                       CWFrameIdx);
16503
16504     // Set the high part to be round to zero...
16505     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16506       .addImm(0xC7F);
16507
16508     // Reload the modified control word now...
16509     addFrameReference(BuildMI(*BB, MI, DL,
16510                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16511
16512     // Restore the memory image of control word to original value
16513     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16514       .addReg(OldCW);
16515
16516     // Get the X86 opcode to use.
16517     unsigned Opc;
16518     switch (MI->getOpcode()) {
16519     default: llvm_unreachable("illegal opcode!");
16520     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16521     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16522     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16523     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16524     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16525     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16526     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16527     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16528     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16529     }
16530
16531     X86AddressMode AM;
16532     MachineOperand &Op = MI->getOperand(0);
16533     if (Op.isReg()) {
16534       AM.BaseType = X86AddressMode::RegBase;
16535       AM.Base.Reg = Op.getReg();
16536     } else {
16537       AM.BaseType = X86AddressMode::FrameIndexBase;
16538       AM.Base.FrameIndex = Op.getIndex();
16539     }
16540     Op = MI->getOperand(1);
16541     if (Op.isImm())
16542       AM.Scale = Op.getImm();
16543     Op = MI->getOperand(2);
16544     if (Op.isImm())
16545       AM.IndexReg = Op.getImm();
16546     Op = MI->getOperand(3);
16547     if (Op.isGlobal()) {
16548       AM.GV = Op.getGlobal();
16549     } else {
16550       AM.Disp = Op.getImm();
16551     }
16552     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16553                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16554
16555     // Reload the original control word now.
16556     addFrameReference(BuildMI(*BB, MI, DL,
16557                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16558
16559     MI->eraseFromParent();   // The pseudo instruction is gone now.
16560     return BB;
16561   }
16562     // String/text processing lowering.
16563   case X86::PCMPISTRM128REG:
16564   case X86::VPCMPISTRM128REG:
16565   case X86::PCMPISTRM128MEM:
16566   case X86::VPCMPISTRM128MEM:
16567   case X86::PCMPESTRM128REG:
16568   case X86::VPCMPESTRM128REG:
16569   case X86::PCMPESTRM128MEM:
16570   case X86::VPCMPESTRM128MEM:
16571     assert(Subtarget->hasSSE42() &&
16572            "Target must have SSE4.2 or AVX features enabled");
16573     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16574
16575   // String/text processing lowering.
16576   case X86::PCMPISTRIREG:
16577   case X86::VPCMPISTRIREG:
16578   case X86::PCMPISTRIMEM:
16579   case X86::VPCMPISTRIMEM:
16580   case X86::PCMPESTRIREG:
16581   case X86::VPCMPESTRIREG:
16582   case X86::PCMPESTRIMEM:
16583   case X86::VPCMPESTRIMEM:
16584     assert(Subtarget->hasSSE42() &&
16585            "Target must have SSE4.2 or AVX features enabled");
16586     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16587
16588   // Thread synchronization.
16589   case X86::MONITOR:
16590     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16591
16592   // xbegin
16593   case X86::XBEGIN:
16594     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16595
16596   // Atomic Lowering.
16597   case X86::ATOMAND8:
16598   case X86::ATOMAND16:
16599   case X86::ATOMAND32:
16600   case X86::ATOMAND64:
16601     // Fall through
16602   case X86::ATOMOR8:
16603   case X86::ATOMOR16:
16604   case X86::ATOMOR32:
16605   case X86::ATOMOR64:
16606     // Fall through
16607   case X86::ATOMXOR16:
16608   case X86::ATOMXOR8:
16609   case X86::ATOMXOR32:
16610   case X86::ATOMXOR64:
16611     // Fall through
16612   case X86::ATOMNAND8:
16613   case X86::ATOMNAND16:
16614   case X86::ATOMNAND32:
16615   case X86::ATOMNAND64:
16616     // Fall through
16617   case X86::ATOMMAX8:
16618   case X86::ATOMMAX16:
16619   case X86::ATOMMAX32:
16620   case X86::ATOMMAX64:
16621     // Fall through
16622   case X86::ATOMMIN8:
16623   case X86::ATOMMIN16:
16624   case X86::ATOMMIN32:
16625   case X86::ATOMMIN64:
16626     // Fall through
16627   case X86::ATOMUMAX8:
16628   case X86::ATOMUMAX16:
16629   case X86::ATOMUMAX32:
16630   case X86::ATOMUMAX64:
16631     // Fall through
16632   case X86::ATOMUMIN8:
16633   case X86::ATOMUMIN16:
16634   case X86::ATOMUMIN32:
16635   case X86::ATOMUMIN64:
16636     return EmitAtomicLoadArith(MI, BB);
16637
16638   // This group does 64-bit operations on a 32-bit host.
16639   case X86::ATOMAND6432:
16640   case X86::ATOMOR6432:
16641   case X86::ATOMXOR6432:
16642   case X86::ATOMNAND6432:
16643   case X86::ATOMADD6432:
16644   case X86::ATOMSUB6432:
16645   case X86::ATOMMAX6432:
16646   case X86::ATOMMIN6432:
16647   case X86::ATOMUMAX6432:
16648   case X86::ATOMUMIN6432:
16649   case X86::ATOMSWAP6432:
16650     return EmitAtomicLoadArith6432(MI, BB);
16651
16652   case X86::VASTART_SAVE_XMM_REGS:
16653     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16654
16655   case X86::VAARG_64:
16656     return EmitVAARG64WithCustomInserter(MI, BB);
16657
16658   case X86::EH_SjLj_SetJmp32:
16659   case X86::EH_SjLj_SetJmp64:
16660     return emitEHSjLjSetJmp(MI, BB);
16661
16662   case X86::EH_SjLj_LongJmp32:
16663   case X86::EH_SjLj_LongJmp64:
16664     return emitEHSjLjLongJmp(MI, BB);
16665
16666   case TargetOpcode::STACKMAP:
16667   case TargetOpcode::PATCHPOINT:
16668     return emitPatchPoint(MI, BB);
16669
16670   case X86::VFMADDPDr213r:
16671   case X86::VFMADDPSr213r:
16672   case X86::VFMADDSDr213r:
16673   case X86::VFMADDSSr213r:
16674   case X86::VFMSUBPDr213r:
16675   case X86::VFMSUBPSr213r:
16676   case X86::VFMSUBSDr213r:
16677   case X86::VFMSUBSSr213r:
16678   case X86::VFNMADDPDr213r:
16679   case X86::VFNMADDPSr213r:
16680   case X86::VFNMADDSDr213r:
16681   case X86::VFNMADDSSr213r:
16682   case X86::VFNMSUBPDr213r:
16683   case X86::VFNMSUBPSr213r:
16684   case X86::VFNMSUBSDr213r:
16685   case X86::VFNMSUBSSr213r:
16686   case X86::VFMADDPDr213rY:
16687   case X86::VFMADDPSr213rY:
16688   case X86::VFMSUBPDr213rY:
16689   case X86::VFMSUBPSr213rY:
16690   case X86::VFNMADDPDr213rY:
16691   case X86::VFNMADDPSr213rY:
16692   case X86::VFNMSUBPDr213rY:
16693   case X86::VFNMSUBPSr213rY:
16694     return emitFMA3Instr(MI, BB);
16695   }
16696 }
16697
16698 //===----------------------------------------------------------------------===//
16699 //                           X86 Optimization Hooks
16700 //===----------------------------------------------------------------------===//
16701
16702 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16703                                                        APInt &KnownZero,
16704                                                        APInt &KnownOne,
16705                                                        const SelectionDAG &DAG,
16706                                                        unsigned Depth) const {
16707   unsigned BitWidth = KnownZero.getBitWidth();
16708   unsigned Opc = Op.getOpcode();
16709   assert((Opc >= ISD::BUILTIN_OP_END ||
16710           Opc == ISD::INTRINSIC_WO_CHAIN ||
16711           Opc == ISD::INTRINSIC_W_CHAIN ||
16712           Opc == ISD::INTRINSIC_VOID) &&
16713          "Should use MaskedValueIsZero if you don't know whether Op"
16714          " is a target node!");
16715
16716   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16717   switch (Opc) {
16718   default: break;
16719   case X86ISD::ADD:
16720   case X86ISD::SUB:
16721   case X86ISD::ADC:
16722   case X86ISD::SBB:
16723   case X86ISD::SMUL:
16724   case X86ISD::UMUL:
16725   case X86ISD::INC:
16726   case X86ISD::DEC:
16727   case X86ISD::OR:
16728   case X86ISD::XOR:
16729   case X86ISD::AND:
16730     // These nodes' second result is a boolean.
16731     if (Op.getResNo() == 0)
16732       break;
16733     // Fallthrough
16734   case X86ISD::SETCC:
16735     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16736     break;
16737   case ISD::INTRINSIC_WO_CHAIN: {
16738     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16739     unsigned NumLoBits = 0;
16740     switch (IntId) {
16741     default: break;
16742     case Intrinsic::x86_sse_movmsk_ps:
16743     case Intrinsic::x86_avx_movmsk_ps_256:
16744     case Intrinsic::x86_sse2_movmsk_pd:
16745     case Intrinsic::x86_avx_movmsk_pd_256:
16746     case Intrinsic::x86_mmx_pmovmskb:
16747     case Intrinsic::x86_sse2_pmovmskb_128:
16748     case Intrinsic::x86_avx2_pmovmskb: {
16749       // High bits of movmskp{s|d}, pmovmskb are known zero.
16750       switch (IntId) {
16751         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16752         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16753         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16754         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16755         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16756         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16757         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16758         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16759       }
16760       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16761       break;
16762     }
16763     }
16764     break;
16765   }
16766   }
16767 }
16768
16769 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16770   SDValue Op,
16771   const SelectionDAG &,
16772   unsigned Depth) const {
16773   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16774   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16775     return Op.getValueType().getScalarType().getSizeInBits();
16776
16777   // Fallback case.
16778   return 1;
16779 }
16780
16781 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16782 /// node is a GlobalAddress + offset.
16783 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16784                                        const GlobalValue* &GA,
16785                                        int64_t &Offset) const {
16786   if (N->getOpcode() == X86ISD::Wrapper) {
16787     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16788       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16789       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16790       return true;
16791     }
16792   }
16793   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16794 }
16795
16796 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16797 /// same as extracting the high 128-bit part of 256-bit vector and then
16798 /// inserting the result into the low part of a new 256-bit vector
16799 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16800   EVT VT = SVOp->getValueType(0);
16801   unsigned NumElems = VT.getVectorNumElements();
16802
16803   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16804   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16805     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16806         SVOp->getMaskElt(j) >= 0)
16807       return false;
16808
16809   return true;
16810 }
16811
16812 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16813 /// same as extracting the low 128-bit part of 256-bit vector and then
16814 /// inserting the result into the high part of a new 256-bit vector
16815 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16816   EVT VT = SVOp->getValueType(0);
16817   unsigned NumElems = VT.getVectorNumElements();
16818
16819   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16820   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16821     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16822         SVOp->getMaskElt(j) >= 0)
16823       return false;
16824
16825   return true;
16826 }
16827
16828 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16829 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16830                                         TargetLowering::DAGCombinerInfo &DCI,
16831                                         const X86Subtarget* Subtarget) {
16832   SDLoc dl(N);
16833   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16834   SDValue V1 = SVOp->getOperand(0);
16835   SDValue V2 = SVOp->getOperand(1);
16836   EVT VT = SVOp->getValueType(0);
16837   unsigned NumElems = VT.getVectorNumElements();
16838
16839   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16840       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16841     //
16842     //                   0,0,0,...
16843     //                      |
16844     //    V      UNDEF    BUILD_VECTOR    UNDEF
16845     //     \      /           \           /
16846     //  CONCAT_VECTOR         CONCAT_VECTOR
16847     //         \                  /
16848     //          \                /
16849     //          RESULT: V + zero extended
16850     //
16851     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16852         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16853         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16854       return SDValue();
16855
16856     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16857       return SDValue();
16858
16859     // To match the shuffle mask, the first half of the mask should
16860     // be exactly the first vector, and all the rest a splat with the
16861     // first element of the second one.
16862     for (unsigned i = 0; i != NumElems/2; ++i)
16863       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16864           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16865         return SDValue();
16866
16867     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16868     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16869       if (Ld->hasNUsesOfValue(1, 0)) {
16870         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16871         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16872         SDValue ResNode =
16873           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16874                                   array_lengthof(Ops),
16875                                   Ld->getMemoryVT(),
16876                                   Ld->getPointerInfo(),
16877                                   Ld->getAlignment(),
16878                                   false/*isVolatile*/, true/*ReadMem*/,
16879                                   false/*WriteMem*/);
16880
16881         // Make sure the newly-created LOAD is in the same position as Ld in
16882         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16883         // and update uses of Ld's output chain to use the TokenFactor.
16884         if (Ld->hasAnyUseOfValue(1)) {
16885           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16886                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16887           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16888           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16889                                  SDValue(ResNode.getNode(), 1));
16890         }
16891
16892         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16893       }
16894     }
16895
16896     // Emit a zeroed vector and insert the desired subvector on its
16897     // first half.
16898     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16899     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16900     return DCI.CombineTo(N, InsV);
16901   }
16902
16903   //===--------------------------------------------------------------------===//
16904   // Combine some shuffles into subvector extracts and inserts:
16905   //
16906
16907   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16908   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16909     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16910     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16911     return DCI.CombineTo(N, InsV);
16912   }
16913
16914   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16915   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16916     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16917     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16918     return DCI.CombineTo(N, InsV);
16919   }
16920
16921   return SDValue();
16922 }
16923
16924 /// PerformShuffleCombine - Performs several different shuffle combines.
16925 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16926                                      TargetLowering::DAGCombinerInfo &DCI,
16927                                      const X86Subtarget *Subtarget) {
16928   SDLoc dl(N);
16929   EVT VT = N->getValueType(0);
16930
16931   // Don't create instructions with illegal types after legalize types has run.
16932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16933   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16934     return SDValue();
16935
16936   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16937   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16938       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16939     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16940
16941   // Only handle 128 wide vector from here on.
16942   if (!VT.is128BitVector())
16943     return SDValue();
16944
16945   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16946   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16947   // consecutive, non-overlapping, and in the right order.
16948   SmallVector<SDValue, 16> Elts;
16949   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16950     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16951
16952   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16953 }
16954
16955 /// PerformTruncateCombine - Converts truncate operation to
16956 /// a sequence of vector shuffle operations.
16957 /// It is possible when we truncate 256-bit vector to 128-bit vector
16958 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16959                                       TargetLowering::DAGCombinerInfo &DCI,
16960                                       const X86Subtarget *Subtarget)  {
16961   return SDValue();
16962 }
16963
16964 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16965 /// specific shuffle of a load can be folded into a single element load.
16966 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16967 /// shuffles have been customed lowered so we need to handle those here.
16968 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16969                                          TargetLowering::DAGCombinerInfo &DCI) {
16970   if (DCI.isBeforeLegalizeOps())
16971     return SDValue();
16972
16973   SDValue InVec = N->getOperand(0);
16974   SDValue EltNo = N->getOperand(1);
16975
16976   if (!isa<ConstantSDNode>(EltNo))
16977     return SDValue();
16978
16979   EVT VT = InVec.getValueType();
16980
16981   bool HasShuffleIntoBitcast = false;
16982   if (InVec.getOpcode() == ISD::BITCAST) {
16983     // Don't duplicate a load with other uses.
16984     if (!InVec.hasOneUse())
16985       return SDValue();
16986     EVT BCVT = InVec.getOperand(0).getValueType();
16987     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16988       return SDValue();
16989     InVec = InVec.getOperand(0);
16990     HasShuffleIntoBitcast = true;
16991   }
16992
16993   if (!isTargetShuffle(InVec.getOpcode()))
16994     return SDValue();
16995
16996   // Don't duplicate a load with other uses.
16997   if (!InVec.hasOneUse())
16998     return SDValue();
16999
17000   SmallVector<int, 16> ShuffleMask;
17001   bool UnaryShuffle;
17002   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17003                             UnaryShuffle))
17004     return SDValue();
17005
17006   // Select the input vector, guarding against out of range extract vector.
17007   unsigned NumElems = VT.getVectorNumElements();
17008   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17009   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17010   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17011                                          : InVec.getOperand(1);
17012
17013   // If inputs to shuffle are the same for both ops, then allow 2 uses
17014   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17015
17016   if (LdNode.getOpcode() == ISD::BITCAST) {
17017     // Don't duplicate a load with other uses.
17018     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17019       return SDValue();
17020
17021     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17022     LdNode = LdNode.getOperand(0);
17023   }
17024
17025   if (!ISD::isNormalLoad(LdNode.getNode()))
17026     return SDValue();
17027
17028   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17029
17030   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17031     return SDValue();
17032
17033   if (HasShuffleIntoBitcast) {
17034     // If there's a bitcast before the shuffle, check if the load type and
17035     // alignment is valid.
17036     unsigned Align = LN0->getAlignment();
17037     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17038     unsigned NewAlign = TLI.getDataLayout()->
17039       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17040
17041     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17042       return SDValue();
17043   }
17044
17045   // All checks match so transform back to vector_shuffle so that DAG combiner
17046   // can finish the job
17047   SDLoc dl(N);
17048
17049   // Create shuffle node taking into account the case that its a unary shuffle
17050   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17051   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17052                                  InVec.getOperand(0), Shuffle,
17053                                  &ShuffleMask[0]);
17054   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17055   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17056                      EltNo);
17057 }
17058
17059 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17060 /// generation and convert it from being a bunch of shuffles and extracts
17061 /// to a simple store and scalar loads to extract the elements.
17062 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17063                                          TargetLowering::DAGCombinerInfo &DCI) {
17064   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17065   if (NewOp.getNode())
17066     return NewOp;
17067
17068   SDValue InputVector = N->getOperand(0);
17069
17070   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17071   // from mmx to v2i32 has a single usage.
17072   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17073       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17074       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17075     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17076                        N->getValueType(0),
17077                        InputVector.getNode()->getOperand(0));
17078
17079   // Only operate on vectors of 4 elements, where the alternative shuffling
17080   // gets to be more expensive.
17081   if (InputVector.getValueType() != MVT::v4i32)
17082     return SDValue();
17083
17084   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17085   // single use which is a sign-extend or zero-extend, and all elements are
17086   // used.
17087   SmallVector<SDNode *, 4> Uses;
17088   unsigned ExtractedElements = 0;
17089   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17090        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17091     if (UI.getUse().getResNo() != InputVector.getResNo())
17092       return SDValue();
17093
17094     SDNode *Extract = *UI;
17095     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17096       return SDValue();
17097
17098     if (Extract->getValueType(0) != MVT::i32)
17099       return SDValue();
17100     if (!Extract->hasOneUse())
17101       return SDValue();
17102     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17103         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17104       return SDValue();
17105     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17106       return SDValue();
17107
17108     // Record which element was extracted.
17109     ExtractedElements |=
17110       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17111
17112     Uses.push_back(Extract);
17113   }
17114
17115   // If not all the elements were used, this may not be worthwhile.
17116   if (ExtractedElements != 15)
17117     return SDValue();
17118
17119   // Ok, we've now decided to do the transformation.
17120   SDLoc dl(InputVector);
17121
17122   // Store the value to a temporary stack slot.
17123   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17124   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17125                             MachinePointerInfo(), false, false, 0);
17126
17127   // Replace each use (extract) with a load of the appropriate element.
17128   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17129        UE = Uses.end(); UI != UE; ++UI) {
17130     SDNode *Extract = *UI;
17131
17132     // cOMpute the element's address.
17133     SDValue Idx = Extract->getOperand(1);
17134     unsigned EltSize =
17135         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17136     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17137     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17138     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17139
17140     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17141                                      StackPtr, OffsetVal);
17142
17143     // Load the scalar.
17144     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17145                                      ScalarAddr, MachinePointerInfo(),
17146                                      false, false, false, 0);
17147
17148     // Replace the exact with the load.
17149     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17150   }
17151
17152   // The replacement was made in place; don't return anything.
17153   return SDValue();
17154 }
17155
17156 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17157 static std::pair<unsigned, bool>
17158 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17159                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17160   if (!VT.isVector())
17161     return std::make_pair(0, false);
17162
17163   bool NeedSplit = false;
17164   switch (VT.getSimpleVT().SimpleTy) {
17165   default: return std::make_pair(0, false);
17166   case MVT::v32i8:
17167   case MVT::v16i16:
17168   case MVT::v8i32:
17169     if (!Subtarget->hasAVX2())
17170       NeedSplit = true;
17171     if (!Subtarget->hasAVX())
17172       return std::make_pair(0, false);
17173     break;
17174   case MVT::v16i8:
17175   case MVT::v8i16:
17176   case MVT::v4i32:
17177     if (!Subtarget->hasSSE2())
17178       return std::make_pair(0, false);
17179   }
17180
17181   // SSE2 has only a small subset of the operations.
17182   bool hasUnsigned = Subtarget->hasSSE41() ||
17183                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17184   bool hasSigned = Subtarget->hasSSE41() ||
17185                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17186
17187   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17188
17189   unsigned Opc = 0;
17190   // Check for x CC y ? x : y.
17191   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17192       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17193     switch (CC) {
17194     default: break;
17195     case ISD::SETULT:
17196     case ISD::SETULE:
17197       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17198     case ISD::SETUGT:
17199     case ISD::SETUGE:
17200       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17201     case ISD::SETLT:
17202     case ISD::SETLE:
17203       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17204     case ISD::SETGT:
17205     case ISD::SETGE:
17206       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17207     }
17208   // Check for x CC y ? y : x -- a min/max with reversed arms.
17209   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17210              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17211     switch (CC) {
17212     default: break;
17213     case ISD::SETULT:
17214     case ISD::SETULE:
17215       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17216     case ISD::SETUGT:
17217     case ISD::SETUGE:
17218       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17219     case ISD::SETLT:
17220     case ISD::SETLE:
17221       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17222     case ISD::SETGT:
17223     case ISD::SETGE:
17224       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17225     }
17226   }
17227
17228   return std::make_pair(Opc, NeedSplit);
17229 }
17230
17231 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17232 /// nodes.
17233 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17234                                     TargetLowering::DAGCombinerInfo &DCI,
17235                                     const X86Subtarget *Subtarget) {
17236   SDLoc DL(N);
17237   SDValue Cond = N->getOperand(0);
17238   // Get the LHS/RHS of the select.
17239   SDValue LHS = N->getOperand(1);
17240   SDValue RHS = N->getOperand(2);
17241   EVT VT = LHS.getValueType();
17242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17243
17244   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17245   // instructions match the semantics of the common C idiom x<y?x:y but not
17246   // x<=y?x:y, because of how they handle negative zero (which can be
17247   // ignored in unsafe-math mode).
17248   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17249       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17250       (Subtarget->hasSSE2() ||
17251        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17252     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17253
17254     unsigned Opcode = 0;
17255     // Check for x CC y ? x : y.
17256     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17257         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17258       switch (CC) {
17259       default: break;
17260       case ISD::SETULT:
17261         // Converting this to a min would handle NaNs incorrectly, and swapping
17262         // the operands would cause it to handle comparisons between positive
17263         // and negative zero incorrectly.
17264         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17265           if (!DAG.getTarget().Options.UnsafeFPMath &&
17266               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17267             break;
17268           std::swap(LHS, RHS);
17269         }
17270         Opcode = X86ISD::FMIN;
17271         break;
17272       case ISD::SETOLE:
17273         // Converting this to a min would handle comparisons between positive
17274         // and negative zero incorrectly.
17275         if (!DAG.getTarget().Options.UnsafeFPMath &&
17276             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17277           break;
17278         Opcode = X86ISD::FMIN;
17279         break;
17280       case ISD::SETULE:
17281         // Converting this to a min would handle both negative zeros and NaNs
17282         // incorrectly, but we can swap the operands to fix both.
17283         std::swap(LHS, RHS);
17284       case ISD::SETOLT:
17285       case ISD::SETLT:
17286       case ISD::SETLE:
17287         Opcode = X86ISD::FMIN;
17288         break;
17289
17290       case ISD::SETOGE:
17291         // Converting this to a max would handle comparisons between positive
17292         // and negative zero incorrectly.
17293         if (!DAG.getTarget().Options.UnsafeFPMath &&
17294             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17295           break;
17296         Opcode = X86ISD::FMAX;
17297         break;
17298       case ISD::SETUGT:
17299         // Converting this to a max would handle NaNs incorrectly, and swapping
17300         // the operands would cause it to handle comparisons between positive
17301         // and negative zero incorrectly.
17302         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17303           if (!DAG.getTarget().Options.UnsafeFPMath &&
17304               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17305             break;
17306           std::swap(LHS, RHS);
17307         }
17308         Opcode = X86ISD::FMAX;
17309         break;
17310       case ISD::SETUGE:
17311         // Converting this to a max would handle both negative zeros and NaNs
17312         // incorrectly, but we can swap the operands to fix both.
17313         std::swap(LHS, RHS);
17314       case ISD::SETOGT:
17315       case ISD::SETGT:
17316       case ISD::SETGE:
17317         Opcode = X86ISD::FMAX;
17318         break;
17319       }
17320     // Check for x CC y ? y : x -- a min/max with reversed arms.
17321     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17322                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17323       switch (CC) {
17324       default: break;
17325       case ISD::SETOGE:
17326         // Converting this to a min would handle comparisons between positive
17327         // and negative zero incorrectly, and swapping the operands would
17328         // cause it to handle NaNs incorrectly.
17329         if (!DAG.getTarget().Options.UnsafeFPMath &&
17330             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17331           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17332             break;
17333           std::swap(LHS, RHS);
17334         }
17335         Opcode = X86ISD::FMIN;
17336         break;
17337       case ISD::SETUGT:
17338         // Converting this to a min would handle NaNs incorrectly.
17339         if (!DAG.getTarget().Options.UnsafeFPMath &&
17340             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17341           break;
17342         Opcode = X86ISD::FMIN;
17343         break;
17344       case ISD::SETUGE:
17345         // Converting this to a min would handle both negative zeros and NaNs
17346         // incorrectly, but we can swap the operands to fix both.
17347         std::swap(LHS, RHS);
17348       case ISD::SETOGT:
17349       case ISD::SETGT:
17350       case ISD::SETGE:
17351         Opcode = X86ISD::FMIN;
17352         break;
17353
17354       case ISD::SETULT:
17355         // Converting this to a max would handle NaNs incorrectly.
17356         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17357           break;
17358         Opcode = X86ISD::FMAX;
17359         break;
17360       case ISD::SETOLE:
17361         // Converting this to a max would handle comparisons between positive
17362         // and negative zero incorrectly, and swapping the operands would
17363         // cause it to handle NaNs incorrectly.
17364         if (!DAG.getTarget().Options.UnsafeFPMath &&
17365             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17366           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17367             break;
17368           std::swap(LHS, RHS);
17369         }
17370         Opcode = X86ISD::FMAX;
17371         break;
17372       case ISD::SETULE:
17373         // Converting this to a max would handle both negative zeros and NaNs
17374         // incorrectly, but we can swap the operands to fix both.
17375         std::swap(LHS, RHS);
17376       case ISD::SETOLT:
17377       case ISD::SETLT:
17378       case ISD::SETLE:
17379         Opcode = X86ISD::FMAX;
17380         break;
17381       }
17382     }
17383
17384     if (Opcode)
17385       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17386   }
17387
17388   EVT CondVT = Cond.getValueType();
17389   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17390       CondVT.getVectorElementType() == MVT::i1) {
17391     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17392     // lowering on AVX-512. In this case we convert it to
17393     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17394     // The same situation for all 128 and 256-bit vectors of i8 and i16
17395     EVT OpVT = LHS.getValueType();
17396     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17397         (OpVT.getVectorElementType() == MVT::i8 ||
17398          OpVT.getVectorElementType() == MVT::i16)) {
17399       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17400       DCI.AddToWorklist(Cond.getNode());
17401       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17402     }
17403   }
17404   // If this is a select between two integer constants, try to do some
17405   // optimizations.
17406   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17407     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17408       // Don't do this for crazy integer types.
17409       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17410         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17411         // so that TrueC (the true value) is larger than FalseC.
17412         bool NeedsCondInvert = false;
17413
17414         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17415             // Efficiently invertible.
17416             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17417              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17418               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17419           NeedsCondInvert = true;
17420           std::swap(TrueC, FalseC);
17421         }
17422
17423         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17424         if (FalseC->getAPIntValue() == 0 &&
17425             TrueC->getAPIntValue().isPowerOf2()) {
17426           if (NeedsCondInvert) // Invert the condition if needed.
17427             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17428                                DAG.getConstant(1, Cond.getValueType()));
17429
17430           // Zero extend the condition if needed.
17431           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17432
17433           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17434           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17435                              DAG.getConstant(ShAmt, MVT::i8));
17436         }
17437
17438         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17439         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17440           if (NeedsCondInvert) // Invert the condition if needed.
17441             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17442                                DAG.getConstant(1, Cond.getValueType()));
17443
17444           // Zero extend the condition if needed.
17445           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17446                              FalseC->getValueType(0), Cond);
17447           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17448                              SDValue(FalseC, 0));
17449         }
17450
17451         // Optimize cases that will turn into an LEA instruction.  This requires
17452         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17453         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17454           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17455           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17456
17457           bool isFastMultiplier = false;
17458           if (Diff < 10) {
17459             switch ((unsigned char)Diff) {
17460               default: break;
17461               case 1:  // result = add base, cond
17462               case 2:  // result = lea base(    , cond*2)
17463               case 3:  // result = lea base(cond, cond*2)
17464               case 4:  // result = lea base(    , cond*4)
17465               case 5:  // result = lea base(cond, cond*4)
17466               case 8:  // result = lea base(    , cond*8)
17467               case 9:  // result = lea base(cond, cond*8)
17468                 isFastMultiplier = true;
17469                 break;
17470             }
17471           }
17472
17473           if (isFastMultiplier) {
17474             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17475             if (NeedsCondInvert) // Invert the condition if needed.
17476               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17477                                  DAG.getConstant(1, Cond.getValueType()));
17478
17479             // Zero extend the condition if needed.
17480             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17481                                Cond);
17482             // Scale the condition by the difference.
17483             if (Diff != 1)
17484               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17485                                  DAG.getConstant(Diff, Cond.getValueType()));
17486
17487             // Add the base if non-zero.
17488             if (FalseC->getAPIntValue() != 0)
17489               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17490                                  SDValue(FalseC, 0));
17491             return Cond;
17492           }
17493         }
17494       }
17495   }
17496
17497   // Canonicalize max and min:
17498   // (x > y) ? x : y -> (x >= y) ? x : y
17499   // (x < y) ? x : y -> (x <= y) ? x : y
17500   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17501   // the need for an extra compare
17502   // against zero. e.g.
17503   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17504   // subl   %esi, %edi
17505   // testl  %edi, %edi
17506   // movl   $0, %eax
17507   // cmovgl %edi, %eax
17508   // =>
17509   // xorl   %eax, %eax
17510   // subl   %esi, $edi
17511   // cmovsl %eax, %edi
17512   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17513       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17514       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17515     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17516     switch (CC) {
17517     default: break;
17518     case ISD::SETLT:
17519     case ISD::SETGT: {
17520       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17521       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17522                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17523       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17524     }
17525     }
17526   }
17527
17528   // Early exit check
17529   if (!TLI.isTypeLegal(VT))
17530     return SDValue();
17531
17532   // Match VSELECTs into subs with unsigned saturation.
17533   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17534       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17535       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17536        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17537     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17538
17539     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17540     // left side invert the predicate to simplify logic below.
17541     SDValue Other;
17542     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17543       Other = RHS;
17544       CC = ISD::getSetCCInverse(CC, true);
17545     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17546       Other = LHS;
17547     }
17548
17549     if (Other.getNode() && Other->getNumOperands() == 2 &&
17550         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17551       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17552       SDValue CondRHS = Cond->getOperand(1);
17553
17554       // Look for a general sub with unsigned saturation first.
17555       // x >= y ? x-y : 0 --> subus x, y
17556       // x >  y ? x-y : 0 --> subus x, y
17557       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17558           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17559         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17560
17561       // If the RHS is a constant we have to reverse the const canonicalization.
17562       // x > C-1 ? x+-C : 0 --> subus x, C
17563       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17564           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17565         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17566         if (CondRHS.getConstantOperandVal(0) == -A-1)
17567           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17568                              DAG.getConstant(-A, VT));
17569       }
17570
17571       // Another special case: If C was a sign bit, the sub has been
17572       // canonicalized into a xor.
17573       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17574       //        it's safe to decanonicalize the xor?
17575       // x s< 0 ? x^C : 0 --> subus x, C
17576       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17577           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17578           isSplatVector(OpRHS.getNode())) {
17579         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17580         if (A.isSignBit())
17581           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17582       }
17583     }
17584   }
17585
17586   // Try to match a min/max vector operation.
17587   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17588     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17589     unsigned Opc = ret.first;
17590     bool NeedSplit = ret.second;
17591
17592     if (Opc && NeedSplit) {
17593       unsigned NumElems = VT.getVectorNumElements();
17594       // Extract the LHS vectors
17595       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17596       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17597
17598       // Extract the RHS vectors
17599       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17600       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17601
17602       // Create min/max for each subvector
17603       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17604       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17605
17606       // Merge the result
17607       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17608     } else if (Opc)
17609       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17610   }
17611
17612   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17613   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17614       // Check if SETCC has already been promoted
17615       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17616       // Check that condition value type matches vselect operand type
17617       CondVT == VT) { 
17618
17619     assert(Cond.getValueType().isVector() &&
17620            "vector select expects a vector selector!");
17621
17622     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17623     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17624
17625     if (!TValIsAllOnes && !FValIsAllZeros) {
17626       // Try invert the condition if true value is not all 1s and false value
17627       // is not all 0s.
17628       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17629       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17630
17631       if (TValIsAllZeros || FValIsAllOnes) {
17632         SDValue CC = Cond.getOperand(2);
17633         ISD::CondCode NewCC =
17634           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17635                                Cond.getOperand(0).getValueType().isInteger());
17636         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17637         std::swap(LHS, RHS);
17638         TValIsAllOnes = FValIsAllOnes;
17639         FValIsAllZeros = TValIsAllZeros;
17640       }
17641     }
17642
17643     if (TValIsAllOnes || FValIsAllZeros) {
17644       SDValue Ret;
17645
17646       if (TValIsAllOnes && FValIsAllZeros)
17647         Ret = Cond;
17648       else if (TValIsAllOnes)
17649         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17650                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17651       else if (FValIsAllZeros)
17652         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17653                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17654
17655       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17656     }
17657   }
17658
17659   // Try to fold this VSELECT into a MOVSS/MOVSD
17660   if (N->getOpcode() == ISD::VSELECT &&
17661       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17662     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17663         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17664       bool CanFold = false;
17665       unsigned NumElems = Cond.getNumOperands();
17666       SDValue A = LHS;
17667       SDValue B = RHS;
17668       
17669       if (isZero(Cond.getOperand(0))) {
17670         CanFold = true;
17671
17672         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17673         // fold (vselect <0,-1> -> (movsd A, B)
17674         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17675           CanFold = isAllOnes(Cond.getOperand(i));
17676       } else if (isAllOnes(Cond.getOperand(0))) {
17677         CanFold = true;
17678         std::swap(A, B);
17679
17680         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17681         // fold (vselect <-1,0> -> (movsd B, A)
17682         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17683           CanFold = isZero(Cond.getOperand(i));
17684       }
17685
17686       if (CanFold) {
17687         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17688           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17689         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17690       }
17691
17692       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17693         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17694         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17695         //                             (v2i64 (bitcast B)))))
17696         //
17697         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17698         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17699         //                             (v2f64 (bitcast B)))))
17700         //
17701         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17702         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17703         //                             (v2i64 (bitcast A)))))
17704         //
17705         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17706         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17707         //                             (v2f64 (bitcast A)))))
17708
17709         CanFold = (isZero(Cond.getOperand(0)) &&
17710                    isZero(Cond.getOperand(1)) &&
17711                    isAllOnes(Cond.getOperand(2)) &&
17712                    isAllOnes(Cond.getOperand(3)));
17713
17714         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17715             isAllOnes(Cond.getOperand(1)) &&
17716             isZero(Cond.getOperand(2)) &&
17717             isZero(Cond.getOperand(3))) {
17718           CanFold = true;
17719           std::swap(LHS, RHS);
17720         }
17721
17722         if (CanFold) {
17723           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17724           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17725           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17726           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17727                                                 NewB, DAG);
17728           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17729         }
17730       }
17731     }
17732   }
17733
17734   // If we know that this node is legal then we know that it is going to be
17735   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17736   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17737   // to simplify previous instructions.
17738   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17739       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17740     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17741
17742     // Don't optimize vector selects that map to mask-registers.
17743     if (BitWidth == 1)
17744       return SDValue();
17745
17746     // Check all uses of that condition operand to check whether it will be
17747     // consumed by non-BLEND instructions, which may depend on all bits are set
17748     // properly.
17749     for (SDNode::use_iterator I = Cond->use_begin(),
17750                               E = Cond->use_end(); I != E; ++I)
17751       if (I->getOpcode() != ISD::VSELECT)
17752         // TODO: Add other opcodes eventually lowered into BLEND.
17753         return SDValue();
17754
17755     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17756     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17757
17758     APInt KnownZero, KnownOne;
17759     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17760                                           DCI.isBeforeLegalizeOps());
17761     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17762         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17763       DCI.CommitTargetLoweringOpt(TLO);
17764   }
17765
17766   return SDValue();
17767 }
17768
17769 // Check whether a boolean test is testing a boolean value generated by
17770 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17771 // code.
17772 //
17773 // Simplify the following patterns:
17774 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17775 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17776 // to (Op EFLAGS Cond)
17777 //
17778 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17779 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17780 // to (Op EFLAGS !Cond)
17781 //
17782 // where Op could be BRCOND or CMOV.
17783 //
17784 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17785   // Quit if not CMP and SUB with its value result used.
17786   if (Cmp.getOpcode() != X86ISD::CMP &&
17787       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17788       return SDValue();
17789
17790   // Quit if not used as a boolean value.
17791   if (CC != X86::COND_E && CC != X86::COND_NE)
17792     return SDValue();
17793
17794   // Check CMP operands. One of them should be 0 or 1 and the other should be
17795   // an SetCC or extended from it.
17796   SDValue Op1 = Cmp.getOperand(0);
17797   SDValue Op2 = Cmp.getOperand(1);
17798
17799   SDValue SetCC;
17800   const ConstantSDNode* C = 0;
17801   bool needOppositeCond = (CC == X86::COND_E);
17802   bool checkAgainstTrue = false; // Is it a comparison against 1?
17803
17804   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17805     SetCC = Op2;
17806   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17807     SetCC = Op1;
17808   else // Quit if all operands are not constants.
17809     return SDValue();
17810
17811   if (C->getZExtValue() == 1) {
17812     needOppositeCond = !needOppositeCond;
17813     checkAgainstTrue = true;
17814   } else if (C->getZExtValue() != 0)
17815     // Quit if the constant is neither 0 or 1.
17816     return SDValue();
17817
17818   bool truncatedToBoolWithAnd = false;
17819   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17820   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17821          SetCC.getOpcode() == ISD::TRUNCATE ||
17822          SetCC.getOpcode() == ISD::AND) {
17823     if (SetCC.getOpcode() == ISD::AND) {
17824       int OpIdx = -1;
17825       ConstantSDNode *CS;
17826       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17827           CS->getZExtValue() == 1)
17828         OpIdx = 1;
17829       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17830           CS->getZExtValue() == 1)
17831         OpIdx = 0;
17832       if (OpIdx == -1)
17833         break;
17834       SetCC = SetCC.getOperand(OpIdx);
17835       truncatedToBoolWithAnd = true;
17836     } else
17837       SetCC = SetCC.getOperand(0);
17838   }
17839
17840   switch (SetCC.getOpcode()) {
17841   case X86ISD::SETCC_CARRY:
17842     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17843     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17844     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17845     // truncated to i1 using 'and'.
17846     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17847       break;
17848     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17849            "Invalid use of SETCC_CARRY!");
17850     // FALL THROUGH
17851   case X86ISD::SETCC:
17852     // Set the condition code or opposite one if necessary.
17853     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17854     if (needOppositeCond)
17855       CC = X86::GetOppositeBranchCondition(CC);
17856     return SetCC.getOperand(1);
17857   case X86ISD::CMOV: {
17858     // Check whether false/true value has canonical one, i.e. 0 or 1.
17859     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17860     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17861     // Quit if true value is not a constant.
17862     if (!TVal)
17863       return SDValue();
17864     // Quit if false value is not a constant.
17865     if (!FVal) {
17866       SDValue Op = SetCC.getOperand(0);
17867       // Skip 'zext' or 'trunc' node.
17868       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17869           Op.getOpcode() == ISD::TRUNCATE)
17870         Op = Op.getOperand(0);
17871       // A special case for rdrand/rdseed, where 0 is set if false cond is
17872       // found.
17873       if ((Op.getOpcode() != X86ISD::RDRAND &&
17874            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17875         return SDValue();
17876     }
17877     // Quit if false value is not the constant 0 or 1.
17878     bool FValIsFalse = true;
17879     if (FVal && FVal->getZExtValue() != 0) {
17880       if (FVal->getZExtValue() != 1)
17881         return SDValue();
17882       // If FVal is 1, opposite cond is needed.
17883       needOppositeCond = !needOppositeCond;
17884       FValIsFalse = false;
17885     }
17886     // Quit if TVal is not the constant opposite of FVal.
17887     if (FValIsFalse && TVal->getZExtValue() != 1)
17888       return SDValue();
17889     if (!FValIsFalse && TVal->getZExtValue() != 0)
17890       return SDValue();
17891     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17892     if (needOppositeCond)
17893       CC = X86::GetOppositeBranchCondition(CC);
17894     return SetCC.getOperand(3);
17895   }
17896   }
17897
17898   return SDValue();
17899 }
17900
17901 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17902 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17903                                   TargetLowering::DAGCombinerInfo &DCI,
17904                                   const X86Subtarget *Subtarget) {
17905   SDLoc DL(N);
17906
17907   // If the flag operand isn't dead, don't touch this CMOV.
17908   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17909     return SDValue();
17910
17911   SDValue FalseOp = N->getOperand(0);
17912   SDValue TrueOp = N->getOperand(1);
17913   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17914   SDValue Cond = N->getOperand(3);
17915
17916   if (CC == X86::COND_E || CC == X86::COND_NE) {
17917     switch (Cond.getOpcode()) {
17918     default: break;
17919     case X86ISD::BSR:
17920     case X86ISD::BSF:
17921       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17922       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17923         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17924     }
17925   }
17926
17927   SDValue Flags;
17928
17929   Flags = checkBoolTestSetCCCombine(Cond, CC);
17930   if (Flags.getNode() &&
17931       // Extra check as FCMOV only supports a subset of X86 cond.
17932       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17933     SDValue Ops[] = { FalseOp, TrueOp,
17934                       DAG.getConstant(CC, MVT::i8), Flags };
17935     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17936                        Ops, array_lengthof(Ops));
17937   }
17938
17939   // If this is a select between two integer constants, try to do some
17940   // optimizations.  Note that the operands are ordered the opposite of SELECT
17941   // operands.
17942   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17943     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17944       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17945       // larger than FalseC (the false value).
17946       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17947         CC = X86::GetOppositeBranchCondition(CC);
17948         std::swap(TrueC, FalseC);
17949         std::swap(TrueOp, FalseOp);
17950       }
17951
17952       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17953       // This is efficient for any integer data type (including i8/i16) and
17954       // shift amount.
17955       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17956         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17957                            DAG.getConstant(CC, MVT::i8), Cond);
17958
17959         // Zero extend the condition if needed.
17960         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17961
17962         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17963         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17964                            DAG.getConstant(ShAmt, MVT::i8));
17965         if (N->getNumValues() == 2)  // Dead flag value?
17966           return DCI.CombineTo(N, Cond, SDValue());
17967         return Cond;
17968       }
17969
17970       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17971       // for any integer data type, including i8/i16.
17972       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17973         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17974                            DAG.getConstant(CC, MVT::i8), Cond);
17975
17976         // Zero extend the condition if needed.
17977         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17978                            FalseC->getValueType(0), Cond);
17979         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17980                            SDValue(FalseC, 0));
17981
17982         if (N->getNumValues() == 2)  // Dead flag value?
17983           return DCI.CombineTo(N, Cond, SDValue());
17984         return Cond;
17985       }
17986
17987       // Optimize cases that will turn into an LEA instruction.  This requires
17988       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17989       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17990         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17991         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17992
17993         bool isFastMultiplier = false;
17994         if (Diff < 10) {
17995           switch ((unsigned char)Diff) {
17996           default: break;
17997           case 1:  // result = add base, cond
17998           case 2:  // result = lea base(    , cond*2)
17999           case 3:  // result = lea base(cond, cond*2)
18000           case 4:  // result = lea base(    , cond*4)
18001           case 5:  // result = lea base(cond, cond*4)
18002           case 8:  // result = lea base(    , cond*8)
18003           case 9:  // result = lea base(cond, cond*8)
18004             isFastMultiplier = true;
18005             break;
18006           }
18007         }
18008
18009         if (isFastMultiplier) {
18010           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18011           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18012                              DAG.getConstant(CC, MVT::i8), Cond);
18013           // Zero extend the condition if needed.
18014           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18015                              Cond);
18016           // Scale the condition by the difference.
18017           if (Diff != 1)
18018             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18019                                DAG.getConstant(Diff, Cond.getValueType()));
18020
18021           // Add the base if non-zero.
18022           if (FalseC->getAPIntValue() != 0)
18023             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18024                                SDValue(FalseC, 0));
18025           if (N->getNumValues() == 2)  // Dead flag value?
18026             return DCI.CombineTo(N, Cond, SDValue());
18027           return Cond;
18028         }
18029       }
18030     }
18031   }
18032
18033   // Handle these cases:
18034   //   (select (x != c), e, c) -> select (x != c), e, x),
18035   //   (select (x == c), c, e) -> select (x == c), x, e)
18036   // where the c is an integer constant, and the "select" is the combination
18037   // of CMOV and CMP.
18038   //
18039   // The rationale for this change is that the conditional-move from a constant
18040   // needs two instructions, however, conditional-move from a register needs
18041   // only one instruction.
18042   //
18043   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18044   //  some instruction-combining opportunities. This opt needs to be
18045   //  postponed as late as possible.
18046   //
18047   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18048     // the DCI.xxxx conditions are provided to postpone the optimization as
18049     // late as possible.
18050
18051     ConstantSDNode *CmpAgainst = 0;
18052     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18053         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18054         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18055
18056       if (CC == X86::COND_NE &&
18057           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18058         CC = X86::GetOppositeBranchCondition(CC);
18059         std::swap(TrueOp, FalseOp);
18060       }
18061
18062       if (CC == X86::COND_E &&
18063           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18064         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18065                           DAG.getConstant(CC, MVT::i8), Cond };
18066         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18067                            array_lengthof(Ops));
18068       }
18069     }
18070   }
18071
18072   return SDValue();
18073 }
18074
18075 /// PerformMulCombine - Optimize a single multiply with constant into two
18076 /// in order to implement it with two cheaper instructions, e.g.
18077 /// LEA + SHL, LEA + LEA.
18078 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18079                                  TargetLowering::DAGCombinerInfo &DCI) {
18080   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18081     return SDValue();
18082
18083   EVT VT = N->getValueType(0);
18084   if (VT != MVT::i64)
18085     return SDValue();
18086
18087   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18088   if (!C)
18089     return SDValue();
18090   uint64_t MulAmt = C->getZExtValue();
18091   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18092     return SDValue();
18093
18094   uint64_t MulAmt1 = 0;
18095   uint64_t MulAmt2 = 0;
18096   if ((MulAmt % 9) == 0) {
18097     MulAmt1 = 9;
18098     MulAmt2 = MulAmt / 9;
18099   } else if ((MulAmt % 5) == 0) {
18100     MulAmt1 = 5;
18101     MulAmt2 = MulAmt / 5;
18102   } else if ((MulAmt % 3) == 0) {
18103     MulAmt1 = 3;
18104     MulAmt2 = MulAmt / 3;
18105   }
18106   if (MulAmt2 &&
18107       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18108     SDLoc DL(N);
18109
18110     if (isPowerOf2_64(MulAmt2) &&
18111         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18112       // If second multiplifer is pow2, issue it first. We want the multiply by
18113       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18114       // is an add.
18115       std::swap(MulAmt1, MulAmt2);
18116
18117     SDValue NewMul;
18118     if (isPowerOf2_64(MulAmt1))
18119       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18120                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18121     else
18122       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18123                            DAG.getConstant(MulAmt1, VT));
18124
18125     if (isPowerOf2_64(MulAmt2))
18126       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18127                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18128     else
18129       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18130                            DAG.getConstant(MulAmt2, VT));
18131
18132     // Do not add new nodes to DAG combiner worklist.
18133     DCI.CombineTo(N, NewMul, false);
18134   }
18135   return SDValue();
18136 }
18137
18138 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18139   SDValue N0 = N->getOperand(0);
18140   SDValue N1 = N->getOperand(1);
18141   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18142   EVT VT = N0.getValueType();
18143
18144   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18145   // since the result of setcc_c is all zero's or all ones.
18146   if (VT.isInteger() && !VT.isVector() &&
18147       N1C && N0.getOpcode() == ISD::AND &&
18148       N0.getOperand(1).getOpcode() == ISD::Constant) {
18149     SDValue N00 = N0.getOperand(0);
18150     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18151         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18152           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18153          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18154       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18155       APInt ShAmt = N1C->getAPIntValue();
18156       Mask = Mask.shl(ShAmt);
18157       if (Mask != 0)
18158         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18159                            N00, DAG.getConstant(Mask, VT));
18160     }
18161   }
18162
18163   // Hardware support for vector shifts is sparse which makes us scalarize the
18164   // vector operations in many cases. Also, on sandybridge ADD is faster than
18165   // shl.
18166   // (shl V, 1) -> add V,V
18167   if (isSplatVector(N1.getNode())) {
18168     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18169     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18170     // We shift all of the values by one. In many cases we do not have
18171     // hardware support for this operation. This is better expressed as an ADD
18172     // of two values.
18173     if (N1C && (1 == N1C->getZExtValue())) {
18174       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18175     }
18176   }
18177
18178   return SDValue();
18179 }
18180
18181 /// \brief Returns a vector of 0s if the node in input is a vector logical
18182 /// shift by a constant amount which is known to be bigger than or equal
18183 /// to the vector element size in bits.
18184 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18185                                       const X86Subtarget *Subtarget) {
18186   EVT VT = N->getValueType(0);
18187
18188   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18189       (!Subtarget->hasInt256() ||
18190        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18191     return SDValue();
18192
18193   SDValue Amt = N->getOperand(1);
18194   SDLoc DL(N);
18195   if (isSplatVector(Amt.getNode())) {
18196     SDValue SclrAmt = Amt->getOperand(0);
18197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18198       APInt ShiftAmt = C->getAPIntValue();
18199       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18200
18201       // SSE2/AVX2 logical shifts always return a vector of 0s
18202       // if the shift amount is bigger than or equal to
18203       // the element size. The constant shift amount will be
18204       // encoded as a 8-bit immediate.
18205       if (ShiftAmt.trunc(8).uge(MaxAmount))
18206         return getZeroVector(VT, Subtarget, DAG, DL);
18207     }
18208   }
18209
18210   return SDValue();
18211 }
18212
18213 /// PerformShiftCombine - Combine shifts.
18214 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18215                                    TargetLowering::DAGCombinerInfo &DCI,
18216                                    const X86Subtarget *Subtarget) {
18217   if (N->getOpcode() == ISD::SHL) {
18218     SDValue V = PerformSHLCombine(N, DAG);
18219     if (V.getNode()) return V;
18220   }
18221
18222   if (N->getOpcode() != ISD::SRA) {
18223     // Try to fold this logical shift into a zero vector.
18224     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18225     if (V.getNode()) return V;
18226   }
18227
18228   return SDValue();
18229 }
18230
18231 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18232 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18233 // and friends.  Likewise for OR -> CMPNEQSS.
18234 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18235                             TargetLowering::DAGCombinerInfo &DCI,
18236                             const X86Subtarget *Subtarget) {
18237   unsigned opcode;
18238
18239   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18240   // we're requiring SSE2 for both.
18241   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18242     SDValue N0 = N->getOperand(0);
18243     SDValue N1 = N->getOperand(1);
18244     SDValue CMP0 = N0->getOperand(1);
18245     SDValue CMP1 = N1->getOperand(1);
18246     SDLoc DL(N);
18247
18248     // The SETCCs should both refer to the same CMP.
18249     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18250       return SDValue();
18251
18252     SDValue CMP00 = CMP0->getOperand(0);
18253     SDValue CMP01 = CMP0->getOperand(1);
18254     EVT     VT    = CMP00.getValueType();
18255
18256     if (VT == MVT::f32 || VT == MVT::f64) {
18257       bool ExpectingFlags = false;
18258       // Check for any users that want flags:
18259       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18260            !ExpectingFlags && UI != UE; ++UI)
18261         switch (UI->getOpcode()) {
18262         default:
18263         case ISD::BR_CC:
18264         case ISD::BRCOND:
18265         case ISD::SELECT:
18266           ExpectingFlags = true;
18267           break;
18268         case ISD::CopyToReg:
18269         case ISD::SIGN_EXTEND:
18270         case ISD::ZERO_EXTEND:
18271         case ISD::ANY_EXTEND:
18272           break;
18273         }
18274
18275       if (!ExpectingFlags) {
18276         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18277         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18278
18279         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18280           X86::CondCode tmp = cc0;
18281           cc0 = cc1;
18282           cc1 = tmp;
18283         }
18284
18285         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18286             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18287           // FIXME: need symbolic constants for these magic numbers.
18288           // See X86ATTInstPrinter.cpp:printSSECC().
18289           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18290           if (Subtarget->hasAVX512()) {
18291             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18292                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18293             if (N->getValueType(0) != MVT::i1)
18294               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18295                                  FSetCC);
18296             return FSetCC;
18297           }
18298           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18299                                               CMP00.getValueType(), CMP00, CMP01,
18300                                               DAG.getConstant(x86cc, MVT::i8));
18301
18302           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18303           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18304
18305           if (is64BitFP && !Subtarget->is64Bit()) {
18306             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18307             // 64-bit integer, since that's not a legal type. Since
18308             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18309             // bits, but can do this little dance to extract the lowest 32 bits
18310             // and work with those going forward.
18311             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18312                                            OnesOrZeroesF);
18313             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18314                                            Vector64);
18315             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18316                                         Vector32, DAG.getIntPtrConstant(0));
18317             IntVT = MVT::i32;
18318           }
18319
18320           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18321           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18322                                       DAG.getConstant(1, IntVT));
18323           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18324           return OneBitOfTruth;
18325         }
18326       }
18327     }
18328   }
18329   return SDValue();
18330 }
18331
18332 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18333 /// so it can be folded inside ANDNP.
18334 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18335   EVT VT = N->getValueType(0);
18336
18337   // Match direct AllOnes for 128 and 256-bit vectors
18338   if (ISD::isBuildVectorAllOnes(N))
18339     return true;
18340
18341   // Look through a bit convert.
18342   if (N->getOpcode() == ISD::BITCAST)
18343     N = N->getOperand(0).getNode();
18344
18345   // Sometimes the operand may come from a insert_subvector building a 256-bit
18346   // allones vector
18347   if (VT.is256BitVector() &&
18348       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18349     SDValue V1 = N->getOperand(0);
18350     SDValue V2 = N->getOperand(1);
18351
18352     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18353         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18354         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18355         ISD::isBuildVectorAllOnes(V2.getNode()))
18356       return true;
18357   }
18358
18359   return false;
18360 }
18361
18362 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18363 // register. In most cases we actually compare or select YMM-sized registers
18364 // and mixing the two types creates horrible code. This method optimizes
18365 // some of the transition sequences.
18366 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18367                                  TargetLowering::DAGCombinerInfo &DCI,
18368                                  const X86Subtarget *Subtarget) {
18369   EVT VT = N->getValueType(0);
18370   if (!VT.is256BitVector())
18371     return SDValue();
18372
18373   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18374           N->getOpcode() == ISD::ZERO_EXTEND ||
18375           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18376
18377   SDValue Narrow = N->getOperand(0);
18378   EVT NarrowVT = Narrow->getValueType(0);
18379   if (!NarrowVT.is128BitVector())
18380     return SDValue();
18381
18382   if (Narrow->getOpcode() != ISD::XOR &&
18383       Narrow->getOpcode() != ISD::AND &&
18384       Narrow->getOpcode() != ISD::OR)
18385     return SDValue();
18386
18387   SDValue N0  = Narrow->getOperand(0);
18388   SDValue N1  = Narrow->getOperand(1);
18389   SDLoc DL(Narrow);
18390
18391   // The Left side has to be a trunc.
18392   if (N0.getOpcode() != ISD::TRUNCATE)
18393     return SDValue();
18394
18395   // The type of the truncated inputs.
18396   EVT WideVT = N0->getOperand(0)->getValueType(0);
18397   if (WideVT != VT)
18398     return SDValue();
18399
18400   // The right side has to be a 'trunc' or a constant vector.
18401   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18402   bool RHSConst = (isSplatVector(N1.getNode()) &&
18403                    isa<ConstantSDNode>(N1->getOperand(0)));
18404   if (!RHSTrunc && !RHSConst)
18405     return SDValue();
18406
18407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18408
18409   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18410     return SDValue();
18411
18412   // Set N0 and N1 to hold the inputs to the new wide operation.
18413   N0 = N0->getOperand(0);
18414   if (RHSConst) {
18415     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18416                      N1->getOperand(0));
18417     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18418     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18419   } else if (RHSTrunc) {
18420     N1 = N1->getOperand(0);
18421   }
18422
18423   // Generate the wide operation.
18424   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18425   unsigned Opcode = N->getOpcode();
18426   switch (Opcode) {
18427   case ISD::ANY_EXTEND:
18428     return Op;
18429   case ISD::ZERO_EXTEND: {
18430     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18431     APInt Mask = APInt::getAllOnesValue(InBits);
18432     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18433     return DAG.getNode(ISD::AND, DL, VT,
18434                        Op, DAG.getConstant(Mask, VT));
18435   }
18436   case ISD::SIGN_EXTEND:
18437     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18438                        Op, DAG.getValueType(NarrowVT));
18439   default:
18440     llvm_unreachable("Unexpected opcode");
18441   }
18442 }
18443
18444 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18445                                  TargetLowering::DAGCombinerInfo &DCI,
18446                                  const X86Subtarget *Subtarget) {
18447   EVT VT = N->getValueType(0);
18448   if (DCI.isBeforeLegalizeOps())
18449     return SDValue();
18450
18451   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18452   if (R.getNode())
18453     return R;
18454
18455   // Create BEXTR instructions
18456   // BEXTR is ((X >> imm) & (2**size-1))
18457   if (VT == MVT::i32 || VT == MVT::i64) {
18458     SDValue N0 = N->getOperand(0);
18459     SDValue N1 = N->getOperand(1);
18460     SDLoc DL(N);
18461
18462     // Check for BEXTR.
18463     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18464         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18465       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18466       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18467       if (MaskNode && ShiftNode) {
18468         uint64_t Mask = MaskNode->getZExtValue();
18469         uint64_t Shift = ShiftNode->getZExtValue();
18470         if (isMask_64(Mask)) {
18471           uint64_t MaskSize = CountPopulation_64(Mask);
18472           if (Shift + MaskSize <= VT.getSizeInBits())
18473             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18474                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18475         }
18476       }
18477     } // BEXTR
18478
18479     return SDValue();
18480   }
18481
18482   // Want to form ANDNP nodes:
18483   // 1) In the hopes of then easily combining them with OR and AND nodes
18484   //    to form PBLEND/PSIGN.
18485   // 2) To match ANDN packed intrinsics
18486   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18487     return SDValue();
18488
18489   SDValue N0 = N->getOperand(0);
18490   SDValue N1 = N->getOperand(1);
18491   SDLoc DL(N);
18492
18493   // Check LHS for vnot
18494   if (N0.getOpcode() == ISD::XOR &&
18495       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18496       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18497     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18498
18499   // Check RHS for vnot
18500   if (N1.getOpcode() == ISD::XOR &&
18501       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18502       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18503     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18504
18505   return SDValue();
18506 }
18507
18508 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18509                                 TargetLowering::DAGCombinerInfo &DCI,
18510                                 const X86Subtarget *Subtarget) {
18511   if (DCI.isBeforeLegalizeOps())
18512     return SDValue();
18513
18514   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18515   if (R.getNode())
18516     return R;
18517
18518   SDValue N0 = N->getOperand(0);
18519   SDValue N1 = N->getOperand(1);
18520   EVT VT = N->getValueType(0);
18521
18522   // look for psign/blend
18523   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18524     if (!Subtarget->hasSSSE3() ||
18525         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18526       return SDValue();
18527
18528     // Canonicalize pandn to RHS
18529     if (N0.getOpcode() == X86ISD::ANDNP)
18530       std::swap(N0, N1);
18531     // or (and (m, y), (pandn m, x))
18532     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18533       SDValue Mask = N1.getOperand(0);
18534       SDValue X    = N1.getOperand(1);
18535       SDValue Y;
18536       if (N0.getOperand(0) == Mask)
18537         Y = N0.getOperand(1);
18538       if (N0.getOperand(1) == Mask)
18539         Y = N0.getOperand(0);
18540
18541       // Check to see if the mask appeared in both the AND and ANDNP and
18542       if (!Y.getNode())
18543         return SDValue();
18544
18545       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18546       // Look through mask bitcast.
18547       if (Mask.getOpcode() == ISD::BITCAST)
18548         Mask = Mask.getOperand(0);
18549       if (X.getOpcode() == ISD::BITCAST)
18550         X = X.getOperand(0);
18551       if (Y.getOpcode() == ISD::BITCAST)
18552         Y = Y.getOperand(0);
18553
18554       EVT MaskVT = Mask.getValueType();
18555
18556       // Validate that the Mask operand is a vector sra node.
18557       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18558       // there is no psrai.b
18559       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18560       unsigned SraAmt = ~0;
18561       if (Mask.getOpcode() == ISD::SRA) {
18562         SDValue Amt = Mask.getOperand(1);
18563         if (isSplatVector(Amt.getNode())) {
18564           SDValue SclrAmt = Amt->getOperand(0);
18565           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18566             SraAmt = C->getZExtValue();
18567         }
18568       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18569         SDValue SraC = Mask.getOperand(1);
18570         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18571       }
18572       if ((SraAmt + 1) != EltBits)
18573         return SDValue();
18574
18575       SDLoc DL(N);
18576
18577       // Now we know we at least have a plendvb with the mask val.  See if
18578       // we can form a psignb/w/d.
18579       // psign = x.type == y.type == mask.type && y = sub(0, x);
18580       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18581           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18582           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18583         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18584                "Unsupported VT for PSIGN");
18585         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18586         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18587       }
18588       // PBLENDVB only available on SSE 4.1
18589       if (!Subtarget->hasSSE41())
18590         return SDValue();
18591
18592       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18593
18594       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18595       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18596       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18597       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18598       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18599     }
18600   }
18601
18602   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18603     return SDValue();
18604
18605   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18606   MachineFunction &MF = DAG.getMachineFunction();
18607   bool OptForSize = MF.getFunction()->getAttributes().
18608     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18609
18610   // SHLD/SHRD instructions have lower register pressure, but on some
18611   // platforms they have higher latency than the equivalent
18612   // series of shifts/or that would otherwise be generated.
18613   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18614   // have higher latencies and we are not optimizing for size.
18615   if (!OptForSize && Subtarget->isSHLDSlow())
18616     return SDValue();
18617
18618   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18619     std::swap(N0, N1);
18620   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18621     return SDValue();
18622   if (!N0.hasOneUse() || !N1.hasOneUse())
18623     return SDValue();
18624
18625   SDValue ShAmt0 = N0.getOperand(1);
18626   if (ShAmt0.getValueType() != MVT::i8)
18627     return SDValue();
18628   SDValue ShAmt1 = N1.getOperand(1);
18629   if (ShAmt1.getValueType() != MVT::i8)
18630     return SDValue();
18631   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18632     ShAmt0 = ShAmt0.getOperand(0);
18633   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18634     ShAmt1 = ShAmt1.getOperand(0);
18635
18636   SDLoc DL(N);
18637   unsigned Opc = X86ISD::SHLD;
18638   SDValue Op0 = N0.getOperand(0);
18639   SDValue Op1 = N1.getOperand(0);
18640   if (ShAmt0.getOpcode() == ISD::SUB) {
18641     Opc = X86ISD::SHRD;
18642     std::swap(Op0, Op1);
18643     std::swap(ShAmt0, ShAmt1);
18644   }
18645
18646   unsigned Bits = VT.getSizeInBits();
18647   if (ShAmt1.getOpcode() == ISD::SUB) {
18648     SDValue Sum = ShAmt1.getOperand(0);
18649     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18650       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18651       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18652         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18653       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18654         return DAG.getNode(Opc, DL, VT,
18655                            Op0, Op1,
18656                            DAG.getNode(ISD::TRUNCATE, DL,
18657                                        MVT::i8, ShAmt0));
18658     }
18659   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18660     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18661     if (ShAmt0C &&
18662         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18663       return DAG.getNode(Opc, DL, VT,
18664                          N0.getOperand(0), N1.getOperand(0),
18665                          DAG.getNode(ISD::TRUNCATE, DL,
18666                                        MVT::i8, ShAmt0));
18667   }
18668
18669   return SDValue();
18670 }
18671
18672 // Generate NEG and CMOV for integer abs.
18673 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18674   EVT VT = N->getValueType(0);
18675
18676   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18677   // 8-bit integer abs to NEG and CMOV.
18678   if (VT.isInteger() && VT.getSizeInBits() == 8)
18679     return SDValue();
18680
18681   SDValue N0 = N->getOperand(0);
18682   SDValue N1 = N->getOperand(1);
18683   SDLoc DL(N);
18684
18685   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18686   // and change it to SUB and CMOV.
18687   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18688       N0.getOpcode() == ISD::ADD &&
18689       N0.getOperand(1) == N1 &&
18690       N1.getOpcode() == ISD::SRA &&
18691       N1.getOperand(0) == N0.getOperand(0))
18692     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18693       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18694         // Generate SUB & CMOV.
18695         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18696                                   DAG.getConstant(0, VT), N0.getOperand(0));
18697
18698         SDValue Ops[] = { N0.getOperand(0), Neg,
18699                           DAG.getConstant(X86::COND_GE, MVT::i8),
18700                           SDValue(Neg.getNode(), 1) };
18701         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18702                            Ops, array_lengthof(Ops));
18703       }
18704   return SDValue();
18705 }
18706
18707 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18708 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18709                                  TargetLowering::DAGCombinerInfo &DCI,
18710                                  const X86Subtarget *Subtarget) {
18711   if (DCI.isBeforeLegalizeOps())
18712     return SDValue();
18713
18714   if (Subtarget->hasCMov()) {
18715     SDValue RV = performIntegerAbsCombine(N, DAG);
18716     if (RV.getNode())
18717       return RV;
18718   }
18719
18720   return SDValue();
18721 }
18722
18723 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18724 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18725                                   TargetLowering::DAGCombinerInfo &DCI,
18726                                   const X86Subtarget *Subtarget) {
18727   LoadSDNode *Ld = cast<LoadSDNode>(N);
18728   EVT RegVT = Ld->getValueType(0);
18729   EVT MemVT = Ld->getMemoryVT();
18730   SDLoc dl(Ld);
18731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18732   unsigned RegSz = RegVT.getSizeInBits();
18733
18734   // On Sandybridge unaligned 256bit loads are inefficient.
18735   ISD::LoadExtType Ext = Ld->getExtensionType();
18736   unsigned Alignment = Ld->getAlignment();
18737   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18738   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18739       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18740     unsigned NumElems = RegVT.getVectorNumElements();
18741     if (NumElems < 2)
18742       return SDValue();
18743
18744     SDValue Ptr = Ld->getBasePtr();
18745     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18746
18747     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18748                                   NumElems/2);
18749     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18750                                 Ld->getPointerInfo(), Ld->isVolatile(),
18751                                 Ld->isNonTemporal(), Ld->isInvariant(),
18752                                 Alignment);
18753     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18754     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18755                                 Ld->getPointerInfo(), Ld->isVolatile(),
18756                                 Ld->isNonTemporal(), Ld->isInvariant(),
18757                                 std::min(16U, Alignment));
18758     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18759                              Load1.getValue(1),
18760                              Load2.getValue(1));
18761
18762     SDValue NewVec = DAG.getUNDEF(RegVT);
18763     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18764     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18765     return DCI.CombineTo(N, NewVec, TF, true);
18766   }
18767
18768   // If this is a vector EXT Load then attempt to optimize it using a
18769   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18770   // expansion is still better than scalar code.
18771   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18772   // emit a shuffle and a arithmetic shift.
18773   // TODO: It is possible to support ZExt by zeroing the undef values
18774   // during the shuffle phase or after the shuffle.
18775   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18776       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18777     assert(MemVT != RegVT && "Cannot extend to the same type");
18778     assert(MemVT.isVector() && "Must load a vector from memory");
18779
18780     unsigned NumElems = RegVT.getVectorNumElements();
18781     unsigned MemSz = MemVT.getSizeInBits();
18782     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18783
18784     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18785       return SDValue();
18786
18787     // All sizes must be a power of two.
18788     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18789       return SDValue();
18790
18791     // Attempt to load the original value using scalar loads.
18792     // Find the largest scalar type that divides the total loaded size.
18793     MVT SclrLoadTy = MVT::i8;
18794     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18795          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18796       MVT Tp = (MVT::SimpleValueType)tp;
18797       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18798         SclrLoadTy = Tp;
18799       }
18800     }
18801
18802     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18803     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18804         (64 <= MemSz))
18805       SclrLoadTy = MVT::f64;
18806
18807     // Calculate the number of scalar loads that we need to perform
18808     // in order to load our vector from memory.
18809     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18810     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18811       return SDValue();
18812
18813     unsigned loadRegZize = RegSz;
18814     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18815       loadRegZize /= 2;
18816
18817     // Represent our vector as a sequence of elements which are the
18818     // largest scalar that we can load.
18819     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18820       loadRegZize/SclrLoadTy.getSizeInBits());
18821
18822     // Represent the data using the same element type that is stored in
18823     // memory. In practice, we ''widen'' MemVT.
18824     EVT WideVecVT =
18825           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18826                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18827
18828     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18829       "Invalid vector type");
18830
18831     // We can't shuffle using an illegal type.
18832     if (!TLI.isTypeLegal(WideVecVT))
18833       return SDValue();
18834
18835     SmallVector<SDValue, 8> Chains;
18836     SDValue Ptr = Ld->getBasePtr();
18837     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18838                                         TLI.getPointerTy());
18839     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18840
18841     for (unsigned i = 0; i < NumLoads; ++i) {
18842       // Perform a single load.
18843       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18844                                        Ptr, Ld->getPointerInfo(),
18845                                        Ld->isVolatile(), Ld->isNonTemporal(),
18846                                        Ld->isInvariant(), Ld->getAlignment());
18847       Chains.push_back(ScalarLoad.getValue(1));
18848       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18849       // another round of DAGCombining.
18850       if (i == 0)
18851         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18852       else
18853         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18854                           ScalarLoad, DAG.getIntPtrConstant(i));
18855
18856       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18857     }
18858
18859     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18860                                Chains.size());
18861
18862     // Bitcast the loaded value to a vector of the original element type, in
18863     // the size of the target vector type.
18864     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18865     unsigned SizeRatio = RegSz/MemSz;
18866
18867     if (Ext == ISD::SEXTLOAD) {
18868       // If we have SSE4.1 we can directly emit a VSEXT node.
18869       if (Subtarget->hasSSE41()) {
18870         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18871         return DCI.CombineTo(N, Sext, TF, true);
18872       }
18873
18874       // Otherwise we'll shuffle the small elements in the high bits of the
18875       // larger type and perform an arithmetic shift. If the shift is not legal
18876       // it's better to scalarize.
18877       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18878         return SDValue();
18879
18880       // Redistribute the loaded elements into the different locations.
18881       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18882       for (unsigned i = 0; i != NumElems; ++i)
18883         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18884
18885       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18886                                            DAG.getUNDEF(WideVecVT),
18887                                            &ShuffleVec[0]);
18888
18889       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18890
18891       // Build the arithmetic shift.
18892       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18893                      MemVT.getVectorElementType().getSizeInBits();
18894       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18895                           DAG.getConstant(Amt, RegVT));
18896
18897       return DCI.CombineTo(N, Shuff, TF, true);
18898     }
18899
18900     // Redistribute the loaded elements into the different locations.
18901     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18902     for (unsigned i = 0; i != NumElems; ++i)
18903       ShuffleVec[i*SizeRatio] = i;
18904
18905     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18906                                          DAG.getUNDEF(WideVecVT),
18907                                          &ShuffleVec[0]);
18908
18909     // Bitcast to the requested type.
18910     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18911     // Replace the original load with the new sequence
18912     // and return the new chain.
18913     return DCI.CombineTo(N, Shuff, TF, true);
18914   }
18915
18916   return SDValue();
18917 }
18918
18919 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18920 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18921                                    const X86Subtarget *Subtarget) {
18922   StoreSDNode *St = cast<StoreSDNode>(N);
18923   EVT VT = St->getValue().getValueType();
18924   EVT StVT = St->getMemoryVT();
18925   SDLoc dl(St);
18926   SDValue StoredVal = St->getOperand(1);
18927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18928
18929   // If we are saving a concatenation of two XMM registers, perform two stores.
18930   // On Sandy Bridge, 256-bit memory operations are executed by two
18931   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18932   // memory  operation.
18933   unsigned Alignment = St->getAlignment();
18934   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18935   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18936       StVT == VT && !IsAligned) {
18937     unsigned NumElems = VT.getVectorNumElements();
18938     if (NumElems < 2)
18939       return SDValue();
18940
18941     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18942     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18943
18944     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18945     SDValue Ptr0 = St->getBasePtr();
18946     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18947
18948     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18949                                 St->getPointerInfo(), St->isVolatile(),
18950                                 St->isNonTemporal(), Alignment);
18951     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18952                                 St->getPointerInfo(), St->isVolatile(),
18953                                 St->isNonTemporal(),
18954                                 std::min(16U, Alignment));
18955     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18956   }
18957
18958   // Optimize trunc store (of multiple scalars) to shuffle and store.
18959   // First, pack all of the elements in one place. Next, store to memory
18960   // in fewer chunks.
18961   if (St->isTruncatingStore() && VT.isVector()) {
18962     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18963     unsigned NumElems = VT.getVectorNumElements();
18964     assert(StVT != VT && "Cannot truncate to the same type");
18965     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18966     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18967
18968     // From, To sizes and ElemCount must be pow of two
18969     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18970     // We are going to use the original vector elt for storing.
18971     // Accumulated smaller vector elements must be a multiple of the store size.
18972     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18973
18974     unsigned SizeRatio  = FromSz / ToSz;
18975
18976     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18977
18978     // Create a type on which we perform the shuffle
18979     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18980             StVT.getScalarType(), NumElems*SizeRatio);
18981
18982     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18983
18984     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18985     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18986     for (unsigned i = 0; i != NumElems; ++i)
18987       ShuffleVec[i] = i * SizeRatio;
18988
18989     // Can't shuffle using an illegal type.
18990     if (!TLI.isTypeLegal(WideVecVT))
18991       return SDValue();
18992
18993     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18994                                          DAG.getUNDEF(WideVecVT),
18995                                          &ShuffleVec[0]);
18996     // At this point all of the data is stored at the bottom of the
18997     // register. We now need to save it to mem.
18998
18999     // Find the largest store unit
19000     MVT StoreType = MVT::i8;
19001     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19002          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19003       MVT Tp = (MVT::SimpleValueType)tp;
19004       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19005         StoreType = Tp;
19006     }
19007
19008     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19009     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19010         (64 <= NumElems * ToSz))
19011       StoreType = MVT::f64;
19012
19013     // Bitcast the original vector into a vector of store-size units
19014     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19015             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19016     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19017     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19018     SmallVector<SDValue, 8> Chains;
19019     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19020                                         TLI.getPointerTy());
19021     SDValue Ptr = St->getBasePtr();
19022
19023     // Perform one or more big stores into memory.
19024     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19025       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19026                                    StoreType, ShuffWide,
19027                                    DAG.getIntPtrConstant(i));
19028       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19029                                 St->getPointerInfo(), St->isVolatile(),
19030                                 St->isNonTemporal(), St->getAlignment());
19031       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19032       Chains.push_back(Ch);
19033     }
19034
19035     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19036                                Chains.size());
19037   }
19038
19039   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19040   // the FP state in cases where an emms may be missing.
19041   // A preferable solution to the general problem is to figure out the right
19042   // places to insert EMMS.  This qualifies as a quick hack.
19043
19044   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19045   if (VT.getSizeInBits() != 64)
19046     return SDValue();
19047
19048   const Function *F = DAG.getMachineFunction().getFunction();
19049   bool NoImplicitFloatOps = F->getAttributes().
19050     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19051   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19052                      && Subtarget->hasSSE2();
19053   if ((VT.isVector() ||
19054        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19055       isa<LoadSDNode>(St->getValue()) &&
19056       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19057       St->getChain().hasOneUse() && !St->isVolatile()) {
19058     SDNode* LdVal = St->getValue().getNode();
19059     LoadSDNode *Ld = 0;
19060     int TokenFactorIndex = -1;
19061     SmallVector<SDValue, 8> Ops;
19062     SDNode* ChainVal = St->getChain().getNode();
19063     // Must be a store of a load.  We currently handle two cases:  the load
19064     // is a direct child, and it's under an intervening TokenFactor.  It is
19065     // possible to dig deeper under nested TokenFactors.
19066     if (ChainVal == LdVal)
19067       Ld = cast<LoadSDNode>(St->getChain());
19068     else if (St->getValue().hasOneUse() &&
19069              ChainVal->getOpcode() == ISD::TokenFactor) {
19070       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19071         if (ChainVal->getOperand(i).getNode() == LdVal) {
19072           TokenFactorIndex = i;
19073           Ld = cast<LoadSDNode>(St->getValue());
19074         } else
19075           Ops.push_back(ChainVal->getOperand(i));
19076       }
19077     }
19078
19079     if (!Ld || !ISD::isNormalLoad(Ld))
19080       return SDValue();
19081
19082     // If this is not the MMX case, i.e. we are just turning i64 load/store
19083     // into f64 load/store, avoid the transformation if there are multiple
19084     // uses of the loaded value.
19085     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19086       return SDValue();
19087
19088     SDLoc LdDL(Ld);
19089     SDLoc StDL(N);
19090     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19091     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19092     // pair instead.
19093     if (Subtarget->is64Bit() || F64IsLegal) {
19094       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19095       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19096                                   Ld->getPointerInfo(), Ld->isVolatile(),
19097                                   Ld->isNonTemporal(), Ld->isInvariant(),
19098                                   Ld->getAlignment());
19099       SDValue NewChain = NewLd.getValue(1);
19100       if (TokenFactorIndex != -1) {
19101         Ops.push_back(NewChain);
19102         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19103                                Ops.size());
19104       }
19105       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19106                           St->getPointerInfo(),
19107                           St->isVolatile(), St->isNonTemporal(),
19108                           St->getAlignment());
19109     }
19110
19111     // Otherwise, lower to two pairs of 32-bit loads / stores.
19112     SDValue LoAddr = Ld->getBasePtr();
19113     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19114                                  DAG.getConstant(4, MVT::i32));
19115
19116     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19117                                Ld->getPointerInfo(),
19118                                Ld->isVolatile(), Ld->isNonTemporal(),
19119                                Ld->isInvariant(), Ld->getAlignment());
19120     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19121                                Ld->getPointerInfo().getWithOffset(4),
19122                                Ld->isVolatile(), Ld->isNonTemporal(),
19123                                Ld->isInvariant(),
19124                                MinAlign(Ld->getAlignment(), 4));
19125
19126     SDValue NewChain = LoLd.getValue(1);
19127     if (TokenFactorIndex != -1) {
19128       Ops.push_back(LoLd);
19129       Ops.push_back(HiLd);
19130       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19131                              Ops.size());
19132     }
19133
19134     LoAddr = St->getBasePtr();
19135     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19136                          DAG.getConstant(4, MVT::i32));
19137
19138     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19139                                 St->getPointerInfo(),
19140                                 St->isVolatile(), St->isNonTemporal(),
19141                                 St->getAlignment());
19142     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19143                                 St->getPointerInfo().getWithOffset(4),
19144                                 St->isVolatile(),
19145                                 St->isNonTemporal(),
19146                                 MinAlign(St->getAlignment(), 4));
19147     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19148   }
19149   return SDValue();
19150 }
19151
19152 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19153 /// and return the operands for the horizontal operation in LHS and RHS.  A
19154 /// horizontal operation performs the binary operation on successive elements
19155 /// of its first operand, then on successive elements of its second operand,
19156 /// returning the resulting values in a vector.  For example, if
19157 ///   A = < float a0, float a1, float a2, float a3 >
19158 /// and
19159 ///   B = < float b0, float b1, float b2, float b3 >
19160 /// then the result of doing a horizontal operation on A and B is
19161 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19162 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19163 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19164 /// set to A, RHS to B, and the routine returns 'true'.
19165 /// Note that the binary operation should have the property that if one of the
19166 /// operands is UNDEF then the result is UNDEF.
19167 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19168   // Look for the following pattern: if
19169   //   A = < float a0, float a1, float a2, float a3 >
19170   //   B = < float b0, float b1, float b2, float b3 >
19171   // and
19172   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19173   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19174   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19175   // which is A horizontal-op B.
19176
19177   // At least one of the operands should be a vector shuffle.
19178   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19179       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19180     return false;
19181
19182   MVT VT = LHS.getSimpleValueType();
19183
19184   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19185          "Unsupported vector type for horizontal add/sub");
19186
19187   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19188   // operate independently on 128-bit lanes.
19189   unsigned NumElts = VT.getVectorNumElements();
19190   unsigned NumLanes = VT.getSizeInBits()/128;
19191   unsigned NumLaneElts = NumElts / NumLanes;
19192   assert((NumLaneElts % 2 == 0) &&
19193          "Vector type should have an even number of elements in each lane");
19194   unsigned HalfLaneElts = NumLaneElts/2;
19195
19196   // View LHS in the form
19197   //   LHS = VECTOR_SHUFFLE A, B, LMask
19198   // If LHS is not a shuffle then pretend it is the shuffle
19199   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19200   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19201   // type VT.
19202   SDValue A, B;
19203   SmallVector<int, 16> LMask(NumElts);
19204   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19205     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19206       A = LHS.getOperand(0);
19207     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19208       B = LHS.getOperand(1);
19209     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19210     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19211   } else {
19212     if (LHS.getOpcode() != ISD::UNDEF)
19213       A = LHS;
19214     for (unsigned i = 0; i != NumElts; ++i)
19215       LMask[i] = i;
19216   }
19217
19218   // Likewise, view RHS in the form
19219   //   RHS = VECTOR_SHUFFLE C, D, RMask
19220   SDValue C, D;
19221   SmallVector<int, 16> RMask(NumElts);
19222   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19223     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19224       C = RHS.getOperand(0);
19225     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19226       D = RHS.getOperand(1);
19227     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19228     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19229   } else {
19230     if (RHS.getOpcode() != ISD::UNDEF)
19231       C = RHS;
19232     for (unsigned i = 0; i != NumElts; ++i)
19233       RMask[i] = i;
19234   }
19235
19236   // Check that the shuffles are both shuffling the same vectors.
19237   if (!(A == C && B == D) && !(A == D && B == C))
19238     return false;
19239
19240   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19241   if (!A.getNode() && !B.getNode())
19242     return false;
19243
19244   // If A and B occur in reverse order in RHS, then "swap" them (which means
19245   // rewriting the mask).
19246   if (A != C)
19247     CommuteVectorShuffleMask(RMask, NumElts);
19248
19249   // At this point LHS and RHS are equivalent to
19250   //   LHS = VECTOR_SHUFFLE A, B, LMask
19251   //   RHS = VECTOR_SHUFFLE A, B, RMask
19252   // Check that the masks correspond to performing a horizontal operation.
19253   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19254     for (unsigned i = 0; i != NumLaneElts; ++i) {
19255       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19256
19257       // Ignore any UNDEF components.
19258       if (LIdx < 0 || RIdx < 0 ||
19259           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19260           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19261         continue;
19262
19263       // Check that successive elements are being operated on.  If not, this is
19264       // not a horizontal operation.
19265       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19266       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19267       if (!(LIdx == Index && RIdx == Index + 1) &&
19268           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19269         return false;
19270     }
19271   }
19272
19273   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19274   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19275   return true;
19276 }
19277
19278 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19279 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19280                                   const X86Subtarget *Subtarget) {
19281   EVT VT = N->getValueType(0);
19282   SDValue LHS = N->getOperand(0);
19283   SDValue RHS = N->getOperand(1);
19284
19285   // Try to synthesize horizontal adds from adds of shuffles.
19286   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19287        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19288       isHorizontalBinOp(LHS, RHS, true))
19289     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19290   return SDValue();
19291 }
19292
19293 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19294 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19295                                   const X86Subtarget *Subtarget) {
19296   EVT VT = N->getValueType(0);
19297   SDValue LHS = N->getOperand(0);
19298   SDValue RHS = N->getOperand(1);
19299
19300   // Try to synthesize horizontal subs from subs of shuffles.
19301   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19302        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19303       isHorizontalBinOp(LHS, RHS, false))
19304     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19305   return SDValue();
19306 }
19307
19308 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19309 /// X86ISD::FXOR nodes.
19310 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19311   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19312   // F[X]OR(0.0, x) -> x
19313   // F[X]OR(x, 0.0) -> x
19314   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19315     if (C->getValueAPF().isPosZero())
19316       return N->getOperand(1);
19317   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19318     if (C->getValueAPF().isPosZero())
19319       return N->getOperand(0);
19320   return SDValue();
19321 }
19322
19323 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19324 /// X86ISD::FMAX nodes.
19325 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19326   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19327
19328   // Only perform optimizations if UnsafeMath is used.
19329   if (!DAG.getTarget().Options.UnsafeFPMath)
19330     return SDValue();
19331
19332   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19333   // into FMINC and FMAXC, which are Commutative operations.
19334   unsigned NewOp = 0;
19335   switch (N->getOpcode()) {
19336     default: llvm_unreachable("unknown opcode");
19337     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19338     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19339   }
19340
19341   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19342                      N->getOperand(0), N->getOperand(1));
19343 }
19344
19345 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19346 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19347   // FAND(0.0, x) -> 0.0
19348   // FAND(x, 0.0) -> 0.0
19349   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19350     if (C->getValueAPF().isPosZero())
19351       return N->getOperand(0);
19352   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19353     if (C->getValueAPF().isPosZero())
19354       return N->getOperand(1);
19355   return SDValue();
19356 }
19357
19358 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19359 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19360   // FANDN(x, 0.0) -> 0.0
19361   // FANDN(0.0, x) -> x
19362   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19363     if (C->getValueAPF().isPosZero())
19364       return N->getOperand(1);
19365   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19366     if (C->getValueAPF().isPosZero())
19367       return N->getOperand(1);
19368   return SDValue();
19369 }
19370
19371 static SDValue PerformBTCombine(SDNode *N,
19372                                 SelectionDAG &DAG,
19373                                 TargetLowering::DAGCombinerInfo &DCI) {
19374   // BT ignores high bits in the bit index operand.
19375   SDValue Op1 = N->getOperand(1);
19376   if (Op1.hasOneUse()) {
19377     unsigned BitWidth = Op1.getValueSizeInBits();
19378     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19379     APInt KnownZero, KnownOne;
19380     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19381                                           !DCI.isBeforeLegalizeOps());
19382     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19383     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19384         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19385       DCI.CommitTargetLoweringOpt(TLO);
19386   }
19387   return SDValue();
19388 }
19389
19390 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19391   SDValue Op = N->getOperand(0);
19392   if (Op.getOpcode() == ISD::BITCAST)
19393     Op = Op.getOperand(0);
19394   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19395   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19396       VT.getVectorElementType().getSizeInBits() ==
19397       OpVT.getVectorElementType().getSizeInBits()) {
19398     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19399   }
19400   return SDValue();
19401 }
19402
19403 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19404                                                const X86Subtarget *Subtarget) {
19405   EVT VT = N->getValueType(0);
19406   if (!VT.isVector())
19407     return SDValue();
19408
19409   SDValue N0 = N->getOperand(0);
19410   SDValue N1 = N->getOperand(1);
19411   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19412   SDLoc dl(N);
19413
19414   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19415   // both SSE and AVX2 since there is no sign-extended shift right
19416   // operation on a vector with 64-bit elements.
19417   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19418   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19419   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19420       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19421     SDValue N00 = N0.getOperand(0);
19422
19423     // EXTLOAD has a better solution on AVX2,
19424     // it may be replaced with X86ISD::VSEXT node.
19425     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19426       if (!ISD::isNormalLoad(N00.getNode()))
19427         return SDValue();
19428
19429     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19430         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19431                                   N00, N1);
19432       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19433     }
19434   }
19435   return SDValue();
19436 }
19437
19438 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19439                                   TargetLowering::DAGCombinerInfo &DCI,
19440                                   const X86Subtarget *Subtarget) {
19441   if (!DCI.isBeforeLegalizeOps())
19442     return SDValue();
19443
19444   if (!Subtarget->hasFp256())
19445     return SDValue();
19446
19447   EVT VT = N->getValueType(0);
19448   if (VT.isVector() && VT.getSizeInBits() == 256) {
19449     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19450     if (R.getNode())
19451       return R;
19452   }
19453
19454   return SDValue();
19455 }
19456
19457 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19458                                  const X86Subtarget* Subtarget) {
19459   SDLoc dl(N);
19460   EVT VT = N->getValueType(0);
19461
19462   // Let legalize expand this if it isn't a legal type yet.
19463   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19464     return SDValue();
19465
19466   EVT ScalarVT = VT.getScalarType();
19467   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19468       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19469     return SDValue();
19470
19471   SDValue A = N->getOperand(0);
19472   SDValue B = N->getOperand(1);
19473   SDValue C = N->getOperand(2);
19474
19475   bool NegA = (A.getOpcode() == ISD::FNEG);
19476   bool NegB = (B.getOpcode() == ISD::FNEG);
19477   bool NegC = (C.getOpcode() == ISD::FNEG);
19478
19479   // Negative multiplication when NegA xor NegB
19480   bool NegMul = (NegA != NegB);
19481   if (NegA)
19482     A = A.getOperand(0);
19483   if (NegB)
19484     B = B.getOperand(0);
19485   if (NegC)
19486     C = C.getOperand(0);
19487
19488   unsigned Opcode;
19489   if (!NegMul)
19490     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19491   else
19492     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19493
19494   return DAG.getNode(Opcode, dl, VT, A, B, C);
19495 }
19496
19497 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19498                                   TargetLowering::DAGCombinerInfo &DCI,
19499                                   const X86Subtarget *Subtarget) {
19500   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19501   //           (and (i32 x86isd::setcc_carry), 1)
19502   // This eliminates the zext. This transformation is necessary because
19503   // ISD::SETCC is always legalized to i8.
19504   SDLoc dl(N);
19505   SDValue N0 = N->getOperand(0);
19506   EVT VT = N->getValueType(0);
19507
19508   if (N0.getOpcode() == ISD::AND &&
19509       N0.hasOneUse() &&
19510       N0.getOperand(0).hasOneUse()) {
19511     SDValue N00 = N0.getOperand(0);
19512     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19513       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19514       if (!C || C->getZExtValue() != 1)
19515         return SDValue();
19516       return DAG.getNode(ISD::AND, dl, VT,
19517                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19518                                      N00.getOperand(0), N00.getOperand(1)),
19519                          DAG.getConstant(1, VT));
19520     }
19521   }
19522
19523   if (N0.getOpcode() == ISD::TRUNCATE &&
19524       N0.hasOneUse() &&
19525       N0.getOperand(0).hasOneUse()) {
19526     SDValue N00 = N0.getOperand(0);
19527     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19528       return DAG.getNode(ISD::AND, dl, VT,
19529                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19530                                      N00.getOperand(0), N00.getOperand(1)),
19531                          DAG.getConstant(1, VT));
19532     }
19533   }
19534   if (VT.is256BitVector()) {
19535     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19536     if (R.getNode())
19537       return R;
19538   }
19539
19540   return SDValue();
19541 }
19542
19543 // Optimize x == -y --> x+y == 0
19544 //          x != -y --> x+y != 0
19545 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19546                                       const X86Subtarget* Subtarget) {
19547   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19548   SDValue LHS = N->getOperand(0);
19549   SDValue RHS = N->getOperand(1);
19550   EVT VT = N->getValueType(0);
19551   SDLoc DL(N);
19552
19553   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19554     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19555       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19556         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19557                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19558         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19559                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19560       }
19561   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19563       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19564         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19565                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19566         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19567                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19568       }
19569
19570   if (VT.getScalarType() == MVT::i1) {
19571     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19572       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19573     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19574     if (!IsSEXT0 && !IsVZero0)
19575       return SDValue();
19576     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19577       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19578     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19579
19580     if (!IsSEXT1 && !IsVZero1)
19581       return SDValue();
19582
19583     if (IsSEXT0 && IsVZero1) {
19584       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19585       if (CC == ISD::SETEQ)
19586         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19587       return LHS.getOperand(0);
19588     }
19589     if (IsSEXT1 && IsVZero0) {
19590       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19591       if (CC == ISD::SETEQ)
19592         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19593       return RHS.getOperand(0);
19594     }
19595   }
19596
19597   return SDValue();
19598 }
19599
19600 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19601 // as "sbb reg,reg", since it can be extended without zext and produces
19602 // an all-ones bit which is more useful than 0/1 in some cases.
19603 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19604                                MVT VT) {
19605   if (VT == MVT::i8)
19606     return DAG.getNode(ISD::AND, DL, VT,
19607                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19608                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19609                        DAG.getConstant(1, VT));
19610   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19611   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19612                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19613                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19614 }
19615
19616 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19617 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19618                                    TargetLowering::DAGCombinerInfo &DCI,
19619                                    const X86Subtarget *Subtarget) {
19620   SDLoc DL(N);
19621   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19622   SDValue EFLAGS = N->getOperand(1);
19623
19624   if (CC == X86::COND_A) {
19625     // Try to convert COND_A into COND_B in an attempt to facilitate
19626     // materializing "setb reg".
19627     //
19628     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19629     // cannot take an immediate as its first operand.
19630     //
19631     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19632         EFLAGS.getValueType().isInteger() &&
19633         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19634       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19635                                    EFLAGS.getNode()->getVTList(),
19636                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19637       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19638       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19639     }
19640   }
19641
19642   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19643   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19644   // cases.
19645   if (CC == X86::COND_B)
19646     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19647
19648   SDValue Flags;
19649
19650   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19651   if (Flags.getNode()) {
19652     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19653     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19654   }
19655
19656   return SDValue();
19657 }
19658
19659 // Optimize branch condition evaluation.
19660 //
19661 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19662                                     TargetLowering::DAGCombinerInfo &DCI,
19663                                     const X86Subtarget *Subtarget) {
19664   SDLoc DL(N);
19665   SDValue Chain = N->getOperand(0);
19666   SDValue Dest = N->getOperand(1);
19667   SDValue EFLAGS = N->getOperand(3);
19668   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19669
19670   SDValue Flags;
19671
19672   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19673   if (Flags.getNode()) {
19674     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19675     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19676                        Flags);
19677   }
19678
19679   return SDValue();
19680 }
19681
19682 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19683                                         const X86TargetLowering *XTLI) {
19684   SDValue Op0 = N->getOperand(0);
19685   EVT InVT = Op0->getValueType(0);
19686
19687   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19688   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19689     SDLoc dl(N);
19690     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19691     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19692     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19693   }
19694
19695   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19696   // a 32-bit target where SSE doesn't support i64->FP operations.
19697   if (Op0.getOpcode() == ISD::LOAD) {
19698     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19699     EVT VT = Ld->getValueType(0);
19700     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19701         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19702         !XTLI->getSubtarget()->is64Bit() &&
19703         VT == MVT::i64) {
19704       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19705                                           Ld->getChain(), Op0, DAG);
19706       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19707       return FILDChain;
19708     }
19709   }
19710   return SDValue();
19711 }
19712
19713 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19714 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19715                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19716   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19717   // the result is either zero or one (depending on the input carry bit).
19718   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19719   if (X86::isZeroNode(N->getOperand(0)) &&
19720       X86::isZeroNode(N->getOperand(1)) &&
19721       // We don't have a good way to replace an EFLAGS use, so only do this when
19722       // dead right now.
19723       SDValue(N, 1).use_empty()) {
19724     SDLoc DL(N);
19725     EVT VT = N->getValueType(0);
19726     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19727     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19728                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19729                                            DAG.getConstant(X86::COND_B,MVT::i8),
19730                                            N->getOperand(2)),
19731                                DAG.getConstant(1, VT));
19732     return DCI.CombineTo(N, Res1, CarryOut);
19733   }
19734
19735   return SDValue();
19736 }
19737
19738 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19739 //      (add Y, (setne X, 0)) -> sbb -1, Y
19740 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19741 //      (sub (setne X, 0), Y) -> adc -1, Y
19742 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19743   SDLoc DL(N);
19744
19745   // Look through ZExts.
19746   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19747   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19748     return SDValue();
19749
19750   SDValue SetCC = Ext.getOperand(0);
19751   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19752     return SDValue();
19753
19754   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19755   if (CC != X86::COND_E && CC != X86::COND_NE)
19756     return SDValue();
19757
19758   SDValue Cmp = SetCC.getOperand(1);
19759   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19760       !X86::isZeroNode(Cmp.getOperand(1)) ||
19761       !Cmp.getOperand(0).getValueType().isInteger())
19762     return SDValue();
19763
19764   SDValue CmpOp0 = Cmp.getOperand(0);
19765   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19766                                DAG.getConstant(1, CmpOp0.getValueType()));
19767
19768   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19769   if (CC == X86::COND_NE)
19770     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19771                        DL, OtherVal.getValueType(), OtherVal,
19772                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19773   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19774                      DL, OtherVal.getValueType(), OtherVal,
19775                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19776 }
19777
19778 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19779 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19780                                  const X86Subtarget *Subtarget) {
19781   EVT VT = N->getValueType(0);
19782   SDValue Op0 = N->getOperand(0);
19783   SDValue Op1 = N->getOperand(1);
19784
19785   // Try to synthesize horizontal adds from adds of shuffles.
19786   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19787        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19788       isHorizontalBinOp(Op0, Op1, true))
19789     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19790
19791   return OptimizeConditionalInDecrement(N, DAG);
19792 }
19793
19794 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19795                                  const X86Subtarget *Subtarget) {
19796   SDValue Op0 = N->getOperand(0);
19797   SDValue Op1 = N->getOperand(1);
19798
19799   // X86 can't encode an immediate LHS of a sub. See if we can push the
19800   // negation into a preceding instruction.
19801   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19802     // If the RHS of the sub is a XOR with one use and a constant, invert the
19803     // immediate. Then add one to the LHS of the sub so we can turn
19804     // X-Y -> X+~Y+1, saving one register.
19805     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19806         isa<ConstantSDNode>(Op1.getOperand(1))) {
19807       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19808       EVT VT = Op0.getValueType();
19809       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19810                                    Op1.getOperand(0),
19811                                    DAG.getConstant(~XorC, VT));
19812       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19813                          DAG.getConstant(C->getAPIntValue()+1, VT));
19814     }
19815   }
19816
19817   // Try to synthesize horizontal adds from adds of shuffles.
19818   EVT VT = N->getValueType(0);
19819   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19820        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19821       isHorizontalBinOp(Op0, Op1, true))
19822     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19823
19824   return OptimizeConditionalInDecrement(N, DAG);
19825 }
19826
19827 /// performVZEXTCombine - Performs build vector combines
19828 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19829                                         TargetLowering::DAGCombinerInfo &DCI,
19830                                         const X86Subtarget *Subtarget) {
19831   // (vzext (bitcast (vzext (x)) -> (vzext x)
19832   SDValue In = N->getOperand(0);
19833   while (In.getOpcode() == ISD::BITCAST)
19834     In = In.getOperand(0);
19835
19836   if (In.getOpcode() != X86ISD::VZEXT)
19837     return SDValue();
19838
19839   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19840                      In.getOperand(0));
19841 }
19842
19843 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19844                                              DAGCombinerInfo &DCI) const {
19845   SelectionDAG &DAG = DCI.DAG;
19846   switch (N->getOpcode()) {
19847   default: break;
19848   case ISD::EXTRACT_VECTOR_ELT:
19849     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19850   case ISD::VSELECT:
19851   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19852   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19853   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19854   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19855   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19856   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19857   case ISD::SHL:
19858   case ISD::SRA:
19859   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19860   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19861   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19862   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19863   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19864   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19865   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19866   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19867   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19868   case X86ISD::FXOR:
19869   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19870   case X86ISD::FMIN:
19871   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19872   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19873   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19874   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19875   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19876   case ISD::ANY_EXTEND:
19877   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19878   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19879   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19880   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19881   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19882   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19883   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19884   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19885   case X86ISD::SHUFP:       // Handle all target specific shuffles
19886   case X86ISD::PALIGNR:
19887   case X86ISD::UNPCKH:
19888   case X86ISD::UNPCKL:
19889   case X86ISD::MOVHLPS:
19890   case X86ISD::MOVLHPS:
19891   case X86ISD::PSHUFD:
19892   case X86ISD::PSHUFHW:
19893   case X86ISD::PSHUFLW:
19894   case X86ISD::MOVSS:
19895   case X86ISD::MOVSD:
19896   case X86ISD::VPERMILP:
19897   case X86ISD::VPERM2X128:
19898   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19899   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19900   }
19901
19902   return SDValue();
19903 }
19904
19905 /// isTypeDesirableForOp - Return true if the target has native support for
19906 /// the specified value type and it is 'desirable' to use the type for the
19907 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19908 /// instruction encodings are longer and some i16 instructions are slow.
19909 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19910   if (!isTypeLegal(VT))
19911     return false;
19912   if (VT != MVT::i16)
19913     return true;
19914
19915   switch (Opc) {
19916   default:
19917     return true;
19918   case ISD::LOAD:
19919   case ISD::SIGN_EXTEND:
19920   case ISD::ZERO_EXTEND:
19921   case ISD::ANY_EXTEND:
19922   case ISD::SHL:
19923   case ISD::SRL:
19924   case ISD::SUB:
19925   case ISD::ADD:
19926   case ISD::MUL:
19927   case ISD::AND:
19928   case ISD::OR:
19929   case ISD::XOR:
19930     return false;
19931   }
19932 }
19933
19934 /// IsDesirableToPromoteOp - This method query the target whether it is
19935 /// beneficial for dag combiner to promote the specified node. If true, it
19936 /// should return the desired promotion type by reference.
19937 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19938   EVT VT = Op.getValueType();
19939   if (VT != MVT::i16)
19940     return false;
19941
19942   bool Promote = false;
19943   bool Commute = false;
19944   switch (Op.getOpcode()) {
19945   default: break;
19946   case ISD::LOAD: {
19947     LoadSDNode *LD = cast<LoadSDNode>(Op);
19948     // If the non-extending load has a single use and it's not live out, then it
19949     // might be folded.
19950     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19951                                                      Op.hasOneUse()*/) {
19952       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19953              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19954         // The only case where we'd want to promote LOAD (rather then it being
19955         // promoted as an operand is when it's only use is liveout.
19956         if (UI->getOpcode() != ISD::CopyToReg)
19957           return false;
19958       }
19959     }
19960     Promote = true;
19961     break;
19962   }
19963   case ISD::SIGN_EXTEND:
19964   case ISD::ZERO_EXTEND:
19965   case ISD::ANY_EXTEND:
19966     Promote = true;
19967     break;
19968   case ISD::SHL:
19969   case ISD::SRL: {
19970     SDValue N0 = Op.getOperand(0);
19971     // Look out for (store (shl (load), x)).
19972     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19973       return false;
19974     Promote = true;
19975     break;
19976   }
19977   case ISD::ADD:
19978   case ISD::MUL:
19979   case ISD::AND:
19980   case ISD::OR:
19981   case ISD::XOR:
19982     Commute = true;
19983     // fallthrough
19984   case ISD::SUB: {
19985     SDValue N0 = Op.getOperand(0);
19986     SDValue N1 = Op.getOperand(1);
19987     if (!Commute && MayFoldLoad(N1))
19988       return false;
19989     // Avoid disabling potential load folding opportunities.
19990     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19991       return false;
19992     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19993       return false;
19994     Promote = true;
19995   }
19996   }
19997
19998   PVT = MVT::i32;
19999   return Promote;
20000 }
20001
20002 //===----------------------------------------------------------------------===//
20003 //                           X86 Inline Assembly Support
20004 //===----------------------------------------------------------------------===//
20005
20006 namespace {
20007   // Helper to match a string separated by whitespace.
20008   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20009     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20010
20011     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20012       StringRef piece(*args[i]);
20013       if (!s.startswith(piece)) // Check if the piece matches.
20014         return false;
20015
20016       s = s.substr(piece.size());
20017       StringRef::size_type pos = s.find_first_not_of(" \t");
20018       if (pos == 0) // We matched a prefix.
20019         return false;
20020
20021       s = s.substr(pos);
20022     }
20023
20024     return s.empty();
20025   }
20026   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20027 }
20028
20029 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20030
20031   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20032     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20033         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20034         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20035
20036       if (AsmPieces.size() == 3)
20037         return true;
20038       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20039         return true;
20040     }
20041   }
20042   return false;
20043 }
20044
20045 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20046   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20047
20048   std::string AsmStr = IA->getAsmString();
20049
20050   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20051   if (!Ty || Ty->getBitWidth() % 16 != 0)
20052     return false;
20053
20054   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20055   SmallVector<StringRef, 4> AsmPieces;
20056   SplitString(AsmStr, AsmPieces, ";\n");
20057
20058   switch (AsmPieces.size()) {
20059   default: return false;
20060   case 1:
20061     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20062     // we will turn this bswap into something that will be lowered to logical
20063     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20064     // lower so don't worry about this.
20065     // bswap $0
20066     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20067         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20068         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20069         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20070         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20071         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20072       // No need to check constraints, nothing other than the equivalent of
20073       // "=r,0" would be valid here.
20074       return IntrinsicLowering::LowerToByteSwap(CI);
20075     }
20076
20077     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20078     if (CI->getType()->isIntegerTy(16) &&
20079         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20080         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20081          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20082       AsmPieces.clear();
20083       const std::string &ConstraintsStr = IA->getConstraintString();
20084       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20085       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20086       if (clobbersFlagRegisters(AsmPieces))
20087         return IntrinsicLowering::LowerToByteSwap(CI);
20088     }
20089     break;
20090   case 3:
20091     if (CI->getType()->isIntegerTy(32) &&
20092         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20093         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20094         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20095         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20096       AsmPieces.clear();
20097       const std::string &ConstraintsStr = IA->getConstraintString();
20098       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20099       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20100       if (clobbersFlagRegisters(AsmPieces))
20101         return IntrinsicLowering::LowerToByteSwap(CI);
20102     }
20103
20104     if (CI->getType()->isIntegerTy(64)) {
20105       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20106       if (Constraints.size() >= 2 &&
20107           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20108           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20109         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20110         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20111             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20112             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20113           return IntrinsicLowering::LowerToByteSwap(CI);
20114       }
20115     }
20116     break;
20117   }
20118   return false;
20119 }
20120
20121 /// getConstraintType - Given a constraint letter, return the type of
20122 /// constraint it is for this target.
20123 X86TargetLowering::ConstraintType
20124 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20125   if (Constraint.size() == 1) {
20126     switch (Constraint[0]) {
20127     case 'R':
20128     case 'q':
20129     case 'Q':
20130     case 'f':
20131     case 't':
20132     case 'u':
20133     case 'y':
20134     case 'x':
20135     case 'Y':
20136     case 'l':
20137       return C_RegisterClass;
20138     case 'a':
20139     case 'b':
20140     case 'c':
20141     case 'd':
20142     case 'S':
20143     case 'D':
20144     case 'A':
20145       return C_Register;
20146     case 'I':
20147     case 'J':
20148     case 'K':
20149     case 'L':
20150     case 'M':
20151     case 'N':
20152     case 'G':
20153     case 'C':
20154     case 'e':
20155     case 'Z':
20156       return C_Other;
20157     default:
20158       break;
20159     }
20160   }
20161   return TargetLowering::getConstraintType(Constraint);
20162 }
20163
20164 /// Examine constraint type and operand type and determine a weight value.
20165 /// This object must already have been set up with the operand type
20166 /// and the current alternative constraint selected.
20167 TargetLowering::ConstraintWeight
20168   X86TargetLowering::getSingleConstraintMatchWeight(
20169     AsmOperandInfo &info, const char *constraint) const {
20170   ConstraintWeight weight = CW_Invalid;
20171   Value *CallOperandVal = info.CallOperandVal;
20172     // If we don't have a value, we can't do a match,
20173     // but allow it at the lowest weight.
20174   if (CallOperandVal == NULL)
20175     return CW_Default;
20176   Type *type = CallOperandVal->getType();
20177   // Look at the constraint type.
20178   switch (*constraint) {
20179   default:
20180     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20181   case 'R':
20182   case 'q':
20183   case 'Q':
20184   case 'a':
20185   case 'b':
20186   case 'c':
20187   case 'd':
20188   case 'S':
20189   case 'D':
20190   case 'A':
20191     if (CallOperandVal->getType()->isIntegerTy())
20192       weight = CW_SpecificReg;
20193     break;
20194   case 'f':
20195   case 't':
20196   case 'u':
20197     if (type->isFloatingPointTy())
20198       weight = CW_SpecificReg;
20199     break;
20200   case 'y':
20201     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20202       weight = CW_SpecificReg;
20203     break;
20204   case 'x':
20205   case 'Y':
20206     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20207         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20208       weight = CW_Register;
20209     break;
20210   case 'I':
20211     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20212       if (C->getZExtValue() <= 31)
20213         weight = CW_Constant;
20214     }
20215     break;
20216   case 'J':
20217     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20218       if (C->getZExtValue() <= 63)
20219         weight = CW_Constant;
20220     }
20221     break;
20222   case 'K':
20223     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20224       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20225         weight = CW_Constant;
20226     }
20227     break;
20228   case 'L':
20229     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20230       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20231         weight = CW_Constant;
20232     }
20233     break;
20234   case 'M':
20235     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20236       if (C->getZExtValue() <= 3)
20237         weight = CW_Constant;
20238     }
20239     break;
20240   case 'N':
20241     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20242       if (C->getZExtValue() <= 0xff)
20243         weight = CW_Constant;
20244     }
20245     break;
20246   case 'G':
20247   case 'C':
20248     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20249       weight = CW_Constant;
20250     }
20251     break;
20252   case 'e':
20253     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20254       if ((C->getSExtValue() >= -0x80000000LL) &&
20255           (C->getSExtValue() <= 0x7fffffffLL))
20256         weight = CW_Constant;
20257     }
20258     break;
20259   case 'Z':
20260     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20261       if (C->getZExtValue() <= 0xffffffff)
20262         weight = CW_Constant;
20263     }
20264     break;
20265   }
20266   return weight;
20267 }
20268
20269 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20270 /// with another that has more specific requirements based on the type of the
20271 /// corresponding operand.
20272 const char *X86TargetLowering::
20273 LowerXConstraint(EVT ConstraintVT) const {
20274   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20275   // 'f' like normal targets.
20276   if (ConstraintVT.isFloatingPoint()) {
20277     if (Subtarget->hasSSE2())
20278       return "Y";
20279     if (Subtarget->hasSSE1())
20280       return "x";
20281   }
20282
20283   return TargetLowering::LowerXConstraint(ConstraintVT);
20284 }
20285
20286 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20287 /// vector.  If it is invalid, don't add anything to Ops.
20288 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20289                                                      std::string &Constraint,
20290                                                      std::vector<SDValue>&Ops,
20291                                                      SelectionDAG &DAG) const {
20292   SDValue Result(0, 0);
20293
20294   // Only support length 1 constraints for now.
20295   if (Constraint.length() > 1) return;
20296
20297   char ConstraintLetter = Constraint[0];
20298   switch (ConstraintLetter) {
20299   default: break;
20300   case 'I':
20301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20302       if (C->getZExtValue() <= 31) {
20303         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20304         break;
20305       }
20306     }
20307     return;
20308   case 'J':
20309     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20310       if (C->getZExtValue() <= 63) {
20311         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20312         break;
20313       }
20314     }
20315     return;
20316   case 'K':
20317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20318       if (isInt<8>(C->getSExtValue())) {
20319         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20320         break;
20321       }
20322     }
20323     return;
20324   case 'N':
20325     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20326       if (C->getZExtValue() <= 255) {
20327         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20328         break;
20329       }
20330     }
20331     return;
20332   case 'e': {
20333     // 32-bit signed value
20334     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20335       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20336                                            C->getSExtValue())) {
20337         // Widen to 64 bits here to get it sign extended.
20338         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20339         break;
20340       }
20341     // FIXME gcc accepts some relocatable values here too, but only in certain
20342     // memory models; it's complicated.
20343     }
20344     return;
20345   }
20346   case 'Z': {
20347     // 32-bit unsigned value
20348     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20349       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20350                                            C->getZExtValue())) {
20351         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20352         break;
20353       }
20354     }
20355     // FIXME gcc accepts some relocatable values here too, but only in certain
20356     // memory models; it's complicated.
20357     return;
20358   }
20359   case 'i': {
20360     // Literal immediates are always ok.
20361     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20362       // Widen to 64 bits here to get it sign extended.
20363       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20364       break;
20365     }
20366
20367     // In any sort of PIC mode addresses need to be computed at runtime by
20368     // adding in a register or some sort of table lookup.  These can't
20369     // be used as immediates.
20370     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20371       return;
20372
20373     // If we are in non-pic codegen mode, we allow the address of a global (with
20374     // an optional displacement) to be used with 'i'.
20375     GlobalAddressSDNode *GA = 0;
20376     int64_t Offset = 0;
20377
20378     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20379     while (1) {
20380       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20381         Offset += GA->getOffset();
20382         break;
20383       } else if (Op.getOpcode() == ISD::ADD) {
20384         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20385           Offset += C->getZExtValue();
20386           Op = Op.getOperand(0);
20387           continue;
20388         }
20389       } else if (Op.getOpcode() == ISD::SUB) {
20390         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20391           Offset += -C->getZExtValue();
20392           Op = Op.getOperand(0);
20393           continue;
20394         }
20395       }
20396
20397       // Otherwise, this isn't something we can handle, reject it.
20398       return;
20399     }
20400
20401     const GlobalValue *GV = GA->getGlobal();
20402     // If we require an extra load to get this address, as in PIC mode, we
20403     // can't accept it.
20404     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20405                                                         getTargetMachine())))
20406       return;
20407
20408     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20409                                         GA->getValueType(0), Offset);
20410     break;
20411   }
20412   }
20413
20414   if (Result.getNode()) {
20415     Ops.push_back(Result);
20416     return;
20417   }
20418   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20419 }
20420
20421 std::pair<unsigned, const TargetRegisterClass*>
20422 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20423                                                 MVT VT) const {
20424   // First, see if this is a constraint that directly corresponds to an LLVM
20425   // register class.
20426   if (Constraint.size() == 1) {
20427     // GCC Constraint Letters
20428     switch (Constraint[0]) {
20429     default: break;
20430       // TODO: Slight differences here in allocation order and leaving
20431       // RIP in the class. Do they matter any more here than they do
20432       // in the normal allocation?
20433     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20434       if (Subtarget->is64Bit()) {
20435         if (VT == MVT::i32 || VT == MVT::f32)
20436           return std::make_pair(0U, &X86::GR32RegClass);
20437         if (VT == MVT::i16)
20438           return std::make_pair(0U, &X86::GR16RegClass);
20439         if (VT == MVT::i8 || VT == MVT::i1)
20440           return std::make_pair(0U, &X86::GR8RegClass);
20441         if (VT == MVT::i64 || VT == MVT::f64)
20442           return std::make_pair(0U, &X86::GR64RegClass);
20443         break;
20444       }
20445       // 32-bit fallthrough
20446     case 'Q':   // Q_REGS
20447       if (VT == MVT::i32 || VT == MVT::f32)
20448         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20449       if (VT == MVT::i16)
20450         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20451       if (VT == MVT::i8 || VT == MVT::i1)
20452         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20453       if (VT == MVT::i64)
20454         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20455       break;
20456     case 'r':   // GENERAL_REGS
20457     case 'l':   // INDEX_REGS
20458       if (VT == MVT::i8 || VT == MVT::i1)
20459         return std::make_pair(0U, &X86::GR8RegClass);
20460       if (VT == MVT::i16)
20461         return std::make_pair(0U, &X86::GR16RegClass);
20462       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20463         return std::make_pair(0U, &X86::GR32RegClass);
20464       return std::make_pair(0U, &X86::GR64RegClass);
20465     case 'R':   // LEGACY_REGS
20466       if (VT == MVT::i8 || VT == MVT::i1)
20467         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20468       if (VT == MVT::i16)
20469         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20470       if (VT == MVT::i32 || !Subtarget->is64Bit())
20471         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20472       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20473     case 'f':  // FP Stack registers.
20474       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20475       // value to the correct fpstack register class.
20476       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20477         return std::make_pair(0U, &X86::RFP32RegClass);
20478       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20479         return std::make_pair(0U, &X86::RFP64RegClass);
20480       return std::make_pair(0U, &X86::RFP80RegClass);
20481     case 'y':   // MMX_REGS if MMX allowed.
20482       if (!Subtarget->hasMMX()) break;
20483       return std::make_pair(0U, &X86::VR64RegClass);
20484     case 'Y':   // SSE_REGS if SSE2 allowed
20485       if (!Subtarget->hasSSE2()) break;
20486       // FALL THROUGH.
20487     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20488       if (!Subtarget->hasSSE1()) break;
20489
20490       switch (VT.SimpleTy) {
20491       default: break;
20492       // Scalar SSE types.
20493       case MVT::f32:
20494       case MVT::i32:
20495         return std::make_pair(0U, &X86::FR32RegClass);
20496       case MVT::f64:
20497       case MVT::i64:
20498         return std::make_pair(0U, &X86::FR64RegClass);
20499       // Vector types.
20500       case MVT::v16i8:
20501       case MVT::v8i16:
20502       case MVT::v4i32:
20503       case MVT::v2i64:
20504       case MVT::v4f32:
20505       case MVT::v2f64:
20506         return std::make_pair(0U, &X86::VR128RegClass);
20507       // AVX types.
20508       case MVT::v32i8:
20509       case MVT::v16i16:
20510       case MVT::v8i32:
20511       case MVT::v4i64:
20512       case MVT::v8f32:
20513       case MVT::v4f64:
20514         return std::make_pair(0U, &X86::VR256RegClass);
20515       case MVT::v8f64:
20516       case MVT::v16f32:
20517       case MVT::v16i32:
20518       case MVT::v8i64:
20519         return std::make_pair(0U, &X86::VR512RegClass);
20520       }
20521       break;
20522     }
20523   }
20524
20525   // Use the default implementation in TargetLowering to convert the register
20526   // constraint into a member of a register class.
20527   std::pair<unsigned, const TargetRegisterClass*> Res;
20528   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20529
20530   // Not found as a standard register?
20531   if (Res.second == 0) {
20532     // Map st(0) -> st(7) -> ST0
20533     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20534         tolower(Constraint[1]) == 's' &&
20535         tolower(Constraint[2]) == 't' &&
20536         Constraint[3] == '(' &&
20537         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20538         Constraint[5] == ')' &&
20539         Constraint[6] == '}') {
20540
20541       Res.first = X86::ST0+Constraint[4]-'0';
20542       Res.second = &X86::RFP80RegClass;
20543       return Res;
20544     }
20545
20546     // GCC allows "st(0)" to be called just plain "st".
20547     if (StringRef("{st}").equals_lower(Constraint)) {
20548       Res.first = X86::ST0;
20549       Res.second = &X86::RFP80RegClass;
20550       return Res;
20551     }
20552
20553     // flags -> EFLAGS
20554     if (StringRef("{flags}").equals_lower(Constraint)) {
20555       Res.first = X86::EFLAGS;
20556       Res.second = &X86::CCRRegClass;
20557       return Res;
20558     }
20559
20560     // 'A' means EAX + EDX.
20561     if (Constraint == "A") {
20562       Res.first = X86::EAX;
20563       Res.second = &X86::GR32_ADRegClass;
20564       return Res;
20565     }
20566     return Res;
20567   }
20568
20569   // Otherwise, check to see if this is a register class of the wrong value
20570   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20571   // turn into {ax},{dx}.
20572   if (Res.second->hasType(VT))
20573     return Res;   // Correct type already, nothing to do.
20574
20575   // All of the single-register GCC register classes map their values onto
20576   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20577   // really want an 8-bit or 32-bit register, map to the appropriate register
20578   // class and return the appropriate register.
20579   if (Res.second == &X86::GR16RegClass) {
20580     if (VT == MVT::i8 || VT == MVT::i1) {
20581       unsigned DestReg = 0;
20582       switch (Res.first) {
20583       default: break;
20584       case X86::AX: DestReg = X86::AL; break;
20585       case X86::DX: DestReg = X86::DL; break;
20586       case X86::CX: DestReg = X86::CL; break;
20587       case X86::BX: DestReg = X86::BL; break;
20588       }
20589       if (DestReg) {
20590         Res.first = DestReg;
20591         Res.second = &X86::GR8RegClass;
20592       }
20593     } else if (VT == MVT::i32 || VT == MVT::f32) {
20594       unsigned DestReg = 0;
20595       switch (Res.first) {
20596       default: break;
20597       case X86::AX: DestReg = X86::EAX; break;
20598       case X86::DX: DestReg = X86::EDX; break;
20599       case X86::CX: DestReg = X86::ECX; break;
20600       case X86::BX: DestReg = X86::EBX; break;
20601       case X86::SI: DestReg = X86::ESI; break;
20602       case X86::DI: DestReg = X86::EDI; break;
20603       case X86::BP: DestReg = X86::EBP; break;
20604       case X86::SP: DestReg = X86::ESP; break;
20605       }
20606       if (DestReg) {
20607         Res.first = DestReg;
20608         Res.second = &X86::GR32RegClass;
20609       }
20610     } else if (VT == MVT::i64 || VT == MVT::f64) {
20611       unsigned DestReg = 0;
20612       switch (Res.first) {
20613       default: break;
20614       case X86::AX: DestReg = X86::RAX; break;
20615       case X86::DX: DestReg = X86::RDX; break;
20616       case X86::CX: DestReg = X86::RCX; break;
20617       case X86::BX: DestReg = X86::RBX; break;
20618       case X86::SI: DestReg = X86::RSI; break;
20619       case X86::DI: DestReg = X86::RDI; break;
20620       case X86::BP: DestReg = X86::RBP; break;
20621       case X86::SP: DestReg = X86::RSP; break;
20622       }
20623       if (DestReg) {
20624         Res.first = DestReg;
20625         Res.second = &X86::GR64RegClass;
20626       }
20627     }
20628   } else if (Res.second == &X86::FR32RegClass ||
20629              Res.second == &X86::FR64RegClass ||
20630              Res.second == &X86::VR128RegClass ||
20631              Res.second == &X86::VR256RegClass ||
20632              Res.second == &X86::FR32XRegClass ||
20633              Res.second == &X86::FR64XRegClass ||
20634              Res.second == &X86::VR128XRegClass ||
20635              Res.second == &X86::VR256XRegClass ||
20636              Res.second == &X86::VR512RegClass) {
20637     // Handle references to XMM physical registers that got mapped into the
20638     // wrong class.  This can happen with constraints like {xmm0} where the
20639     // target independent register mapper will just pick the first match it can
20640     // find, ignoring the required type.
20641
20642     if (VT == MVT::f32 || VT == MVT::i32)
20643       Res.second = &X86::FR32RegClass;
20644     else if (VT == MVT::f64 || VT == MVT::i64)
20645       Res.second = &X86::FR64RegClass;
20646     else if (X86::VR128RegClass.hasType(VT))
20647       Res.second = &X86::VR128RegClass;
20648     else if (X86::VR256RegClass.hasType(VT))
20649       Res.second = &X86::VR256RegClass;
20650     else if (X86::VR512RegClass.hasType(VT))
20651       Res.second = &X86::VR512RegClass;
20652   }
20653
20654   return Res;
20655 }