Clean up unused variable warning in release build.
[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/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorShuffleLowering(
62     "x86-experimental-vector-shuffle-lowering", cl::init(false),
63     cl::desc("Enable an experimental vector shuffle lowering code path."),
64     cl::Hidden);
65
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
68                        SDValue V2);
69
70 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
71                                 SelectionDAG &DAG, SDLoc dl,
72                                 unsigned vectorWidth) {
73   assert((vectorWidth == 128 || vectorWidth == 256) &&
74          "Unsupported vector width");
75   EVT VT = Vec.getValueType();
76   EVT ElVT = VT.getVectorElementType();
77   unsigned Factor = VT.getSizeInBits()/vectorWidth;
78   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
79                                   VT.getVectorNumElements()/Factor);
80
81   // Extract from UNDEF is UNDEF.
82   if (Vec.getOpcode() == ISD::UNDEF)
83     return DAG.getUNDEF(ResultVT);
84
85   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
86   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
87
88   // This is the index of the first element of the vectorWidth-bit chunk
89   // we want.
90   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
91                                * ElemsPerChunk);
92
93   // If the input is a buildvector just emit a smaller one.
94   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
95     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
96                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
97                                     ElemsPerChunk));
98
99   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
100   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
101                                VecIdx);
102
103   return Result;
104
105 }
106 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
107 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
108 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
109 /// instructions or a simple subregister reference. Idx is an index in the
110 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
111 /// lowering EXTRACT_VECTOR_ELT operations easier.
112 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
113                                    SelectionDAG &DAG, SDLoc dl) {
114   assert((Vec.getValueType().is256BitVector() ||
115           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
117 }
118
119 /// Generate a DAG to grab 256-bits from a 512-bit vector.
120 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
121                                    SelectionDAG &DAG, SDLoc dl) {
122   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
124 }
125
126 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
127                                unsigned IdxVal, SelectionDAG &DAG,
128                                SDLoc dl, unsigned vectorWidth) {
129   assert((vectorWidth == 128 || vectorWidth == 256) &&
130          "Unsupported vector width");
131   // Inserting UNDEF is Result
132   if (Vec.getOpcode() == ISD::UNDEF)
133     return Result;
134   EVT VT = Vec.getValueType();
135   EVT ElVT = VT.getVectorElementType();
136   EVT ResultVT = Result.getValueType();
137
138   // Insert the relevant vectorWidth bits.
139   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
140
141   // This is the index of the first element of the vectorWidth-bit chunk
142   // we want.
143   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
144                                * ElemsPerChunk);
145
146   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
147   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
148                      VecIdx);
149 }
150 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
151 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
152 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
153 /// simple superregister reference.  Idx is an index in the 128 bits
154 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
155 /// lowering INSERT_VECTOR_ELT operations easier.
156 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
161 }
162
163 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
168 }
169
170 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
171 /// instructions. This is used because creating CONCAT_VECTOR nodes of
172 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
173 /// large BUILD_VECTORS.
174 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
189   if (TT.isOSBinFormatMachO()) {
190     if (TT.getArch() == Triple::x86_64)
191       return new X86_64MachoTargetObjectFile();
192     return new TargetLoweringObjectFileMachO();
193   }
194
195   if (TT.isOSLinux())
196     return new X86LinuxTargetObjectFile();
197   if (TT.isOSBinFormatELF())
198     return new TargetLoweringObjectFileELF();
199   if (TT.isKnownWindowsMSVCEnvironment())
200     return new X86WindowsTargetObjectFile();
201   if (TT.isOSBinFormatCOFF())
202     return new TargetLoweringObjectFileCOFF();
203   llvm_unreachable("unknown subtarget type");
204 }
205
206 // FIXME: This should stop caching the target machine as soon as
207 // we can remove resetOperationActions et al.
208 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
209   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
210   Subtarget = &TM.getSubtarget<X86Subtarget>();
211   X86ScalarSSEf64 = Subtarget->hasSSE2();
212   X86ScalarSSEf32 = Subtarget->hasSSE1();
213   TD = getDataLayout();
214
215   resetOperationActions();
216 }
217
218 void X86TargetLowering::resetOperationActions() {
219   const TargetMachine &TM = getTargetMachine();
220   static bool FirstTimeThrough = true;
221
222   // If none of the target options have changed, then we don't need to reset the
223   // operation actions.
224   if (!FirstTimeThrough && TO == TM.Options) return;
225
226   if (!FirstTimeThrough) {
227     // Reinitialize the actions.
228     initActions();
229     FirstTimeThrough = false;
230   }
231
232   TO = TM.Options;
233
234   // Set up the TargetLowering object.
235   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
236
237   // X86 is weird, it always uses i8 for shift amounts and setcc results.
238   setBooleanContents(ZeroOrOneBooleanContent);
239   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
240   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
241
242   // For 64-bit since we have so many registers use the ILP scheduler, for
243   // 32-bit code use the register pressure specific scheduling.
244   // For Atom, always use ILP scheduling.
245   if (Subtarget->isAtom())
246     setSchedulingPreference(Sched::ILP);
247   else if (Subtarget->is64Bit())
248     setSchedulingPreference(Sched::ILP);
249   else
250     setSchedulingPreference(Sched::RegPressure);
251   const X86RegisterInfo *RegInfo =
252     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
253   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
254
255   // Bypass expensive divides on Atom when compiling with O2
256   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
257     addBypassSlowDiv(32, 8);
258     if (Subtarget->is64Bit())
259       addBypassSlowDiv(64, 16);
260   }
261
262   if (Subtarget->isTargetKnownWindowsMSVC()) {
263     // Setup Windows compiler runtime calls.
264     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
265     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
266     setLibcallName(RTLIB::SREM_I64, "_allrem");
267     setLibcallName(RTLIB::UREM_I64, "_aullrem");
268     setLibcallName(RTLIB::MUL_I64, "_allmul");
269     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
270     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
271     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
272     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
273     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
274
275     // The _ftol2 runtime function has an unusual calling conv, which
276     // is modeled by a special pseudo-instruction.
277     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
278     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
279     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
280     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
281   }
282
283   if (Subtarget->isTargetDarwin()) {
284     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
285     setUseUnderscoreSetJmp(false);
286     setUseUnderscoreLongJmp(false);
287   } else if (Subtarget->isTargetWindowsGNU()) {
288     // MS runtime is weird: it exports _setjmp, but longjmp!
289     setUseUnderscoreSetJmp(true);
290     setUseUnderscoreLongJmp(false);
291   } else {
292     setUseUnderscoreSetJmp(true);
293     setUseUnderscoreLongJmp(true);
294   }
295
296   // Set up the register classes.
297   addRegisterClass(MVT::i8, &X86::GR8RegClass);
298   addRegisterClass(MVT::i16, &X86::GR16RegClass);
299   addRegisterClass(MVT::i32, &X86::GR32RegClass);
300   if (Subtarget->is64Bit())
301     addRegisterClass(MVT::i64, &X86::GR64RegClass);
302
303   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
304
305   // We don't accept any truncstore of integer registers.
306   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
307   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
308   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
309   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
310   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
311   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
312
313   // SETOEQ and SETUNE require checking two conditions.
314   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
315   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
316   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
317   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
318   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
319   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
320
321   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
322   // operation.
323   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
324   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
325   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
326
327   if (Subtarget->is64Bit()) {
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
329     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
330   } else if (!TM.Options.UseSoftFloat) {
331     // We have an algorithm for SSE2->double, and we turn this into a
332     // 64-bit FILD followed by conditional FADD for other targets.
333     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
334     // We have an algorithm for SSE2, and we turn this into a 64-bit
335     // FILD for other targets.
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
337   }
338
339   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
340   // this operation.
341   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
342   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
343
344   if (!TM.Options.UseSoftFloat) {
345     // SSE has no i16 to fp conversion, only i32
346     if (X86ScalarSSEf32) {
347       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348       // f32 and f64 cases are Legal, f80 case is not
349       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
350     } else {
351       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
352       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
353     }
354   } else {
355     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
356     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
357   }
358
359   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
360   // are Legal, f80 is custom lowered.
361   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
362   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
363
364   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
365   // this operation.
366   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
367   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
368
369   if (X86ScalarSSEf32) {
370     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
371     // f32 and f64 cases are Legal, f80 case is not
372     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
373   } else {
374     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
375     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
376   }
377
378   // Handle FP_TO_UINT by promoting the destination to a larger signed
379   // conversion.
380   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
381   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
382   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
383
384   if (Subtarget->is64Bit()) {
385     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
386     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
387   } else if (!TM.Options.UseSoftFloat) {
388     // Since AVX is a superset of SSE3, only check for SSE here.
389     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
390       // Expand FP_TO_UINT into a select.
391       // FIXME: We would like to use a Custom expander here eventually to do
392       // the optimal thing for SSE vs. the default expansion in the legalizer.
393       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
394     else
395       // With SSE3 we can use fisttpll to convert to a signed i64; without
396       // SSE, we're stuck with a fistpll.
397       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
398   }
399
400   if (isTargetFTOL()) {
401     // Use the _ftol2 runtime function, which has a pseudo-instruction
402     // to handle its weird calling convention.
403     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
404   }
405
406   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
407   if (!X86ScalarSSEf64) {
408     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
409     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
410     if (Subtarget->is64Bit()) {
411       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
412       // Without SSE, i64->f64 goes through memory.
413       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
414     }
415   }
416
417   // Scalar integer divide and remainder are lowered to use operations that
418   // produce two results, to match the available instructions. This exposes
419   // the two-result form to trivial CSE, which is able to combine x/y and x%y
420   // into a single instruction.
421   //
422   // Scalar integer multiply-high is also lowered to use two-result
423   // operations, to match the available instructions. However, plain multiply
424   // (low) operations are left as Legal, as there are single-result
425   // instructions for this in x86. Using the two-result multiply instructions
426   // when both high and low results are needed must be arranged by dagcombine.
427   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
428     MVT VT = IntVTs[i];
429     setOperationAction(ISD::MULHS, VT, Expand);
430     setOperationAction(ISD::MULHU, VT, Expand);
431     setOperationAction(ISD::SDIV, VT, Expand);
432     setOperationAction(ISD::UDIV, VT, Expand);
433     setOperationAction(ISD::SREM, VT, Expand);
434     setOperationAction(ISD::UREM, VT, Expand);
435
436     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
437     setOperationAction(ISD::ADDC, VT, Custom);
438     setOperationAction(ISD::ADDE, VT, Custom);
439     setOperationAction(ISD::SUBC, VT, Custom);
440     setOperationAction(ISD::SUBE, VT, Custom);
441   }
442
443   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
444   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
445   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
446   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
447   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
448   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
449   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
450   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
451   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
453   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
454   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
455   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
456   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
457   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
462   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
463   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
464   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
465   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
466   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
467   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
468   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
469
470   // Promote the i8 variants and force them on up to i32 which has a shorter
471   // encoding.
472   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
473   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
474   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
475   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
476   if (Subtarget->hasBMI()) {
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
479     if (Subtarget->is64Bit())
480       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
481   } else {
482     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
483     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
484     if (Subtarget->is64Bit())
485       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
486   }
487
488   if (Subtarget->hasLZCNT()) {
489     // When promoting the i8 variants, force them to i32 for a shorter
490     // encoding.
491     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
492     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
494     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
495     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
497     if (Subtarget->is64Bit())
498       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
499   } else {
500     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
501     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
502     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
504     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
505     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
506     if (Subtarget->is64Bit()) {
507       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
508       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
509     }
510   }
511
512   if (Subtarget->hasPOPCNT()) {
513     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
514   } else {
515     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
516     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
517     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
518     if (Subtarget->is64Bit())
519       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
520   }
521
522   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
523
524   if (!Subtarget->hasMOVBE())
525     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
526
527   // These should be promoted to a larger select which is supported.
528   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
529   // X86 wants to expand cmov itself.
530   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
531   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
532   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
533   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
534   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
535   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
536   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
537   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
538   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
539   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
540   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
541   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
544     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
545   }
546   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
547   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
548   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
549   // support continuation, user-level threading, and etc.. As a result, no
550   // other SjLj exception interfaces are implemented and please don't build
551   // your own exception handling based on them.
552   // LLVM/Clang supports zero-cost DWARF exception handling.
553   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
554   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
555
556   // Darwin ABI issue.
557   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
558   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
559   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
560   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
561   if (Subtarget->is64Bit())
562     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
563   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
564   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
567     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
568     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
569     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
570     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
571   }
572   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
573   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
574   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
575   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
576   if (Subtarget->is64Bit()) {
577     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
578     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
579     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
580   }
581
582   if (Subtarget->hasSSE1())
583     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
584
585   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
586
587   // Expand certain atomics
588   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
589     MVT VT = IntVTs[i];
590     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
592     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
593   }
594
595   if (!Subtarget->is64Bit()) {
596     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
597     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
598     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
599     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
600     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
601     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
602     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
603     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
606     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
607     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
608   }
609
610   if (Subtarget->hasCmpxchg16b()) {
611     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
612   }
613
614   // FIXME - use subtarget debug flags
615   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
616       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
617     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
618   }
619
620   if (Subtarget->is64Bit()) {
621     setExceptionPointerRegister(X86::RAX);
622     setExceptionSelectorRegister(X86::RDX);
623   } else {
624     setExceptionPointerRegister(X86::EAX);
625     setExceptionSelectorRegister(X86::EDX);
626   }
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
628   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
629
630   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
631   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
632
633   setOperationAction(ISD::TRAP, MVT::Other, Legal);
634   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
635
636   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
637   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
638   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
639   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
640     // TargetInfo::X86_64ABIBuiltinVaList
641     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
642     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
643   } else {
644     // TargetInfo::CharPtrBuiltinVaList
645     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
646     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
647   }
648
649   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
650   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
651
652   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
653                      MVT::i64 : MVT::i32, Custom);
654
655   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
656     // f32 and f64 use SSE.
657     // Set up the FP register classes.
658     addRegisterClass(MVT::f32, &X86::FR32RegClass);
659     addRegisterClass(MVT::f64, &X86::FR64RegClass);
660
661     // Use ANDPD to simulate FABS.
662     setOperationAction(ISD::FABS , MVT::f64, Custom);
663     setOperationAction(ISD::FABS , MVT::f32, Custom);
664
665     // Use XORP to simulate FNEG.
666     setOperationAction(ISD::FNEG , MVT::f64, Custom);
667     setOperationAction(ISD::FNEG , MVT::f32, Custom);
668
669     // Use ANDPD and ORPD to simulate FCOPYSIGN.
670     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
672
673     // Lower this to FGETSIGNx86 plus an AND.
674     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
675     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
676
677     // We don't support sin/cos/fmod
678     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
681     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
683     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
684
685     // Expand FP immediates into loads from the stack, except for the special
686     // cases we handle.
687     addLegalFPImmediate(APFloat(+0.0)); // xorpd
688     addLegalFPImmediate(APFloat(+0.0f)); // xorps
689   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
690     // Use SSE for f32, x87 for f64.
691     // Set up the FP register classes.
692     addRegisterClass(MVT::f32, &X86::FR32RegClass);
693     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
694
695     // Use ANDPS to simulate FABS.
696     setOperationAction(ISD::FABS , MVT::f32, Custom);
697
698     // Use XORP to simulate FNEG.
699     setOperationAction(ISD::FNEG , MVT::f32, Custom);
700
701     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
702
703     // Use ANDPS and ORPS to simulate FCOPYSIGN.
704     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
706
707     // We don't support sin/cos/fmod
708     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
709     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
710     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
711
712     // Special cases we handle for FP constants.
713     addLegalFPImmediate(APFloat(+0.0f)); // xorps
714     addLegalFPImmediate(APFloat(+0.0)); // FLD0
715     addLegalFPImmediate(APFloat(+1.0)); // FLD1
716     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
717     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
718
719     if (!TM.Options.UnsafeFPMath) {
720       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
721       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
722       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
723     }
724   } else if (!TM.Options.UseSoftFloat) {
725     // f32 and f64 in x87.
726     // Set up the FP register classes.
727     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
728     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
729
730     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
731     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
734
735     if (!TM.Options.UnsafeFPMath) {
736       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
737       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
739       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
741       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
742     }
743     addLegalFPImmediate(APFloat(+0.0)); // FLD0
744     addLegalFPImmediate(APFloat(+1.0)); // FLD1
745     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
746     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
747     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
748     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
749     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
750     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
751   }
752
753   // We don't support FMA.
754   setOperationAction(ISD::FMA, MVT::f64, Expand);
755   setOperationAction(ISD::FMA, MVT::f32, Expand);
756
757   // Long double always uses X87.
758   if (!TM.Options.UseSoftFloat) {
759     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
760     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
761     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
762     {
763       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
764       addLegalFPImmediate(TmpFlt);  // FLD0
765       TmpFlt.changeSign();
766       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
767
768       bool ignored;
769       APFloat TmpFlt2(+1.0);
770       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
771                       &ignored);
772       addLegalFPImmediate(TmpFlt2);  // FLD1
773       TmpFlt2.changeSign();
774       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
775     }
776
777     if (!TM.Options.UnsafeFPMath) {
778       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
779       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
780       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
781     }
782
783     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
784     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
785     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
786     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
787     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
788     setOperationAction(ISD::FMA, MVT::f80, Expand);
789   }
790
791   // Always use a library call for pow.
792   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
794   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
795
796   setOperationAction(ISD::FLOG, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
798   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP, MVT::f80, Expand);
800   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
801
802   // First set operation action for all vector types to either promote
803   // (for widening) or expand (for scalarization). Then we will selectively
804   // turn on ones that can be effectively codegen'd.
805   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
806            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
807     MVT VT = (MVT::SimpleValueType)i;
808     setOperationAction(ISD::ADD , VT, Expand);
809     setOperationAction(ISD::SUB , VT, Expand);
810     setOperationAction(ISD::FADD, VT, Expand);
811     setOperationAction(ISD::FNEG, VT, Expand);
812     setOperationAction(ISD::FSUB, VT, Expand);
813     setOperationAction(ISD::MUL , VT, Expand);
814     setOperationAction(ISD::FMUL, VT, Expand);
815     setOperationAction(ISD::SDIV, VT, Expand);
816     setOperationAction(ISD::UDIV, VT, Expand);
817     setOperationAction(ISD::FDIV, VT, Expand);
818     setOperationAction(ISD::SREM, VT, Expand);
819     setOperationAction(ISD::UREM, VT, Expand);
820     setOperationAction(ISD::LOAD, VT, Expand);
821     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
822     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
823     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
824     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
826     setOperationAction(ISD::FABS, VT, Expand);
827     setOperationAction(ISD::FSIN, VT, Expand);
828     setOperationAction(ISD::FSINCOS, VT, Expand);
829     setOperationAction(ISD::FCOS, VT, Expand);
830     setOperationAction(ISD::FSINCOS, VT, Expand);
831     setOperationAction(ISD::FREM, VT, Expand);
832     setOperationAction(ISD::FMA,  VT, Expand);
833     setOperationAction(ISD::FPOWI, VT, Expand);
834     setOperationAction(ISD::FSQRT, VT, Expand);
835     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
836     setOperationAction(ISD::FFLOOR, VT, Expand);
837     setOperationAction(ISD::FCEIL, VT, Expand);
838     setOperationAction(ISD::FTRUNC, VT, Expand);
839     setOperationAction(ISD::FRINT, VT, Expand);
840     setOperationAction(ISD::FNEARBYINT, VT, Expand);
841     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
842     setOperationAction(ISD::MULHS, VT, Expand);
843     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
844     setOperationAction(ISD::MULHU, VT, Expand);
845     setOperationAction(ISD::SDIVREM, VT, Expand);
846     setOperationAction(ISD::UDIVREM, VT, Expand);
847     setOperationAction(ISD::FPOW, VT, Expand);
848     setOperationAction(ISD::CTPOP, VT, Expand);
849     setOperationAction(ISD::CTTZ, VT, Expand);
850     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
851     setOperationAction(ISD::CTLZ, VT, Expand);
852     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
853     setOperationAction(ISD::SHL, VT, Expand);
854     setOperationAction(ISD::SRA, VT, Expand);
855     setOperationAction(ISD::SRL, VT, Expand);
856     setOperationAction(ISD::ROTL, VT, Expand);
857     setOperationAction(ISD::ROTR, VT, Expand);
858     setOperationAction(ISD::BSWAP, VT, Expand);
859     setOperationAction(ISD::SETCC, VT, Expand);
860     setOperationAction(ISD::FLOG, VT, Expand);
861     setOperationAction(ISD::FLOG2, VT, Expand);
862     setOperationAction(ISD::FLOG10, VT, Expand);
863     setOperationAction(ISD::FEXP, VT, Expand);
864     setOperationAction(ISD::FEXP2, VT, Expand);
865     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
866     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
867     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
869     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
870     setOperationAction(ISD::TRUNCATE, VT, Expand);
871     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
872     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
873     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
874     setOperationAction(ISD::VSELECT, VT, Expand);
875     setOperationAction(ISD::SELECT_CC, VT, Expand);
876     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
877              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
878       setTruncStoreAction(VT,
879                           (MVT::SimpleValueType)InnerVT, Expand);
880     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
881     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
882     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
883   }
884
885   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886   // with -msoft-float, disable use of MMX as well.
887   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889     // No operations on x86mmx supported, everything uses intrinsics.
890   }
891
892   // MMX-sized vectors (other than x86mmx) are expected to be expanded
893   // into smaller operations.
894   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
895   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
897   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
898   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
900   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
901   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
902   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
903   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
904   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
905   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
906   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
907   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
908   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
909   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
913   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
914   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
915   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
916   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
918   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
922   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
923
924   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
926
927     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
931     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
932     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
933     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
934     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
935     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
936     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
939   }
940
941   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
942     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
943
944     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
945     // registers cannot be used even for integer operations.
946     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
947     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
948     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
949     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
950
951     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
952     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
953     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
954     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
955     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
956     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
957     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
958     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
959     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
960     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
961     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
962     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
963     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
964     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
965     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
966     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
972     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
973
974     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
975     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
977     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
978
979     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
980     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
984
985     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
986     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
987       MVT VT = (MVT::SimpleValueType)i;
988       // Do not attempt to custom lower non-power-of-2 vectors
989       if (!isPowerOf2_32(VT.getVectorNumElements()))
990         continue;
991       // Do not attempt to custom lower non-128-bit vectors
992       if (!VT.is128BitVector())
993         continue;
994       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
995       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
997     }
998
999     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1000     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1001     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1002     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1003     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1005
1006     if (Subtarget->is64Bit()) {
1007       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1008       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009     }
1010
1011     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1012     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1013       MVT VT = (MVT::SimpleValueType)i;
1014
1015       // Do not attempt to promote non-128-bit vectors
1016       if (!VT.is128BitVector())
1017         continue;
1018
1019       setOperationAction(ISD::AND,    VT, Promote);
1020       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1021       setOperationAction(ISD::OR,     VT, Promote);
1022       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1023       setOperationAction(ISD::XOR,    VT, Promote);
1024       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1025       setOperationAction(ISD::LOAD,   VT, Promote);
1026       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1027       setOperationAction(ISD::SELECT, VT, Promote);
1028       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1029     }
1030
1031     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1032
1033     // Custom lower v2i64 and v2f64 selects.
1034     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1035     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1036     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1037     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1038
1039     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1040     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1041
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1043     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1044     // As there is no 64-bit GPR available, we need build a special custom
1045     // sequence to convert from v2i32 to v2f32.
1046     if (!Subtarget->is64Bit())
1047       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1048
1049     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1050     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1051
1052     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1053
1054     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1055     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1056     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1057   }
1058
1059   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1060     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1061     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1062     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1063     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1064     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1068     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1070
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1076     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1077     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1078     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1079     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1080     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1081
1082     // FIXME: Do we need to handle scalar-to-vector here?
1083     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1084
1085     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1086     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1087     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1088     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1089     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1090     // There is no BLENDI for byte vectors. We don't need to custom lower
1091     // some vselects for now.
1092     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1093
1094     // i8 and i16 vectors are custom , because the source register and source
1095     // source memory operand types are not the same width.  f32 vectors are
1096     // custom since the immediate controlling the insert encodes additional
1097     // information.
1098     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1099     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1101     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1102
1103     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1104     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1105     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1106     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1107
1108     // FIXME: these should be Legal but thats only for the case where
1109     // the index is constant.  For now custom expand to deal with that.
1110     if (Subtarget->is64Bit()) {
1111       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1112       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1113     }
1114   }
1115
1116   if (Subtarget->hasSSE2()) {
1117     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1118     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1119
1120     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1121     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1122
1123     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1124     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1125
1126     // In the customized shift lowering, the legal cases in AVX2 will be
1127     // recognized.
1128     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1129     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1130
1131     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1132     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1133
1134     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1135   }
1136
1137   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1138     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1139     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1140     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1141     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1142     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1143     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1144
1145     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1148
1149     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1151     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1152     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1153     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1154     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1155     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1156     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1157     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1158     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1159     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1160     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1161
1162     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1163     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1164     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1165     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1166     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1167     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1168     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1169     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1170     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1171     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1172     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1173     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1174
1175     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1176     // even though v8i16 is a legal type.
1177     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1178     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1179     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1180
1181     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1182     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1183     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1184
1185     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1186     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1187
1188     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1189
1190     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1191     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1192
1193     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1194     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1195
1196     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1197     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1198
1199     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1200     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1201     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1202     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1203
1204     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1205     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1206     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1207
1208     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1209     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1210     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1211     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1212
1213     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1214     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1215     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1216     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1218     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1219     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1220     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1221     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1222     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1223     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1224     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1225
1226     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1227       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1228       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1229       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1230       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1231       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1232       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1233     }
1234
1235     if (Subtarget->hasInt256()) {
1236       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1237       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1238       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1239       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1240
1241       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1242       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1243       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1244       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1245
1246       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1248       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1249       // Don't lower v32i8 because there is no 128-bit byte mul
1250
1251       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1252       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1253       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1254       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1255
1256       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1257       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1258     } else {
1259       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1260       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1261       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1262       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1263
1264       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1265       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1266       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1267       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1268
1269       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1271       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1272       // Don't lower v32i8 because there is no 128-bit byte mul
1273     }
1274
1275     // In the customized shift lowering, the legal cases in AVX2 will be
1276     // recognized.
1277     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1278     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1279
1280     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1281     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1282
1283     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1284
1285     // Custom lower several nodes for 256-bit types.
1286     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1287              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1288       MVT VT = (MVT::SimpleValueType)i;
1289
1290       // Extract subvector is special because the value type
1291       // (result) is 128-bit but the source is 256-bit wide.
1292       if (VT.is128BitVector())
1293         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1294
1295       // Do not attempt to custom lower other non-256-bit vectors
1296       if (!VT.is256BitVector())
1297         continue;
1298
1299       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1300       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1301       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1302       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1303       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1304       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1305       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1306     }
1307
1308     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1309     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1310       MVT VT = (MVT::SimpleValueType)i;
1311
1312       // Do not attempt to promote non-256-bit vectors
1313       if (!VT.is256BitVector())
1314         continue;
1315
1316       setOperationAction(ISD::AND,    VT, Promote);
1317       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1318       setOperationAction(ISD::OR,     VT, Promote);
1319       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1320       setOperationAction(ISD::XOR,    VT, Promote);
1321       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1322       setOperationAction(ISD::LOAD,   VT, Promote);
1323       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1324       setOperationAction(ISD::SELECT, VT, Promote);
1325       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1326     }
1327   }
1328
1329   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1330     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1331     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1332     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1333     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1334
1335     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1336     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1337     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1338
1339     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1340     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1341     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1342     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1343     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1344     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1350
1351     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1365     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1366
1367     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1368     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1369     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1371     if (Subtarget->is64Bit()) {
1372       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1373       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1376     }
1377     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1379     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1380     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1381     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1384     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1385     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1386     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1387
1388     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1391     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1392     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1393     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1394     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1395     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1396     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1397     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1398     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1399     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1400     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1401
1402     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1403     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1404     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1405     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1407     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1408
1409     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1410     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1411
1412     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1413
1414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1415     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1416     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1417     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1418     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1419     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1420     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1421     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1422     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1423
1424     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1425     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1426
1427     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1428     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1429
1430     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1431
1432     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1433     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1434
1435     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1436     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1437
1438     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1439     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1440
1441     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1442     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1443     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1444     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1445     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1446     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1447
1448     if (Subtarget->hasCDI()) {
1449       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1450       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1451     }
1452
1453     // Custom lower several nodes.
1454     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1455              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1456       MVT VT = (MVT::SimpleValueType)i;
1457
1458       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1459       // Extract subvector is special because the value type
1460       // (result) is 256/128-bit but the source is 512-bit wide.
1461       if (VT.is128BitVector() || VT.is256BitVector())
1462         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1463
1464       if (VT.getVectorElementType() == MVT::i1)
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1466
1467       // Do not attempt to custom lower other non-512-bit vectors
1468       if (!VT.is512BitVector())
1469         continue;
1470
1471       if ( EltSize >= 32) {
1472         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1473         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1474         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1475         setOperationAction(ISD::VSELECT,             VT, Legal);
1476         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1477         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1478         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1479       }
1480     }
1481     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1482       MVT VT = (MVT::SimpleValueType)i;
1483
1484       // Do not attempt to promote non-256-bit vectors
1485       if (!VT.is512BitVector())
1486         continue;
1487
1488       setOperationAction(ISD::SELECT, VT, Promote);
1489       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1490     }
1491   }// has  AVX-512
1492
1493   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1494   // of this type with custom code.
1495   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1496            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1497     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1498                        Custom);
1499   }
1500
1501   // We want to custom lower some of our intrinsics.
1502   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505   if (!Subtarget->is64Bit())
1506     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1507
1508   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509   // handle type legalization for these operations here.
1510   //
1511   // FIXME: We really should do custom legalization for addition and
1512   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1513   // than generic legalization for 64-bit multiplication-with-overflow, though.
1514   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515     // Add/Sub/Mul with overflow operations are custom lowered.
1516     MVT VT = IntVTs[i];
1517     setOperationAction(ISD::SADDO, VT, Custom);
1518     setOperationAction(ISD::UADDO, VT, Custom);
1519     setOperationAction(ISD::SSUBO, VT, Custom);
1520     setOperationAction(ISD::USUBO, VT, Custom);
1521     setOperationAction(ISD::SMULO, VT, Custom);
1522     setOperationAction(ISD::UMULO, VT, Custom);
1523   }
1524
1525   // There are no 8-bit 3-address imul/mul instructions
1526   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1527   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1528
1529   if (!Subtarget->is64Bit()) {
1530     // These libcalls are not available in 32-bit.
1531     setLibcallName(RTLIB::SHL_I128, nullptr);
1532     setLibcallName(RTLIB::SRL_I128, nullptr);
1533     setLibcallName(RTLIB::SRA_I128, nullptr);
1534   }
1535
1536   // Combine sin / cos into one node or libcall if possible.
1537   if (Subtarget->hasSinCos()) {
1538     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1539     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1540     if (Subtarget->isTargetDarwin()) {
1541       // For MacOSX, we don't want to the normal expansion of a libcall to
1542       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1543       // traffic.
1544       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1545       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1546     }
1547   }
1548
1549   if (Subtarget->isTargetWin64()) {
1550     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1551     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1552     setOperationAction(ISD::SREM, MVT::i128, Custom);
1553     setOperationAction(ISD::UREM, MVT::i128, Custom);
1554     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1555     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1556   }
1557
1558   // We have target-specific dag combine patterns for the following nodes:
1559   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1560   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1561   setTargetDAGCombine(ISD::VSELECT);
1562   setTargetDAGCombine(ISD::SELECT);
1563   setTargetDAGCombine(ISD::SHL);
1564   setTargetDAGCombine(ISD::SRA);
1565   setTargetDAGCombine(ISD::SRL);
1566   setTargetDAGCombine(ISD::OR);
1567   setTargetDAGCombine(ISD::AND);
1568   setTargetDAGCombine(ISD::ADD);
1569   setTargetDAGCombine(ISD::FADD);
1570   setTargetDAGCombine(ISD::FSUB);
1571   setTargetDAGCombine(ISD::FMA);
1572   setTargetDAGCombine(ISD::SUB);
1573   setTargetDAGCombine(ISD::LOAD);
1574   setTargetDAGCombine(ISD::STORE);
1575   setTargetDAGCombine(ISD::ZERO_EXTEND);
1576   setTargetDAGCombine(ISD::ANY_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND);
1578   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1579   setTargetDAGCombine(ISD::TRUNCATE);
1580   setTargetDAGCombine(ISD::SINT_TO_FP);
1581   setTargetDAGCombine(ISD::SETCC);
1582   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1583   setTargetDAGCombine(ISD::BUILD_VECTOR);
1584   if (Subtarget->is64Bit())
1585     setTargetDAGCombine(ISD::MUL);
1586   setTargetDAGCombine(ISD::XOR);
1587
1588   computeRegisterProperties();
1589
1590   // On Darwin, -Os means optimize for size without hurting performance,
1591   // do not reduce the limit.
1592   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1593   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1594   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1595   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1597   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1598   setPrefLoopAlignment(4); // 2^4 bytes.
1599
1600   // Predictable cmov don't hurt on atom because it's in-order.
1601   PredictableSelectIsExpensive = !Subtarget->isAtom();
1602
1603   setPrefFunctionAlignment(4); // 2^4 bytes.
1604 }
1605
1606 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1607   if (!VT.isVector())
1608     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1609
1610   if (Subtarget->hasAVX512())
1611     switch(VT.getVectorNumElements()) {
1612     case  8: return MVT::v8i1;
1613     case 16: return MVT::v16i1;
1614   }
1615
1616   return VT.changeVectorElementTypeToInteger();
1617 }
1618
1619 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1620 /// the desired ByVal argument alignment.
1621 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1622   if (MaxAlign == 16)
1623     return;
1624   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1625     if (VTy->getBitWidth() == 128)
1626       MaxAlign = 16;
1627   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1628     unsigned EltAlign = 0;
1629     getMaxByValAlign(ATy->getElementType(), EltAlign);
1630     if (EltAlign > MaxAlign)
1631       MaxAlign = EltAlign;
1632   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1633     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1634       unsigned EltAlign = 0;
1635       getMaxByValAlign(STy->getElementType(i), EltAlign);
1636       if (EltAlign > MaxAlign)
1637         MaxAlign = EltAlign;
1638       if (MaxAlign == 16)
1639         break;
1640     }
1641   }
1642 }
1643
1644 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1645 /// function arguments in the caller parameter area. For X86, aggregates
1646 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1647 /// are at 4-byte boundaries.
1648 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1649   if (Subtarget->is64Bit()) {
1650     // Max of 8 and alignment of type.
1651     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1652     if (TyAlign > 8)
1653       return TyAlign;
1654     return 8;
1655   }
1656
1657   unsigned Align = 4;
1658   if (Subtarget->hasSSE1())
1659     getMaxByValAlign(Ty, Align);
1660   return Align;
1661 }
1662
1663 /// getOptimalMemOpType - Returns the target specific optimal type for load
1664 /// and store operations as a result of memset, memcpy, and memmove
1665 /// lowering. If DstAlign is zero that means it's safe to destination
1666 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1667 /// means there isn't a need to check it against alignment requirement,
1668 /// probably because the source does not need to be loaded. If 'IsMemset' is
1669 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1670 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1671 /// source is constant so it does not need to be loaded.
1672 /// It returns EVT::Other if the type should be determined using generic
1673 /// target-independent logic.
1674 EVT
1675 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1676                                        unsigned DstAlign, unsigned SrcAlign,
1677                                        bool IsMemset, bool ZeroMemset,
1678                                        bool MemcpyStrSrc,
1679                                        MachineFunction &MF) const {
1680   const Function *F = MF.getFunction();
1681   if ((!IsMemset || ZeroMemset) &&
1682       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1683                                        Attribute::NoImplicitFloat)) {
1684     if (Size >= 16 &&
1685         (Subtarget->isUnalignedMemAccessFast() ||
1686          ((DstAlign == 0 || DstAlign >= 16) &&
1687           (SrcAlign == 0 || SrcAlign >= 16)))) {
1688       if (Size >= 32) {
1689         if (Subtarget->hasInt256())
1690           return MVT::v8i32;
1691         if (Subtarget->hasFp256())
1692           return MVT::v8f32;
1693       }
1694       if (Subtarget->hasSSE2())
1695         return MVT::v4i32;
1696       if (Subtarget->hasSSE1())
1697         return MVT::v4f32;
1698     } else if (!MemcpyStrSrc && Size >= 8 &&
1699                !Subtarget->is64Bit() &&
1700                Subtarget->hasSSE2()) {
1701       // Do not use f64 to lower memcpy if source is string constant. It's
1702       // better to use i32 to avoid the loads.
1703       return MVT::f64;
1704     }
1705   }
1706   if (Subtarget->is64Bit() && Size >= 8)
1707     return MVT::i64;
1708   return MVT::i32;
1709 }
1710
1711 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1712   if (VT == MVT::f32)
1713     return X86ScalarSSEf32;
1714   else if (VT == MVT::f64)
1715     return X86ScalarSSEf64;
1716   return true;
1717 }
1718
1719 bool
1720 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1721                                                  unsigned,
1722                                                  bool *Fast) const {
1723   if (Fast)
1724     *Fast = Subtarget->isUnalignedMemAccessFast();
1725   return true;
1726 }
1727
1728 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1729 /// current function.  The returned value is a member of the
1730 /// MachineJumpTableInfo::JTEntryKind enum.
1731 unsigned X86TargetLowering::getJumpTableEncoding() const {
1732   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1733   // symbol.
1734   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1735       Subtarget->isPICStyleGOT())
1736     return MachineJumpTableInfo::EK_Custom32;
1737
1738   // Otherwise, use the normal jump table encoding heuristics.
1739   return TargetLowering::getJumpTableEncoding();
1740 }
1741
1742 const MCExpr *
1743 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1744                                              const MachineBasicBlock *MBB,
1745                                              unsigned uid,MCContext &Ctx) const{
1746   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1747          Subtarget->isPICStyleGOT());
1748   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1749   // entries.
1750   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1751                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1752 }
1753
1754 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1755 /// jumptable.
1756 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1757                                                     SelectionDAG &DAG) const {
1758   if (!Subtarget->is64Bit())
1759     // This doesn't have SDLoc associated with it, but is not really the
1760     // same as a Register.
1761     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1762   return Table;
1763 }
1764
1765 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1766 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1767 /// MCExpr.
1768 const MCExpr *X86TargetLowering::
1769 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1770                              MCContext &Ctx) const {
1771   // X86-64 uses RIP relative addressing based on the jump table label.
1772   if (Subtarget->isPICStyleRIPRel())
1773     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1774
1775   // Otherwise, the reference is relative to the PIC base.
1776   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1777 }
1778
1779 // FIXME: Why this routine is here? Move to RegInfo!
1780 std::pair<const TargetRegisterClass*, uint8_t>
1781 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1782   const TargetRegisterClass *RRC = nullptr;
1783   uint8_t Cost = 1;
1784   switch (VT.SimpleTy) {
1785   default:
1786     return TargetLowering::findRepresentativeClass(VT);
1787   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1788     RRC = Subtarget->is64Bit() ?
1789       (const TargetRegisterClass*)&X86::GR64RegClass :
1790       (const TargetRegisterClass*)&X86::GR32RegClass;
1791     break;
1792   case MVT::x86mmx:
1793     RRC = &X86::VR64RegClass;
1794     break;
1795   case MVT::f32: case MVT::f64:
1796   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1797   case MVT::v4f32: case MVT::v2f64:
1798   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1799   case MVT::v4f64:
1800     RRC = &X86::VR128RegClass;
1801     break;
1802   }
1803   return std::make_pair(RRC, Cost);
1804 }
1805
1806 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1807                                                unsigned &Offset) const {
1808   if (!Subtarget->isTargetLinux())
1809     return false;
1810
1811   if (Subtarget->is64Bit()) {
1812     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1813     Offset = 0x28;
1814     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1815       AddressSpace = 256;
1816     else
1817       AddressSpace = 257;
1818   } else {
1819     // %gs:0x14 on i386
1820     Offset = 0x14;
1821     AddressSpace = 256;
1822   }
1823   return true;
1824 }
1825
1826 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1827                                             unsigned DestAS) const {
1828   assert(SrcAS != DestAS && "Expected different address spaces!");
1829
1830   return SrcAS < 256 && DestAS < 256;
1831 }
1832
1833 //===----------------------------------------------------------------------===//
1834 //               Return Value Calling Convention Implementation
1835 //===----------------------------------------------------------------------===//
1836
1837 #include "X86GenCallingConv.inc"
1838
1839 bool
1840 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1841                                   MachineFunction &MF, bool isVarArg,
1842                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1843                         LLVMContext &Context) const {
1844   SmallVector<CCValAssign, 16> RVLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1846                  RVLocs, Context);
1847   return CCInfo.CheckReturn(Outs, RetCC_X86);
1848 }
1849
1850 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1851   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1852   return ScratchRegs;
1853 }
1854
1855 SDValue
1856 X86TargetLowering::LowerReturn(SDValue Chain,
1857                                CallingConv::ID CallConv, bool isVarArg,
1858                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1859                                const SmallVectorImpl<SDValue> &OutVals,
1860                                SDLoc dl, SelectionDAG &DAG) const {
1861   MachineFunction &MF = DAG.getMachineFunction();
1862   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1863
1864   SmallVector<CCValAssign, 16> RVLocs;
1865   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1866                  RVLocs, *DAG.getContext());
1867   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1868
1869   SDValue Flag;
1870   SmallVector<SDValue, 6> RetOps;
1871   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1872   // Operand #1 = Bytes To Pop
1873   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1874                    MVT::i16));
1875
1876   // Copy the result values into the output registers.
1877   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1878     CCValAssign &VA = RVLocs[i];
1879     assert(VA.isRegLoc() && "Can only return in registers!");
1880     SDValue ValToCopy = OutVals[i];
1881     EVT ValVT = ValToCopy.getValueType();
1882
1883     // Promote values to the appropriate types
1884     if (VA.getLocInfo() == CCValAssign::SExt)
1885       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1886     else if (VA.getLocInfo() == CCValAssign::ZExt)
1887       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1888     else if (VA.getLocInfo() == CCValAssign::AExt)
1889       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1890     else if (VA.getLocInfo() == CCValAssign::BCvt)
1891       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1892
1893     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1894            "Unexpected FP-extend for return value.");  
1895
1896     // If this is x86-64, and we disabled SSE, we can't return FP values,
1897     // or SSE or MMX vectors.
1898     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1899          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1900           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1901       report_fatal_error("SSE register return with SSE disabled");
1902     }
1903     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1904     // llvm-gcc has never done it right and no one has noticed, so this
1905     // should be OK for now.
1906     if (ValVT == MVT::f64 &&
1907         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1908       report_fatal_error("SSE2 register return with SSE2 disabled");
1909
1910     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1911     // the RET instruction and handled by the FP Stackifier.
1912     if (VA.getLocReg() == X86::ST0 ||
1913         VA.getLocReg() == X86::ST1) {
1914       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1915       // change the value to the FP stack register class.
1916       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1917         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1918       RetOps.push_back(ValToCopy);
1919       // Don't emit a copytoreg.
1920       continue;
1921     }
1922
1923     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1924     // which is returned in RAX / RDX.
1925     if (Subtarget->is64Bit()) {
1926       if (ValVT == MVT::x86mmx) {
1927         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1928           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1929           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1930                                   ValToCopy);
1931           // If we don't have SSE2 available, convert to v4f32 so the generated
1932           // register is legal.
1933           if (!Subtarget->hasSSE2())
1934             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1935         }
1936       }
1937     }
1938
1939     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1940     Flag = Chain.getValue(1);
1941     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1942   }
1943
1944   // The x86-64 ABIs require that for returning structs by value we copy
1945   // the sret argument into %rax/%eax (depending on ABI) for the return.
1946   // Win32 requires us to put the sret argument to %eax as well.
1947   // We saved the argument into a virtual register in the entry block,
1948   // so now we copy the value out and into %rax/%eax.
1949   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1950       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1951     MachineFunction &MF = DAG.getMachineFunction();
1952     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953     unsigned Reg = FuncInfo->getSRetReturnReg();
1954     assert(Reg &&
1955            "SRetReturnReg should have been set in LowerFormalArguments().");
1956     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1957
1958     unsigned RetValReg
1959         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1960           X86::RAX : X86::EAX;
1961     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1962     Flag = Chain.getValue(1);
1963
1964     // RAX/EAX now acts like a return value.
1965     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1966   }
1967
1968   RetOps[0] = Chain;  // Update chain.
1969
1970   // Add the flag if we have it.
1971   if (Flag.getNode())
1972     RetOps.push_back(Flag);
1973
1974   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1975 }
1976
1977 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1978   if (N->getNumValues() != 1)
1979     return false;
1980   if (!N->hasNUsesOfValue(1, 0))
1981     return false;
1982
1983   SDValue TCChain = Chain;
1984   SDNode *Copy = *N->use_begin();
1985   if (Copy->getOpcode() == ISD::CopyToReg) {
1986     // If the copy has a glue operand, we conservatively assume it isn't safe to
1987     // perform a tail call.
1988     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1989       return false;
1990     TCChain = Copy->getOperand(0);
1991   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1992     return false;
1993
1994   bool HasRet = false;
1995   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1996        UI != UE; ++UI) {
1997     if (UI->getOpcode() != X86ISD::RET_FLAG)
1998       return false;
1999     HasRet = true;
2000   }
2001
2002   if (!HasRet)
2003     return false;
2004
2005   Chain = TCChain;
2006   return true;
2007 }
2008
2009 MVT
2010 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2011                                             ISD::NodeType ExtendKind) const {
2012   MVT ReturnMVT;
2013   // TODO: Is this also valid on 32-bit?
2014   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2015     ReturnMVT = MVT::i8;
2016   else
2017     ReturnMVT = MVT::i32;
2018
2019   MVT MinVT = getRegisterType(ReturnMVT);
2020   return VT.bitsLT(MinVT) ? MinVT : VT;
2021 }
2022
2023 /// LowerCallResult - Lower the result values of a call into the
2024 /// appropriate copies out of appropriate physical registers.
2025 ///
2026 SDValue
2027 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2028                                    CallingConv::ID CallConv, bool isVarArg,
2029                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2030                                    SDLoc dl, SelectionDAG &DAG,
2031                                    SmallVectorImpl<SDValue> &InVals) const {
2032
2033   // Assign locations to each value returned by this call.
2034   SmallVector<CCValAssign, 16> RVLocs;
2035   bool Is64Bit = Subtarget->is64Bit();
2036   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2037                  DAG.getTarget(), RVLocs, *DAG.getContext());
2038   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2039
2040   // Copy all of the result registers out of their specified physreg.
2041   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2042     CCValAssign &VA = RVLocs[i];
2043     EVT CopyVT = VA.getValVT();
2044
2045     // If this is x86-64, and we disabled SSE, we can't return FP values
2046     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2047         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2048       report_fatal_error("SSE register return with SSE disabled");
2049     }
2050
2051     SDValue Val;
2052
2053     // If this is a call to a function that returns an fp value on the floating
2054     // point stack, we must guarantee the value is popped from the stack, so
2055     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2056     // if the return value is not used. We use the FpPOP_RETVAL instruction
2057     // instead.
2058     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2059       // If we prefer to use the value in xmm registers, copy it out as f80 and
2060       // use a truncate to move it from fp stack reg to xmm reg.
2061       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2062       SDValue Ops[] = { Chain, InFlag };
2063       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2064                                          MVT::Other, MVT::Glue, Ops), 1);
2065       Val = Chain.getValue(0);
2066
2067       // Round the f80 to the right size, which also moves it to the appropriate
2068       // xmm register.
2069       if (CopyVT != VA.getValVT())
2070         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2071                           // This truncation won't change the value.
2072                           DAG.getIntPtrConstant(1));
2073     } else {
2074       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2075                                  CopyVT, InFlag).getValue(1);
2076       Val = Chain.getValue(0);
2077     }
2078     InFlag = Chain.getValue(2);
2079     InVals.push_back(Val);
2080   }
2081
2082   return Chain;
2083 }
2084
2085 //===----------------------------------------------------------------------===//
2086 //                C & StdCall & Fast Calling Convention implementation
2087 //===----------------------------------------------------------------------===//
2088 //  StdCall calling convention seems to be standard for many Windows' API
2089 //  routines and around. It differs from C calling convention just a little:
2090 //  callee should clean up the stack, not caller. Symbols should be also
2091 //  decorated in some fancy way :) It doesn't support any vector arguments.
2092 //  For info on fast calling convention see Fast Calling Convention (tail call)
2093 //  implementation LowerX86_32FastCCCallTo.
2094
2095 /// CallIsStructReturn - Determines whether a call uses struct return
2096 /// semantics.
2097 enum StructReturnType {
2098   NotStructReturn,
2099   RegStructReturn,
2100   StackStructReturn
2101 };
2102 static StructReturnType
2103 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2104   if (Outs.empty())
2105     return NotStructReturn;
2106
2107   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2108   if (!Flags.isSRet())
2109     return NotStructReturn;
2110   if (Flags.isInReg())
2111     return RegStructReturn;
2112   return StackStructReturn;
2113 }
2114
2115 /// ArgsAreStructReturn - Determines whether a function uses struct
2116 /// return semantics.
2117 static StructReturnType
2118 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2119   if (Ins.empty())
2120     return NotStructReturn;
2121
2122   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2123   if (!Flags.isSRet())
2124     return NotStructReturn;
2125   if (Flags.isInReg())
2126     return RegStructReturn;
2127   return StackStructReturn;
2128 }
2129
2130 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2131 /// by "Src" to address "Dst" with size and alignment information specified by
2132 /// the specific parameter attribute. The copy will be passed as a byval
2133 /// function parameter.
2134 static SDValue
2135 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2136                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2137                           SDLoc dl) {
2138   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2139
2140   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2141                        /*isVolatile*/false, /*AlwaysInline=*/true,
2142                        MachinePointerInfo(), MachinePointerInfo());
2143 }
2144
2145 /// IsTailCallConvention - Return true if the calling convention is one that
2146 /// supports tail call optimization.
2147 static bool IsTailCallConvention(CallingConv::ID CC) {
2148   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2149           CC == CallingConv::HiPE);
2150 }
2151
2152 /// \brief Return true if the calling convention is a C calling convention.
2153 static bool IsCCallConvention(CallingConv::ID CC) {
2154   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2155           CC == CallingConv::X86_64_SysV);
2156 }
2157
2158 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2159   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2160     return false;
2161
2162   CallSite CS(CI);
2163   CallingConv::ID CalleeCC = CS.getCallingConv();
2164   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2165     return false;
2166
2167   return true;
2168 }
2169
2170 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2171 /// a tailcall target by changing its ABI.
2172 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2173                                    bool GuaranteedTailCallOpt) {
2174   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2175 }
2176
2177 SDValue
2178 X86TargetLowering::LowerMemArgument(SDValue Chain,
2179                                     CallingConv::ID CallConv,
2180                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2181                                     SDLoc dl, SelectionDAG &DAG,
2182                                     const CCValAssign &VA,
2183                                     MachineFrameInfo *MFI,
2184                                     unsigned i) const {
2185   // Create the nodes corresponding to a load from this parameter slot.
2186   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2187   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2188       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2189   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2190   EVT ValVT;
2191
2192   // If value is passed by pointer we have address passed instead of the value
2193   // itself.
2194   if (VA.getLocInfo() == CCValAssign::Indirect)
2195     ValVT = VA.getLocVT();
2196   else
2197     ValVT = VA.getValVT();
2198
2199   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2200   // changed with more analysis.
2201   // In case of tail call optimization mark all arguments mutable. Since they
2202   // could be overwritten by lowering of arguments in case of a tail call.
2203   if (Flags.isByVal()) {
2204     unsigned Bytes = Flags.getByValSize();
2205     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2206     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2207     return DAG.getFrameIndex(FI, getPointerTy());
2208   } else {
2209     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2210                                     VA.getLocMemOffset(), isImmutable);
2211     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2212     return DAG.getLoad(ValVT, dl, Chain, FIN,
2213                        MachinePointerInfo::getFixedStack(FI),
2214                        false, false, false, 0);
2215   }
2216 }
2217
2218 SDValue
2219 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2220                                         CallingConv::ID CallConv,
2221                                         bool isVarArg,
2222                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2223                                         SDLoc dl,
2224                                         SelectionDAG &DAG,
2225                                         SmallVectorImpl<SDValue> &InVals)
2226                                           const {
2227   MachineFunction &MF = DAG.getMachineFunction();
2228   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2229
2230   const Function* Fn = MF.getFunction();
2231   if (Fn->hasExternalLinkage() &&
2232       Subtarget->isTargetCygMing() &&
2233       Fn->getName() == "main")
2234     FuncInfo->setForceFramePointer(true);
2235
2236   MachineFrameInfo *MFI = MF.getFrameInfo();
2237   bool Is64Bit = Subtarget->is64Bit();
2238   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2239
2240   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2241          "Var args not supported with calling convention fastcc, ghc or hipe");
2242
2243   // Assign locations to all of the incoming arguments.
2244   SmallVector<CCValAssign, 16> ArgLocs;
2245   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2246                  ArgLocs, *DAG.getContext());
2247
2248   // Allocate shadow area for Win64
2249   if (IsWin64)
2250     CCInfo.AllocateStack(32, 8);
2251
2252   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2253
2254   unsigned LastVal = ~0U;
2255   SDValue ArgValue;
2256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257     CCValAssign &VA = ArgLocs[i];
2258     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2259     // places.
2260     assert(VA.getValNo() != LastVal &&
2261            "Don't support value assigned to multiple locs yet");
2262     (void)LastVal;
2263     LastVal = VA.getValNo();
2264
2265     if (VA.isRegLoc()) {
2266       EVT RegVT = VA.getLocVT();
2267       const TargetRegisterClass *RC;
2268       if (RegVT == MVT::i32)
2269         RC = &X86::GR32RegClass;
2270       else if (Is64Bit && RegVT == MVT::i64)
2271         RC = &X86::GR64RegClass;
2272       else if (RegVT == MVT::f32)
2273         RC = &X86::FR32RegClass;
2274       else if (RegVT == MVT::f64)
2275         RC = &X86::FR64RegClass;
2276       else if (RegVT.is512BitVector())
2277         RC = &X86::VR512RegClass;
2278       else if (RegVT.is256BitVector())
2279         RC = &X86::VR256RegClass;
2280       else if (RegVT.is128BitVector())
2281         RC = &X86::VR128RegClass;
2282       else if (RegVT == MVT::x86mmx)
2283         RC = &X86::VR64RegClass;
2284       else if (RegVT == MVT::i1)
2285         RC = &X86::VK1RegClass;
2286       else if (RegVT == MVT::v8i1)
2287         RC = &X86::VK8RegClass;
2288       else if (RegVT == MVT::v16i1)
2289         RC = &X86::VK16RegClass;
2290       else
2291         llvm_unreachable("Unknown argument type!");
2292
2293       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2294       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2295
2296       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2297       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2298       // right size.
2299       if (VA.getLocInfo() == CCValAssign::SExt)
2300         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2301                                DAG.getValueType(VA.getValVT()));
2302       else if (VA.getLocInfo() == CCValAssign::ZExt)
2303         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2304                                DAG.getValueType(VA.getValVT()));
2305       else if (VA.getLocInfo() == CCValAssign::BCvt)
2306         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2307
2308       if (VA.isExtInLoc()) {
2309         // Handle MMX values passed in XMM regs.
2310         if (RegVT.isVector())
2311           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2312         else
2313           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2314       }
2315     } else {
2316       assert(VA.isMemLoc());
2317       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2318     }
2319
2320     // If value is passed via pointer - do a load.
2321     if (VA.getLocInfo() == CCValAssign::Indirect)
2322       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2323                              MachinePointerInfo(), false, false, false, 0);
2324
2325     InVals.push_back(ArgValue);
2326   }
2327
2328   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2329     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330       // The x86-64 ABIs require that for returning structs by value we copy
2331       // the sret argument into %rax/%eax (depending on ABI) for the return.
2332       // Win32 requires us to put the sret argument to %eax as well.
2333       // Save the argument into a virtual register so that we can access it
2334       // from the return points.
2335       if (Ins[i].Flags.isSRet()) {
2336         unsigned Reg = FuncInfo->getSRetReturnReg();
2337         if (!Reg) {
2338           MVT PtrTy = getPointerTy();
2339           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2340           FuncInfo->setSRetReturnReg(Reg);
2341         }
2342         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2343         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2344         break;
2345       }
2346     }
2347   }
2348
2349   unsigned StackSize = CCInfo.getNextStackOffset();
2350   // Align stack specially for tail calls.
2351   if (FuncIsMadeTailCallSafe(CallConv,
2352                              MF.getTarget().Options.GuaranteedTailCallOpt))
2353     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2354
2355   // If the function takes variable number of arguments, make a frame index for
2356   // the start of the first vararg value... for expansion of llvm.va_start.
2357   if (isVarArg) {
2358     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2359                     CallConv != CallingConv::X86_ThisCall)) {
2360       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2361     }
2362     if (Is64Bit) {
2363       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2364
2365       // FIXME: We should really autogenerate these arrays
2366       static const MCPhysReg GPR64ArgRegsWin64[] = {
2367         X86::RCX, X86::RDX, X86::R8,  X86::R9
2368       };
2369       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2370         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2371       };
2372       static const MCPhysReg XMMArgRegs64Bit[] = {
2373         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2374         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2375       };
2376       const MCPhysReg *GPR64ArgRegs;
2377       unsigned NumXMMRegs = 0;
2378
2379       if (IsWin64) {
2380         // The XMM registers which might contain var arg parameters are shadowed
2381         // in their paired GPR.  So we only need to save the GPR to their home
2382         // slots.
2383         TotalNumIntRegs = 4;
2384         GPR64ArgRegs = GPR64ArgRegsWin64;
2385       } else {
2386         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2387         GPR64ArgRegs = GPR64ArgRegs64Bit;
2388
2389         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2390                                                 TotalNumXMMRegs);
2391       }
2392       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2393                                                        TotalNumIntRegs);
2394
2395       bool NoImplicitFloatOps = Fn->getAttributes().
2396         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2397       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2398              "SSE register cannot be used when SSE is disabled!");
2399       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2400                NoImplicitFloatOps) &&
2401              "SSE register cannot be used when SSE is disabled!");
2402       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403           !Subtarget->hasSSE1())
2404         // Kernel mode asks for SSE to be disabled, so don't push them
2405         // on the stack.
2406         TotalNumXMMRegs = 0;
2407
2408       if (IsWin64) {
2409         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2410         // Get to the caller-allocated home save location.  Add 8 to account
2411         // for the return address.
2412         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2413         FuncInfo->setRegSaveFrameIndex(
2414           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2415         // Fixup to set vararg frame on shadow area (4 x i64).
2416         if (NumIntRegs < 4)
2417           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2418       } else {
2419         // For X86-64, if there are vararg parameters that are passed via
2420         // registers, then we must store them to their spots on the stack so
2421         // they may be loaded by deferencing the result of va_next.
2422         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2423         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2424         FuncInfo->setRegSaveFrameIndex(
2425           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2426                                false));
2427       }
2428
2429       // Store the integer parameter registers.
2430       SmallVector<SDValue, 8> MemOps;
2431       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2432                                         getPointerTy());
2433       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2434       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2435         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2436                                   DAG.getIntPtrConstant(Offset));
2437         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2438                                      &X86::GR64RegClass);
2439         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2440         SDValue Store =
2441           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2442                        MachinePointerInfo::getFixedStack(
2443                          FuncInfo->getRegSaveFrameIndex(), Offset),
2444                        false, false, 0);
2445         MemOps.push_back(Store);
2446         Offset += 8;
2447       }
2448
2449       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2450         // Now store the XMM (fp + vector) parameter registers.
2451         SmallVector<SDValue, 11> SaveXMMOps;
2452         SaveXMMOps.push_back(Chain);
2453
2454         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2455         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2456         SaveXMMOps.push_back(ALVal);
2457
2458         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2459                                FuncInfo->getRegSaveFrameIndex()));
2460         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2461                                FuncInfo->getVarArgsFPOffset()));
2462
2463         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2464           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2465                                        &X86::VR128RegClass);
2466           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2467           SaveXMMOps.push_back(Val);
2468         }
2469         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2470                                      MVT::Other, SaveXMMOps));
2471       }
2472
2473       if (!MemOps.empty())
2474         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2475     }
2476   }
2477
2478   // Some CCs need callee pop.
2479   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2480                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2481     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2482   } else {
2483     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2484     // If this is an sret function, the return should pop the hidden pointer.
2485     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2486         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2487         argsAreStructReturn(Ins) == StackStructReturn)
2488       FuncInfo->setBytesToPopOnReturn(4);
2489   }
2490
2491   if (!Is64Bit) {
2492     // RegSaveFrameIndex is X86-64 only.
2493     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2494     if (CallConv == CallingConv::X86_FastCall ||
2495         CallConv == CallingConv::X86_ThisCall)
2496       // fastcc functions can't have varargs.
2497       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2498   }
2499
2500   FuncInfo->setArgumentStackSize(StackSize);
2501
2502   return Chain;
2503 }
2504
2505 SDValue
2506 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2507                                     SDValue StackPtr, SDValue Arg,
2508                                     SDLoc dl, SelectionDAG &DAG,
2509                                     const CCValAssign &VA,
2510                                     ISD::ArgFlagsTy Flags) const {
2511   unsigned LocMemOffset = VA.getLocMemOffset();
2512   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2513   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2514   if (Flags.isByVal())
2515     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2516
2517   return DAG.getStore(Chain, dl, Arg, PtrOff,
2518                       MachinePointerInfo::getStack(LocMemOffset),
2519                       false, false, 0);
2520 }
2521
2522 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2523 /// optimization is performed and it is required.
2524 SDValue
2525 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2526                                            SDValue &OutRetAddr, SDValue Chain,
2527                                            bool IsTailCall, bool Is64Bit,
2528                                            int FPDiff, SDLoc dl) const {
2529   // Adjust the Return address stack slot.
2530   EVT VT = getPointerTy();
2531   OutRetAddr = getReturnAddressFrameIndex(DAG);
2532
2533   // Load the "old" Return address.
2534   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2535                            false, false, false, 0);
2536   return SDValue(OutRetAddr.getNode(), 1);
2537 }
2538
2539 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2540 /// optimization is performed and it is required (FPDiff!=0).
2541 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2542                                         SDValue Chain, SDValue RetAddrFrIdx,
2543                                         EVT PtrVT, unsigned SlotSize,
2544                                         int FPDiff, SDLoc dl) {
2545   // Store the return address to the appropriate stack slot.
2546   if (!FPDiff) return Chain;
2547   // Calculate the new stack slot for the return address.
2548   int NewReturnAddrFI =
2549     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2550                                          false);
2551   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2552   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2553                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2554                        false, false, 0);
2555   return Chain;
2556 }
2557
2558 SDValue
2559 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2560                              SmallVectorImpl<SDValue> &InVals) const {
2561   SelectionDAG &DAG                     = CLI.DAG;
2562   SDLoc &dl                             = CLI.DL;
2563   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2564   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2565   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2566   SDValue Chain                         = CLI.Chain;
2567   SDValue Callee                        = CLI.Callee;
2568   CallingConv::ID CallConv              = CLI.CallConv;
2569   bool &isTailCall                      = CLI.IsTailCall;
2570   bool isVarArg                         = CLI.IsVarArg;
2571
2572   MachineFunction &MF = DAG.getMachineFunction();
2573   bool Is64Bit        = Subtarget->is64Bit();
2574   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2575   StructReturnType SR = callIsStructReturn(Outs);
2576   bool IsSibcall      = false;
2577
2578   if (MF.getTarget().Options.DisableTailCalls)
2579     isTailCall = false;
2580
2581   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2582   if (IsMustTail) {
2583     // Force this to be a tail call.  The verifier rules are enough to ensure
2584     // that we can lower this successfully without moving the return address
2585     // around.
2586     isTailCall = true;
2587   } else if (isTailCall) {
2588     // Check if it's really possible to do a tail call.
2589     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2590                     isVarArg, SR != NotStructReturn,
2591                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2592                     Outs, OutVals, Ins, DAG);
2593
2594     // Sibcalls are automatically detected tailcalls which do not require
2595     // ABI changes.
2596     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2597       IsSibcall = true;
2598
2599     if (isTailCall)
2600       ++NumTailCalls;
2601   }
2602
2603   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2604          "Var args not supported with calling convention fastcc, ghc or hipe");
2605
2606   // Analyze operands of the call, assigning locations to each operand.
2607   SmallVector<CCValAssign, 16> ArgLocs;
2608   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2609                  ArgLocs, *DAG.getContext());
2610
2611   // Allocate shadow area for Win64
2612   if (IsWin64)
2613     CCInfo.AllocateStack(32, 8);
2614
2615   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2616
2617   // Get a count of how many bytes are to be pushed on the stack.
2618   unsigned NumBytes = CCInfo.getNextStackOffset();
2619   if (IsSibcall)
2620     // This is a sibcall. The memory operands are available in caller's
2621     // own caller's stack.
2622     NumBytes = 0;
2623   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2624            IsTailCallConvention(CallConv))
2625     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2626
2627   int FPDiff = 0;
2628   if (isTailCall && !IsSibcall && !IsMustTail) {
2629     // Lower arguments at fp - stackoffset + fpdiff.
2630     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2631     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2632
2633     FPDiff = NumBytesCallerPushed - NumBytes;
2634
2635     // Set the delta of movement of the returnaddr stackslot.
2636     // But only set if delta is greater than previous delta.
2637     if (FPDiff < X86Info->getTCReturnAddrDelta())
2638       X86Info->setTCReturnAddrDelta(FPDiff);
2639   }
2640
2641   unsigned NumBytesToPush = NumBytes;
2642   unsigned NumBytesToPop = NumBytes;
2643
2644   // If we have an inalloca argument, all stack space has already been allocated
2645   // for us and be right at the top of the stack.  We don't support multiple
2646   // arguments passed in memory when using inalloca.
2647   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2648     NumBytesToPush = 0;
2649     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2650            "an inalloca argument must be the only memory argument");
2651   }
2652
2653   if (!IsSibcall)
2654     Chain = DAG.getCALLSEQ_START(
2655         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2656
2657   SDValue RetAddrFrIdx;
2658   // Load return address for tail calls.
2659   if (isTailCall && FPDiff)
2660     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2661                                     Is64Bit, FPDiff, dl);
2662
2663   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2664   SmallVector<SDValue, 8> MemOpChains;
2665   SDValue StackPtr;
2666
2667   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2668   // of tail call optimization arguments are handle later.
2669   const X86RegisterInfo *RegInfo =
2670     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2671   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2672     // Skip inalloca arguments, they have already been written.
2673     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2674     if (Flags.isInAlloca())
2675       continue;
2676
2677     CCValAssign &VA = ArgLocs[i];
2678     EVT RegVT = VA.getLocVT();
2679     SDValue Arg = OutVals[i];
2680     bool isByVal = Flags.isByVal();
2681
2682     // Promote the value if needed.
2683     switch (VA.getLocInfo()) {
2684     default: llvm_unreachable("Unknown loc info!");
2685     case CCValAssign::Full: break;
2686     case CCValAssign::SExt:
2687       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2688       break;
2689     case CCValAssign::ZExt:
2690       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2691       break;
2692     case CCValAssign::AExt:
2693       if (RegVT.is128BitVector()) {
2694         // Special case: passing MMX values in XMM registers.
2695         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2696         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2697         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2698       } else
2699         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2700       break;
2701     case CCValAssign::BCvt:
2702       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2703       break;
2704     case CCValAssign::Indirect: {
2705       // Store the argument.
2706       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2707       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2708       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2709                            MachinePointerInfo::getFixedStack(FI),
2710                            false, false, 0);
2711       Arg = SpillSlot;
2712       break;
2713     }
2714     }
2715
2716     if (VA.isRegLoc()) {
2717       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2718       if (isVarArg && IsWin64) {
2719         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2720         // shadow reg if callee is a varargs function.
2721         unsigned ShadowReg = 0;
2722         switch (VA.getLocReg()) {
2723         case X86::XMM0: ShadowReg = X86::RCX; break;
2724         case X86::XMM1: ShadowReg = X86::RDX; break;
2725         case X86::XMM2: ShadowReg = X86::R8; break;
2726         case X86::XMM3: ShadowReg = X86::R9; break;
2727         }
2728         if (ShadowReg)
2729           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2730       }
2731     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2732       assert(VA.isMemLoc());
2733       if (!StackPtr.getNode())
2734         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2735                                       getPointerTy());
2736       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2737                                              dl, DAG, VA, Flags));
2738     }
2739   }
2740
2741   if (!MemOpChains.empty())
2742     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2743
2744   if (Subtarget->isPICStyleGOT()) {
2745     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2746     // GOT pointer.
2747     if (!isTailCall) {
2748       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2749                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2750     } else {
2751       // If we are tail calling and generating PIC/GOT style code load the
2752       // address of the callee into ECX. The value in ecx is used as target of
2753       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2754       // for tail calls on PIC/GOT architectures. Normally we would just put the
2755       // address of GOT into ebx and then call target@PLT. But for tail calls
2756       // ebx would be restored (since ebx is callee saved) before jumping to the
2757       // target@PLT.
2758
2759       // Note: The actual moving to ECX is done further down.
2760       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2761       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2762           !G->getGlobal()->hasProtectedVisibility())
2763         Callee = LowerGlobalAddress(Callee, DAG);
2764       else if (isa<ExternalSymbolSDNode>(Callee))
2765         Callee = LowerExternalSymbol(Callee, DAG);
2766     }
2767   }
2768
2769   if (Is64Bit && isVarArg && !IsWin64) {
2770     // From AMD64 ABI document:
2771     // For calls that may call functions that use varargs or stdargs
2772     // (prototype-less calls or calls to functions containing ellipsis (...) in
2773     // the declaration) %al is used as hidden argument to specify the number
2774     // of SSE registers used. The contents of %al do not need to match exactly
2775     // the number of registers, but must be an ubound on the number of SSE
2776     // registers used and is in the range 0 - 8 inclusive.
2777
2778     // Count the number of XMM registers allocated.
2779     static const MCPhysReg XMMArgRegs[] = {
2780       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2781       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2782     };
2783     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2784     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2785            && "SSE registers cannot be used when SSE is disabled");
2786
2787     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2788                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2789   }
2790
2791   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2792   // don't need this because the eligibility check rejects calls that require
2793   // shuffling arguments passed in memory.
2794   if (!IsSibcall && isTailCall) {
2795     // Force all the incoming stack arguments to be loaded from the stack
2796     // before any new outgoing arguments are stored to the stack, because the
2797     // outgoing stack slots may alias the incoming argument stack slots, and
2798     // the alias isn't otherwise explicit. This is slightly more conservative
2799     // than necessary, because it means that each store effectively depends
2800     // on every argument instead of just those arguments it would clobber.
2801     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2802
2803     SmallVector<SDValue, 8> MemOpChains2;
2804     SDValue FIN;
2805     int FI = 0;
2806     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2807       CCValAssign &VA = ArgLocs[i];
2808       if (VA.isRegLoc())
2809         continue;
2810       assert(VA.isMemLoc());
2811       SDValue Arg = OutVals[i];
2812       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2813       // Skip inalloca arguments.  They don't require any work.
2814       if (Flags.isInAlloca())
2815         continue;
2816       // Create frame index.
2817       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2818       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2819       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2820       FIN = DAG.getFrameIndex(FI, getPointerTy());
2821
2822       if (Flags.isByVal()) {
2823         // Copy relative to framepointer.
2824         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2825         if (!StackPtr.getNode())
2826           StackPtr = DAG.getCopyFromReg(Chain, dl,
2827                                         RegInfo->getStackRegister(),
2828                                         getPointerTy());
2829         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2830
2831         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2832                                                          ArgChain,
2833                                                          Flags, DAG, dl));
2834       } else {
2835         // Store relative to framepointer.
2836         MemOpChains2.push_back(
2837           DAG.getStore(ArgChain, dl, Arg, FIN,
2838                        MachinePointerInfo::getFixedStack(FI),
2839                        false, false, 0));
2840       }
2841     }
2842
2843     if (!MemOpChains2.empty())
2844       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2845
2846     // Store the return address to the appropriate stack slot.
2847     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2848                                      getPointerTy(), RegInfo->getSlotSize(),
2849                                      FPDiff, dl);
2850   }
2851
2852   // Build a sequence of copy-to-reg nodes chained together with token chain
2853   // and flag operands which copy the outgoing args into registers.
2854   SDValue InFlag;
2855   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2856     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2857                              RegsToPass[i].second, InFlag);
2858     InFlag = Chain.getValue(1);
2859   }
2860
2861   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2862     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2863     // In the 64-bit large code model, we have to make all calls
2864     // through a register, since the call instruction's 32-bit
2865     // pc-relative offset may not be large enough to hold the whole
2866     // address.
2867   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2868     // If the callee is a GlobalAddress node (quite common, every direct call
2869     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2870     // it.
2871
2872     // We should use extra load for direct calls to dllimported functions in
2873     // non-JIT mode.
2874     const GlobalValue *GV = G->getGlobal();
2875     if (!GV->hasDLLImportStorageClass()) {
2876       unsigned char OpFlags = 0;
2877       bool ExtraLoad = false;
2878       unsigned WrapperKind = ISD::DELETED_NODE;
2879
2880       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2881       // external symbols most go through the PLT in PIC mode.  If the symbol
2882       // has hidden or protected visibility, or if it is static or local, then
2883       // we don't need to use the PLT - we can directly call it.
2884       if (Subtarget->isTargetELF() &&
2885           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2886           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2887         OpFlags = X86II::MO_PLT;
2888       } else if (Subtarget->isPICStyleStubAny() &&
2889                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2890                  (!Subtarget->getTargetTriple().isMacOSX() ||
2891                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892         // PC-relative references to external symbols should go through $stub,
2893         // unless we're building with the leopard linker or later, which
2894         // automatically synthesizes these stubs.
2895         OpFlags = X86II::MO_DARWIN_STUB;
2896       } else if (Subtarget->isPICStyleRIPRel() &&
2897                  isa<Function>(GV) &&
2898                  cast<Function>(GV)->getAttributes().
2899                    hasAttribute(AttributeSet::FunctionIndex,
2900                                 Attribute::NonLazyBind)) {
2901         // If the function is marked as non-lazy, generate an indirect call
2902         // which loads from the GOT directly. This avoids runtime overhead
2903         // at the cost of eager binding (and one extra byte of encoding).
2904         OpFlags = X86II::MO_GOTPCREL;
2905         WrapperKind = X86ISD::WrapperRIP;
2906         ExtraLoad = true;
2907       }
2908
2909       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2910                                           G->getOffset(), OpFlags);
2911
2912       // Add a wrapper if needed.
2913       if (WrapperKind != ISD::DELETED_NODE)
2914         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2915       // Add extra indirection if needed.
2916       if (ExtraLoad)
2917         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2918                              MachinePointerInfo::getGOT(),
2919                              false, false, false, 0);
2920     }
2921   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2922     unsigned char OpFlags = 0;
2923
2924     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2925     // external symbols should go through the PLT.
2926     if (Subtarget->isTargetELF() &&
2927         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2928       OpFlags = X86II::MO_PLT;
2929     } else if (Subtarget->isPICStyleStubAny() &&
2930                (!Subtarget->getTargetTriple().isMacOSX() ||
2931                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2932       // PC-relative references to external symbols should go through $stub,
2933       // unless we're building with the leopard linker or later, which
2934       // automatically synthesizes these stubs.
2935       OpFlags = X86II::MO_DARWIN_STUB;
2936     }
2937
2938     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2939                                          OpFlags);
2940   }
2941
2942   // Returns a chain & a flag for retval copy to use.
2943   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2944   SmallVector<SDValue, 8> Ops;
2945
2946   if (!IsSibcall && isTailCall) {
2947     Chain = DAG.getCALLSEQ_END(Chain,
2948                                DAG.getIntPtrConstant(NumBytesToPop, true),
2949                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2950     InFlag = Chain.getValue(1);
2951   }
2952
2953   Ops.push_back(Chain);
2954   Ops.push_back(Callee);
2955
2956   if (isTailCall)
2957     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2958
2959   // Add argument registers to the end of the list so that they are known live
2960   // into the call.
2961   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2962     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2963                                   RegsToPass[i].second.getValueType()));
2964
2965   // Add a register mask operand representing the call-preserved registers.
2966   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2967   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2968   assert(Mask && "Missing call preserved mask for calling convention");
2969   Ops.push_back(DAG.getRegisterMask(Mask));
2970
2971   if (InFlag.getNode())
2972     Ops.push_back(InFlag);
2973
2974   if (isTailCall) {
2975     // We used to do:
2976     //// If this is the first return lowered for this function, add the regs
2977     //// to the liveout set for the function.
2978     // This isn't right, although it's probably harmless on x86; liveouts
2979     // should be computed from returns not tail calls.  Consider a void
2980     // function making a tail call to a function returning int.
2981     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2982   }
2983
2984   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2985   InFlag = Chain.getValue(1);
2986
2987   // Create the CALLSEQ_END node.
2988   unsigned NumBytesForCalleeToPop;
2989   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2990                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2991     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2992   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2993            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2994            SR == StackStructReturn)
2995     // If this is a call to a struct-return function, the callee
2996     // pops the hidden struct pointer, so we have to push it back.
2997     // This is common for Darwin/X86, Linux & Mingw32 targets.
2998     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2999     NumBytesForCalleeToPop = 4;
3000   else
3001     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3002
3003   // Returns a flag for retval copy to use.
3004   if (!IsSibcall) {
3005     Chain = DAG.getCALLSEQ_END(Chain,
3006                                DAG.getIntPtrConstant(NumBytesToPop, true),
3007                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3008                                                      true),
3009                                InFlag, dl);
3010     InFlag = Chain.getValue(1);
3011   }
3012
3013   // Handle result values, copying them out of physregs into vregs that we
3014   // return.
3015   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3016                          Ins, dl, DAG, InVals);
3017 }
3018
3019 //===----------------------------------------------------------------------===//
3020 //                Fast Calling Convention (tail call) implementation
3021 //===----------------------------------------------------------------------===//
3022
3023 //  Like std call, callee cleans arguments, convention except that ECX is
3024 //  reserved for storing the tail called function address. Only 2 registers are
3025 //  free for argument passing (inreg). Tail call optimization is performed
3026 //  provided:
3027 //                * tailcallopt is enabled
3028 //                * caller/callee are fastcc
3029 //  On X86_64 architecture with GOT-style position independent code only local
3030 //  (within module) calls are supported at the moment.
3031 //  To keep the stack aligned according to platform abi the function
3032 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3033 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3034 //  If a tail called function callee has more arguments than the caller the
3035 //  caller needs to make sure that there is room to move the RETADDR to. This is
3036 //  achieved by reserving an area the size of the argument delta right after the
3037 //  original REtADDR, but before the saved framepointer or the spilled registers
3038 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3039 //  stack layout:
3040 //    arg1
3041 //    arg2
3042 //    RETADDR
3043 //    [ new RETADDR
3044 //      move area ]
3045 //    (possible EBP)
3046 //    ESI
3047 //    EDI
3048 //    local1 ..
3049
3050 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3051 /// for a 16 byte align requirement.
3052 unsigned
3053 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3054                                                SelectionDAG& DAG) const {
3055   MachineFunction &MF = DAG.getMachineFunction();
3056   const TargetMachine &TM = MF.getTarget();
3057   const X86RegisterInfo *RegInfo =
3058     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3059   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3060   unsigned StackAlignment = TFI.getStackAlignment();
3061   uint64_t AlignMask = StackAlignment - 1;
3062   int64_t Offset = StackSize;
3063   unsigned SlotSize = RegInfo->getSlotSize();
3064   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3065     // Number smaller than 12 so just add the difference.
3066     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3067   } else {
3068     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3069     Offset = ((~AlignMask) & Offset) + StackAlignment +
3070       (StackAlignment-SlotSize);
3071   }
3072   return Offset;
3073 }
3074
3075 /// MatchingStackOffset - Return true if the given stack call argument is
3076 /// already available in the same position (relatively) of the caller's
3077 /// incoming argument stack.
3078 static
3079 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3080                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3081                          const X86InstrInfo *TII) {
3082   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3083   int FI = INT_MAX;
3084   if (Arg.getOpcode() == ISD::CopyFromReg) {
3085     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3086     if (!TargetRegisterInfo::isVirtualRegister(VR))
3087       return false;
3088     MachineInstr *Def = MRI->getVRegDef(VR);
3089     if (!Def)
3090       return false;
3091     if (!Flags.isByVal()) {
3092       if (!TII->isLoadFromStackSlot(Def, FI))
3093         return false;
3094     } else {
3095       unsigned Opcode = Def->getOpcode();
3096       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3097           Def->getOperand(1).isFI()) {
3098         FI = Def->getOperand(1).getIndex();
3099         Bytes = Flags.getByValSize();
3100       } else
3101         return false;
3102     }
3103   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3104     if (Flags.isByVal())
3105       // ByVal argument is passed in as a pointer but it's now being
3106       // dereferenced. e.g.
3107       // define @foo(%struct.X* %A) {
3108       //   tail call @bar(%struct.X* byval %A)
3109       // }
3110       return false;
3111     SDValue Ptr = Ld->getBasePtr();
3112     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3113     if (!FINode)
3114       return false;
3115     FI = FINode->getIndex();
3116   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3117     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3118     FI = FINode->getIndex();
3119     Bytes = Flags.getByValSize();
3120   } else
3121     return false;
3122
3123   assert(FI != INT_MAX);
3124   if (!MFI->isFixedObjectIndex(FI))
3125     return false;
3126   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3127 }
3128
3129 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3130 /// for tail call optimization. Targets which want to do tail call
3131 /// optimization should implement this function.
3132 bool
3133 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3134                                                      CallingConv::ID CalleeCC,
3135                                                      bool isVarArg,
3136                                                      bool isCalleeStructRet,
3137                                                      bool isCallerStructRet,
3138                                                      Type *RetTy,
3139                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3140                                     const SmallVectorImpl<SDValue> &OutVals,
3141                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3142                                                      SelectionDAG &DAG) const {
3143   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3144     return false;
3145
3146   // If -tailcallopt is specified, make fastcc functions tail-callable.
3147   const MachineFunction &MF = DAG.getMachineFunction();
3148   const Function *CallerF = MF.getFunction();
3149
3150   // If the function return type is x86_fp80 and the callee return type is not,
3151   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3152   // perform a tailcall optimization here.
3153   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3154     return false;
3155
3156   CallingConv::ID CallerCC = CallerF->getCallingConv();
3157   bool CCMatch = CallerCC == CalleeCC;
3158   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3159   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3160
3161   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3162     if (IsTailCallConvention(CalleeCC) && CCMatch)
3163       return true;
3164     return false;
3165   }
3166
3167   // Look for obvious safe cases to perform tail call optimization that do not
3168   // require ABI changes. This is what gcc calls sibcall.
3169
3170   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3171   // emit a special epilogue.
3172   const X86RegisterInfo *RegInfo =
3173     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3174   if (RegInfo->needsStackRealignment(MF))
3175     return false;
3176
3177   // Also avoid sibcall optimization if either caller or callee uses struct
3178   // return semantics.
3179   if (isCalleeStructRet || isCallerStructRet)
3180     return false;
3181
3182   // An stdcall/thiscall caller is expected to clean up its arguments; the
3183   // callee isn't going to do that.
3184   // FIXME: this is more restrictive than needed. We could produce a tailcall
3185   // when the stack adjustment matches. For example, with a thiscall that takes
3186   // only one argument.
3187   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3188                    CallerCC == CallingConv::X86_ThisCall))
3189     return false;
3190
3191   // Do not sibcall optimize vararg calls unless all arguments are passed via
3192   // registers.
3193   if (isVarArg && !Outs.empty()) {
3194
3195     // Optimizing for varargs on Win64 is unlikely to be safe without
3196     // additional testing.
3197     if (IsCalleeWin64 || IsCallerWin64)
3198       return false;
3199
3200     SmallVector<CCValAssign, 16> ArgLocs;
3201     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3202                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3203
3204     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3205     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3206       if (!ArgLocs[i].isRegLoc())
3207         return false;
3208   }
3209
3210   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3211   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3212   // this into a sibcall.
3213   bool Unused = false;
3214   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3215     if (!Ins[i].Used) {
3216       Unused = true;
3217       break;
3218     }
3219   }
3220   if (Unused) {
3221     SmallVector<CCValAssign, 16> RVLocs;
3222     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3223                    DAG.getTarget(), RVLocs, *DAG.getContext());
3224     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3225     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3226       CCValAssign &VA = RVLocs[i];
3227       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3228         return false;
3229     }
3230   }
3231
3232   // If the calling conventions do not match, then we'd better make sure the
3233   // results are returned in the same way as what the caller expects.
3234   if (!CCMatch) {
3235     SmallVector<CCValAssign, 16> RVLocs1;
3236     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3237                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3238     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3239
3240     SmallVector<CCValAssign, 16> RVLocs2;
3241     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3242                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3243     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3244
3245     if (RVLocs1.size() != RVLocs2.size())
3246       return false;
3247     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3248       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3249         return false;
3250       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3251         return false;
3252       if (RVLocs1[i].isRegLoc()) {
3253         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3254           return false;
3255       } else {
3256         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3257           return false;
3258       }
3259     }
3260   }
3261
3262   // If the callee takes no arguments then go on to check the results of the
3263   // call.
3264   if (!Outs.empty()) {
3265     // Check if stack adjustment is needed. For now, do not do this if any
3266     // argument is passed on the stack.
3267     SmallVector<CCValAssign, 16> ArgLocs;
3268     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3270
3271     // Allocate shadow area for Win64
3272     if (IsCalleeWin64)
3273       CCInfo.AllocateStack(32, 8);
3274
3275     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3276     if (CCInfo.getNextStackOffset()) {
3277       MachineFunction &MF = DAG.getMachineFunction();
3278       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3279         return false;
3280
3281       // Check if the arguments are already laid out in the right way as
3282       // the caller's fixed stack objects.
3283       MachineFrameInfo *MFI = MF.getFrameInfo();
3284       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3285       const X86InstrInfo *TII =
3286           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3287       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3288         CCValAssign &VA = ArgLocs[i];
3289         SDValue Arg = OutVals[i];
3290         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3291         if (VA.getLocInfo() == CCValAssign::Indirect)
3292           return false;
3293         if (!VA.isRegLoc()) {
3294           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3295                                    MFI, MRI, TII))
3296             return false;
3297         }
3298       }
3299     }
3300
3301     // If the tailcall address may be in a register, then make sure it's
3302     // possible to register allocate for it. In 32-bit, the call address can
3303     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3304     // callee-saved registers are restored. These happen to be the same
3305     // registers used to pass 'inreg' arguments so watch out for those.
3306     if (!Subtarget->is64Bit() &&
3307         ((!isa<GlobalAddressSDNode>(Callee) &&
3308           !isa<ExternalSymbolSDNode>(Callee)) ||
3309          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3310       unsigned NumInRegs = 0;
3311       // In PIC we need an extra register to formulate the address computation
3312       // for the callee.
3313       unsigned MaxInRegs =
3314         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3315
3316       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317         CCValAssign &VA = ArgLocs[i];
3318         if (!VA.isRegLoc())
3319           continue;
3320         unsigned Reg = VA.getLocReg();
3321         switch (Reg) {
3322         default: break;
3323         case X86::EAX: case X86::EDX: case X86::ECX:
3324           if (++NumInRegs == MaxInRegs)
3325             return false;
3326           break;
3327         }
3328       }
3329     }
3330   }
3331
3332   return true;
3333 }
3334
3335 FastISel *
3336 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3337                                   const TargetLibraryInfo *libInfo) const {
3338   return X86::createFastISel(funcInfo, libInfo);
3339 }
3340
3341 //===----------------------------------------------------------------------===//
3342 //                           Other Lowering Hooks
3343 //===----------------------------------------------------------------------===//
3344
3345 static bool MayFoldLoad(SDValue Op) {
3346   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3347 }
3348
3349 static bool MayFoldIntoStore(SDValue Op) {
3350   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3351 }
3352
3353 static bool isTargetShuffle(unsigned Opcode) {
3354   switch(Opcode) {
3355   default: return false;
3356   case X86ISD::PSHUFD:
3357   case X86ISD::PSHUFHW:
3358   case X86ISD::PSHUFLW:
3359   case X86ISD::SHUFP:
3360   case X86ISD::PALIGNR:
3361   case X86ISD::MOVLHPS:
3362   case X86ISD::MOVLHPD:
3363   case X86ISD::MOVHLPS:
3364   case X86ISD::MOVLPS:
3365   case X86ISD::MOVLPD:
3366   case X86ISD::MOVSHDUP:
3367   case X86ISD::MOVSLDUP:
3368   case X86ISD::MOVDDUP:
3369   case X86ISD::MOVSS:
3370   case X86ISD::MOVSD:
3371   case X86ISD::UNPCKL:
3372   case X86ISD::UNPCKH:
3373   case X86ISD::VPERMILP:
3374   case X86ISD::VPERM2X128:
3375   case X86ISD::VPERMI:
3376     return true;
3377   }
3378 }
3379
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381                                     SDValue V1, SelectionDAG &DAG) {
3382   switch(Opc) {
3383   default: llvm_unreachable("Unknown x86 shuffle node");
3384   case X86ISD::MOVSHDUP:
3385   case X86ISD::MOVSLDUP:
3386   case X86ISD::MOVDDUP:
3387     return DAG.getNode(Opc, dl, VT, V1);
3388   }
3389 }
3390
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392                                     SDValue V1, unsigned TargetMask,
3393                                     SelectionDAG &DAG) {
3394   switch(Opc) {
3395   default: llvm_unreachable("Unknown x86 shuffle node");
3396   case X86ISD::PSHUFD:
3397   case X86ISD::PSHUFHW:
3398   case X86ISD::PSHUFLW:
3399   case X86ISD::VPERMILP:
3400   case X86ISD::VPERMI:
3401     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3402   }
3403 }
3404
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406                                     SDValue V1, SDValue V2, unsigned TargetMask,
3407                                     SelectionDAG &DAG) {
3408   switch(Opc) {
3409   default: llvm_unreachable("Unknown x86 shuffle node");
3410   case X86ISD::PALIGNR:
3411   case X86ISD::SHUFP:
3412   case X86ISD::VPERM2X128:
3413     return DAG.getNode(Opc, dl, VT, V1, V2,
3414                        DAG.getConstant(TargetMask, MVT::i8));
3415   }
3416 }
3417
3418 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3419                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3420   switch(Opc) {
3421   default: llvm_unreachable("Unknown x86 shuffle node");
3422   case X86ISD::MOVLHPS:
3423   case X86ISD::MOVLHPD:
3424   case X86ISD::MOVHLPS:
3425   case X86ISD::MOVLPS:
3426   case X86ISD::MOVLPD:
3427   case X86ISD::MOVSS:
3428   case X86ISD::MOVSD:
3429   case X86ISD::UNPCKL:
3430   case X86ISD::UNPCKH:
3431     return DAG.getNode(Opc, dl, VT, V1, V2);
3432   }
3433 }
3434
3435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3436   MachineFunction &MF = DAG.getMachineFunction();
3437   const X86RegisterInfo *RegInfo =
3438     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3439   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3440   int ReturnAddrIndex = FuncInfo->getRAIndex();
3441
3442   if (ReturnAddrIndex == 0) {
3443     // Set up a frame object for the return address.
3444     unsigned SlotSize = RegInfo->getSlotSize();
3445     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3446                                                            -(int64_t)SlotSize,
3447                                                            false);
3448     FuncInfo->setRAIndex(ReturnAddrIndex);
3449   }
3450
3451   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3452 }
3453
3454 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3455                                        bool hasSymbolicDisplacement) {
3456   // Offset should fit into 32 bit immediate field.
3457   if (!isInt<32>(Offset))
3458     return false;
3459
3460   // If we don't have a symbolic displacement - we don't have any extra
3461   // restrictions.
3462   if (!hasSymbolicDisplacement)
3463     return true;
3464
3465   // FIXME: Some tweaks might be needed for medium code model.
3466   if (M != CodeModel::Small && M != CodeModel::Kernel)
3467     return false;
3468
3469   // For small code model we assume that latest object is 16MB before end of 31
3470   // bits boundary. We may also accept pretty large negative constants knowing
3471   // that all objects are in the positive half of address space.
3472   if (M == CodeModel::Small && Offset < 16*1024*1024)
3473     return true;
3474
3475   // For kernel code model we know that all object resist in the negative half
3476   // of 32bits address space. We may not accept negative offsets, since they may
3477   // be just off and we may accept pretty large positive ones.
3478   if (M == CodeModel::Kernel && Offset > 0)
3479     return true;
3480
3481   return false;
3482 }
3483
3484 /// isCalleePop - Determines whether the callee is required to pop its
3485 /// own arguments. Callee pop is necessary to support tail calls.
3486 bool X86::isCalleePop(CallingConv::ID CallingConv,
3487                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3488   if (IsVarArg)
3489     return false;
3490
3491   switch (CallingConv) {
3492   default:
3493     return false;
3494   case CallingConv::X86_StdCall:
3495     return !is64Bit;
3496   case CallingConv::X86_FastCall:
3497     return !is64Bit;
3498   case CallingConv::X86_ThisCall:
3499     return !is64Bit;
3500   case CallingConv::Fast:
3501     return TailCallOpt;
3502   case CallingConv::GHC:
3503     return TailCallOpt;
3504   case CallingConv::HiPE:
3505     return TailCallOpt;
3506   }
3507 }
3508
3509 /// \brief Return true if the condition is an unsigned comparison operation.
3510 static bool isX86CCUnsigned(unsigned X86CC) {
3511   switch (X86CC) {
3512   default: llvm_unreachable("Invalid integer condition!");
3513   case X86::COND_E:     return true;
3514   case X86::COND_G:     return false;
3515   case X86::COND_GE:    return false;
3516   case X86::COND_L:     return false;
3517   case X86::COND_LE:    return false;
3518   case X86::COND_NE:    return true;
3519   case X86::COND_B:     return true;
3520   case X86::COND_A:     return true;
3521   case X86::COND_BE:    return true;
3522   case X86::COND_AE:    return true;
3523   }
3524   llvm_unreachable("covered switch fell through?!");
3525 }
3526
3527 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3528 /// specific condition code, returning the condition code and the LHS/RHS of the
3529 /// comparison to make.
3530 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3531                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3532   if (!isFP) {
3533     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3534       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3535         // X > -1   -> X == 0, jump !sign.
3536         RHS = DAG.getConstant(0, RHS.getValueType());
3537         return X86::COND_NS;
3538       }
3539       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3540         // X < 0   -> X == 0, jump on sign.
3541         return X86::COND_S;
3542       }
3543       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3544         // X < 1   -> X <= 0
3545         RHS = DAG.getConstant(0, RHS.getValueType());
3546         return X86::COND_LE;
3547       }
3548     }
3549
3550     switch (SetCCOpcode) {
3551     default: llvm_unreachable("Invalid integer condition!");
3552     case ISD::SETEQ:  return X86::COND_E;
3553     case ISD::SETGT:  return X86::COND_G;
3554     case ISD::SETGE:  return X86::COND_GE;
3555     case ISD::SETLT:  return X86::COND_L;
3556     case ISD::SETLE:  return X86::COND_LE;
3557     case ISD::SETNE:  return X86::COND_NE;
3558     case ISD::SETULT: return X86::COND_B;
3559     case ISD::SETUGT: return X86::COND_A;
3560     case ISD::SETULE: return X86::COND_BE;
3561     case ISD::SETUGE: return X86::COND_AE;
3562     }
3563   }
3564
3565   // First determine if it is required or is profitable to flip the operands.
3566
3567   // If LHS is a foldable load, but RHS is not, flip the condition.
3568   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3569       !ISD::isNON_EXTLoad(RHS.getNode())) {
3570     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3571     std::swap(LHS, RHS);
3572   }
3573
3574   switch (SetCCOpcode) {
3575   default: break;
3576   case ISD::SETOLT:
3577   case ISD::SETOLE:
3578   case ISD::SETUGT:
3579   case ISD::SETUGE:
3580     std::swap(LHS, RHS);
3581     break;
3582   }
3583
3584   // On a floating point condition, the flags are set as follows:
3585   // ZF  PF  CF   op
3586   //  0 | 0 | 0 | X > Y
3587   //  0 | 0 | 1 | X < Y
3588   //  1 | 0 | 0 | X == Y
3589   //  1 | 1 | 1 | unordered
3590   switch (SetCCOpcode) {
3591   default: llvm_unreachable("Condcode should be pre-legalized away");
3592   case ISD::SETUEQ:
3593   case ISD::SETEQ:   return X86::COND_E;
3594   case ISD::SETOLT:              // flipped
3595   case ISD::SETOGT:
3596   case ISD::SETGT:   return X86::COND_A;
3597   case ISD::SETOLE:              // flipped
3598   case ISD::SETOGE:
3599   case ISD::SETGE:   return X86::COND_AE;
3600   case ISD::SETUGT:              // flipped
3601   case ISD::SETULT:
3602   case ISD::SETLT:   return X86::COND_B;
3603   case ISD::SETUGE:              // flipped
3604   case ISD::SETULE:
3605   case ISD::SETLE:   return X86::COND_BE;
3606   case ISD::SETONE:
3607   case ISD::SETNE:   return X86::COND_NE;
3608   case ISD::SETUO:   return X86::COND_P;
3609   case ISD::SETO:    return X86::COND_NP;
3610   case ISD::SETOEQ:
3611   case ISD::SETUNE:  return X86::COND_INVALID;
3612   }
3613 }
3614
3615 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3616 /// code. Current x86 isa includes the following FP cmov instructions:
3617 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3618 static bool hasFPCMov(unsigned X86CC) {
3619   switch (X86CC) {
3620   default:
3621     return false;
3622   case X86::COND_B:
3623   case X86::COND_BE:
3624   case X86::COND_E:
3625   case X86::COND_P:
3626   case X86::COND_A:
3627   case X86::COND_AE:
3628   case X86::COND_NE:
3629   case X86::COND_NP:
3630     return true;
3631   }
3632 }
3633
3634 /// isFPImmLegal - Returns true if the target can instruction select the
3635 /// specified FP immediate natively. If false, the legalizer will
3636 /// materialize the FP immediate as a load from a constant pool.
3637 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3638   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3639     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3640       return true;
3641   }
3642   return false;
3643 }
3644
3645 /// \brief Returns true if it is beneficial to convert a load of a constant
3646 /// to just the constant itself.
3647 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3648                                                           Type *Ty) const {
3649   assert(Ty->isIntegerTy());
3650
3651   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3652   if (BitSize == 0 || BitSize > 64)
3653     return false;
3654   return true;
3655 }
3656
3657 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3658 /// the specified range (L, H].
3659 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3660   return (Val < 0) || (Val >= Low && Val < Hi);
3661 }
3662
3663 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3664 /// specified value.
3665 static bool isUndefOrEqual(int Val, int CmpVal) {
3666   return (Val < 0 || Val == CmpVal);
3667 }
3668
3669 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3670 /// from position Pos and ending in Pos+Size, falls within the specified
3671 /// sequential range (L, L+Pos]. or is undef.
3672 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3673                                        unsigned Pos, unsigned Size, int Low) {
3674   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3675     if (!isUndefOrEqual(Mask[i], Low))
3676       return false;
3677   return true;
3678 }
3679
3680 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3682 /// the second operand.
3683 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3684   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3685     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3686   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3687     return (Mask[0] < 2 && Mask[1] < 2);
3688   return false;
3689 }
3690
3691 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3692 /// is suitable for input to PSHUFHW.
3693 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3694   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3695     return false;
3696
3697   // Lower quadword copied in order or undef.
3698   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3699     return false;
3700
3701   // Upper quadword shuffled.
3702   for (unsigned i = 4; i != 8; ++i)
3703     if (!isUndefOrInRange(Mask[i], 4, 8))
3704       return false;
3705
3706   if (VT == MVT::v16i16) {
3707     // Lower quadword copied in order or undef.
3708     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3709       return false;
3710
3711     // Upper quadword shuffled.
3712     for (unsigned i = 12; i != 16; ++i)
3713       if (!isUndefOrInRange(Mask[i], 12, 16))
3714         return false;
3715   }
3716
3717   return true;
3718 }
3719
3720 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3721 /// is suitable for input to PSHUFLW.
3722 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3723   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3724     return false;
3725
3726   // Upper quadword copied in order.
3727   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3728     return false;
3729
3730   // Lower quadword shuffled.
3731   for (unsigned i = 0; i != 4; ++i)
3732     if (!isUndefOrInRange(Mask[i], 0, 4))
3733       return false;
3734
3735   if (VT == MVT::v16i16) {
3736     // Upper quadword copied in order.
3737     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3738       return false;
3739
3740     // Lower quadword shuffled.
3741     for (unsigned i = 8; i != 12; ++i)
3742       if (!isUndefOrInRange(Mask[i], 8, 12))
3743         return false;
3744   }
3745
3746   return true;
3747 }
3748
3749 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PALIGNR.
3751 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3752                           const X86Subtarget *Subtarget) {
3753   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3754       (VT.is256BitVector() && !Subtarget->hasInt256()))
3755     return false;
3756
3757   unsigned NumElts = VT.getVectorNumElements();
3758   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3759   unsigned NumLaneElts = NumElts/NumLanes;
3760
3761   // Do not handle 64-bit element shuffles with palignr.
3762   if (NumLaneElts == 2)
3763     return false;
3764
3765   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3766     unsigned i;
3767     for (i = 0; i != NumLaneElts; ++i) {
3768       if (Mask[i+l] >= 0)
3769         break;
3770     }
3771
3772     // Lane is all undef, go to next lane
3773     if (i == NumLaneElts)
3774       continue;
3775
3776     int Start = Mask[i+l];
3777
3778     // Make sure its in this lane in one of the sources
3779     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3780         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3781       return false;
3782
3783     // If not lane 0, then we must match lane 0
3784     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3785       return false;
3786
3787     // Correct second source to be contiguous with first source
3788     if (Start >= (int)NumElts)
3789       Start -= NumElts - NumLaneElts;
3790
3791     // Make sure we're shifting in the right direction.
3792     if (Start <= (int)(i+l))
3793       return false;
3794
3795     Start -= i;
3796
3797     // Check the rest of the elements to see if they are consecutive.
3798     for (++i; i != NumLaneElts; ++i) {
3799       int Idx = Mask[i+l];
3800
3801       // Make sure its in this lane
3802       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3803           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3804         return false;
3805
3806       // If not lane 0, then we must match lane 0
3807       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3808         return false;
3809
3810       if (Idx >= (int)NumElts)
3811         Idx -= NumElts - NumLaneElts;
3812
3813       if (!isUndefOrEqual(Idx, Start+i))
3814         return false;
3815
3816     }
3817   }
3818
3819   return true;
3820 }
3821
3822 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3823 /// the two vector operands have swapped position.
3824 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3825                                      unsigned NumElems) {
3826   for (unsigned i = 0; i != NumElems; ++i) {
3827     int idx = Mask[i];
3828     if (idx < 0)
3829       continue;
3830     else if (idx < (int)NumElems)
3831       Mask[i] = idx + NumElems;
3832     else
3833       Mask[i] = idx - NumElems;
3834   }
3835 }
3836
3837 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3839 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3840 /// reverse of what x86 shuffles want.
3841 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3842
3843   unsigned NumElems = VT.getVectorNumElements();
3844   unsigned NumLanes = VT.getSizeInBits()/128;
3845   unsigned NumLaneElems = NumElems/NumLanes;
3846
3847   if (NumLaneElems != 2 && NumLaneElems != 4)
3848     return false;
3849
3850   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3851   bool symetricMaskRequired =
3852     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3853
3854   // VSHUFPSY divides the resulting vector into 4 chunks.
3855   // The sources are also splitted into 4 chunks, and each destination
3856   // chunk must come from a different source chunk.
3857   //
3858   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3859   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3860   //
3861   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3862   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3863   //
3864   // VSHUFPDY divides the resulting vector into 4 chunks.
3865   // The sources are also splitted into 4 chunks, and each destination
3866   // chunk must come from a different source chunk.
3867   //
3868   //  SRC1 =>      X3       X2       X1       X0
3869   //  SRC2 =>      Y3       Y2       Y1       Y0
3870   //
3871   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3872   //
3873   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3874   unsigned HalfLaneElems = NumLaneElems/2;
3875   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3876     for (unsigned i = 0; i != NumLaneElems; ++i) {
3877       int Idx = Mask[i+l];
3878       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3879       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3880         return false;
3881       // For VSHUFPSY, the mask of the second half must be the same as the
3882       // first but with the appropriate offsets. This works in the same way as
3883       // VPERMILPS works with masks.
3884       if (!symetricMaskRequired || Idx < 0)
3885         continue;
3886       if (MaskVal[i] < 0) {
3887         MaskVal[i] = Idx - l;
3888         continue;
3889       }
3890       if ((signed)(Idx - l) != MaskVal[i])
3891         return false;
3892     }
3893   }
3894
3895   return true;
3896 }
3897
3898 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3900 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3901   if (!VT.is128BitVector())
3902     return false;
3903
3904   unsigned NumElems = VT.getVectorNumElements();
3905
3906   if (NumElems != 4)
3907     return false;
3908
3909   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3910   return isUndefOrEqual(Mask[0], 6) &&
3911          isUndefOrEqual(Mask[1], 7) &&
3912          isUndefOrEqual(Mask[2], 2) &&
3913          isUndefOrEqual(Mask[3], 3);
3914 }
3915
3916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3918 /// <2, 3, 2, 3>
3919 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3920   if (!VT.is128BitVector())
3921     return false;
3922
3923   unsigned NumElems = VT.getVectorNumElements();
3924
3925   if (NumElems != 4)
3926     return false;
3927
3928   return isUndefOrEqual(Mask[0], 2) &&
3929          isUndefOrEqual(Mask[1], 3) &&
3930          isUndefOrEqual(Mask[2], 2) &&
3931          isUndefOrEqual(Mask[3], 3);
3932 }
3933
3934 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3935 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3936 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3937   if (!VT.is128BitVector())
3938     return false;
3939
3940   unsigned NumElems = VT.getVectorNumElements();
3941
3942   if (NumElems != 2 && NumElems != 4)
3943     return false;
3944
3945   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3946     if (!isUndefOrEqual(Mask[i], i + NumElems))
3947       return false;
3948
3949   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3950     if (!isUndefOrEqual(Mask[i], i))
3951       return false;
3952
3953   return true;
3954 }
3955
3956 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3958 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3959   if (!VT.is128BitVector())
3960     return false;
3961
3962   unsigned NumElems = VT.getVectorNumElements();
3963
3964   if (NumElems != 2 && NumElems != 4)
3965     return false;
3966
3967   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3968     if (!isUndefOrEqual(Mask[i], i))
3969       return false;
3970
3971   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3972     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3973       return false;
3974
3975   return true;
3976 }
3977
3978 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3980 /// i. e: If all but one element come from the same vector.
3981 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3982   // TODO: Deal with AVX's VINSERTPS
3983   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3984     return false;
3985
3986   unsigned CorrectPosV1 = 0;
3987   unsigned CorrectPosV2 = 0;
3988   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3989     if (Mask[i] == -1) {
3990       ++CorrectPosV1;
3991       ++CorrectPosV2;
3992       continue;
3993     }
3994
3995     if (Mask[i] == i)
3996       ++CorrectPosV1;
3997     else if (Mask[i] == i + 4)
3998       ++CorrectPosV2;
3999   }
4000
4001   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4002     // We have 3 elements (undefs count as elements from any vector) from one
4003     // vector, and one from another.
4004     return true;
4005
4006   return false;
4007 }
4008
4009 //
4010 // Some special combinations that can be optimized.
4011 //
4012 static
4013 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4014                                SelectionDAG &DAG) {
4015   MVT VT = SVOp->getSimpleValueType(0);
4016   SDLoc dl(SVOp);
4017
4018   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4019     return SDValue();
4020
4021   ArrayRef<int> Mask = SVOp->getMask();
4022
4023   // These are the special masks that may be optimized.
4024   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4025   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4026   bool MatchEvenMask = true;
4027   bool MatchOddMask  = true;
4028   for (int i=0; i<8; ++i) {
4029     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4030       MatchEvenMask = false;
4031     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4032       MatchOddMask = false;
4033   }
4034
4035   if (!MatchEvenMask && !MatchOddMask)
4036     return SDValue();
4037
4038   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4039
4040   SDValue Op0 = SVOp->getOperand(0);
4041   SDValue Op1 = SVOp->getOperand(1);
4042
4043   if (MatchEvenMask) {
4044     // Shift the second operand right to 32 bits.
4045     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4046     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4047   } else {
4048     // Shift the first operand left to 32 bits.
4049     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4050     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4051   }
4052   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4053   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4054 }
4055
4056 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4058 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4059                          bool HasInt256, bool V2IsSplat = false) {
4060
4061   assert(VT.getSizeInBits() >= 128 &&
4062          "Unsupported vector type for unpckl");
4063
4064   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4065   unsigned NumLanes;
4066   unsigned NumOf256BitLanes;
4067   unsigned NumElts = VT.getVectorNumElements();
4068   if (VT.is256BitVector()) {
4069     if (NumElts != 4 && NumElts != 8 &&
4070         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4071     return false;
4072     NumLanes = 2;
4073     NumOf256BitLanes = 1;
4074   } else if (VT.is512BitVector()) {
4075     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076            "Unsupported vector type for unpckh");
4077     NumLanes = 2;
4078     NumOf256BitLanes = 2;
4079   } else {
4080     NumLanes = 1;
4081     NumOf256BitLanes = 1;
4082   }
4083
4084   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4086
4087   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4090         int BitI  = Mask[l256*NumEltsInStride+l+i];
4091         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4093           return false;
4094         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4095           return false;
4096         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4097           return false;
4098       }
4099     }
4100   }
4101   return true;
4102 }
4103
4104 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4105 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4106 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4107                          bool HasInt256, bool V2IsSplat = false) {
4108   assert(VT.getSizeInBits() >= 128 &&
4109          "Unsupported vector type for unpckh");
4110
4111   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4112   unsigned NumLanes;
4113   unsigned NumOf256BitLanes;
4114   unsigned NumElts = VT.getVectorNumElements();
4115   if (VT.is256BitVector()) {
4116     if (NumElts != 4 && NumElts != 8 &&
4117         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4118     return false;
4119     NumLanes = 2;
4120     NumOf256BitLanes = 1;
4121   } else if (VT.is512BitVector()) {
4122     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4123            "Unsupported vector type for unpckh");
4124     NumLanes = 2;
4125     NumOf256BitLanes = 2;
4126   } else {
4127     NumLanes = 1;
4128     NumOf256BitLanes = 1;
4129   }
4130
4131   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4132   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4133
4134   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4135     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4136       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4137         int BitI  = Mask[l256*NumEltsInStride+l+i];
4138         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4139         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4140           return false;
4141         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4142           return false;
4143         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4144           return false;
4145       }
4146     }
4147   }
4148   return true;
4149 }
4150
4151 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4152 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4153 /// <0, 0, 1, 1>
4154 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4155   unsigned NumElts = VT.getVectorNumElements();
4156   bool Is256BitVec = VT.is256BitVector();
4157
4158   if (VT.is512BitVector())
4159     return false;
4160   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4161          "Unsupported vector type for unpckh");
4162
4163   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4164       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4165     return false;
4166
4167   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4168   // FIXME: Need a better way to get rid of this, there's no latency difference
4169   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4170   // the former later. We should also remove the "_undef" special mask.
4171   if (NumElts == 4 && Is256BitVec)
4172     return false;
4173
4174   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4175   // independently on 128-bit lanes.
4176   unsigned NumLanes = VT.getSizeInBits()/128;
4177   unsigned NumLaneElts = NumElts/NumLanes;
4178
4179   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4180     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4181       int BitI  = Mask[l+i];
4182       int BitI1 = Mask[l+i+1];
4183
4184       if (!isUndefOrEqual(BitI, j))
4185         return false;
4186       if (!isUndefOrEqual(BitI1, j))
4187         return false;
4188     }
4189   }
4190
4191   return true;
4192 }
4193
4194 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4195 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4196 /// <2, 2, 3, 3>
4197 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4198   unsigned NumElts = VT.getVectorNumElements();
4199
4200   if (VT.is512BitVector())
4201     return false;
4202
4203   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4204          "Unsupported vector type for unpckh");
4205
4206   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4207       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4208     return false;
4209
4210   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4211   // independently on 128-bit lanes.
4212   unsigned NumLanes = VT.getSizeInBits()/128;
4213   unsigned NumLaneElts = NumElts/NumLanes;
4214
4215   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4216     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4217       int BitI  = Mask[l+i];
4218       int BitI1 = Mask[l+i+1];
4219       if (!isUndefOrEqual(BitI, j))
4220         return false;
4221       if (!isUndefOrEqual(BitI1, j))
4222         return false;
4223     }
4224   }
4225   return true;
4226 }
4227
4228 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4229 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4230 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4231   if (!VT.is512BitVector())
4232     return false;
4233
4234   unsigned NumElts = VT.getVectorNumElements();
4235   unsigned HalfSize = NumElts/2;
4236   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4237     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4238       *Imm = 1;
4239       return true;
4240     }
4241   }
4242   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4243     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4244       *Imm = 0;
4245       return true;
4246     }
4247   }
4248   return false;
4249 }
4250
4251 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4252 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4253 /// MOVSD, and MOVD, i.e. setting the lowest element.
4254 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4255   if (VT.getVectorElementType().getSizeInBits() < 32)
4256     return false;
4257   if (!VT.is128BitVector())
4258     return false;
4259
4260   unsigned NumElts = VT.getVectorNumElements();
4261
4262   if (!isUndefOrEqual(Mask[0], NumElts))
4263     return false;
4264
4265   for (unsigned i = 1; i != NumElts; ++i)
4266     if (!isUndefOrEqual(Mask[i], i))
4267       return false;
4268
4269   return true;
4270 }
4271
4272 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4273 /// as permutations between 128-bit chunks or halves. As an example: this
4274 /// shuffle bellow:
4275 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4276 /// The first half comes from the second half of V1 and the second half from the
4277 /// the second half of V2.
4278 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4279   if (!HasFp256 || !VT.is256BitVector())
4280     return false;
4281
4282   // The shuffle result is divided into half A and half B. In total the two
4283   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4284   // B must come from C, D, E or F.
4285   unsigned HalfSize = VT.getVectorNumElements()/2;
4286   bool MatchA = false, MatchB = false;
4287
4288   // Check if A comes from one of C, D, E, F.
4289   for (unsigned Half = 0; Half != 4; ++Half) {
4290     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4291       MatchA = true;
4292       break;
4293     }
4294   }
4295
4296   // Check if B comes from one of C, D, E, F.
4297   for (unsigned Half = 0; Half != 4; ++Half) {
4298     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4299       MatchB = true;
4300       break;
4301     }
4302   }
4303
4304   return MatchA && MatchB;
4305 }
4306
4307 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4308 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4309 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4310   MVT VT = SVOp->getSimpleValueType(0);
4311
4312   unsigned HalfSize = VT.getVectorNumElements()/2;
4313
4314   unsigned FstHalf = 0, SndHalf = 0;
4315   for (unsigned i = 0; i < HalfSize; ++i) {
4316     if (SVOp->getMaskElt(i) > 0) {
4317       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4318       break;
4319     }
4320   }
4321   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4322     if (SVOp->getMaskElt(i) > 0) {
4323       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4324       break;
4325     }
4326   }
4327
4328   return (FstHalf | (SndHalf << 4));
4329 }
4330
4331 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4332 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4333   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4334   if (EltSize < 32)
4335     return false;
4336
4337   unsigned NumElts = VT.getVectorNumElements();
4338   Imm8 = 0;
4339   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4340     for (unsigned i = 0; i != NumElts; ++i) {
4341       if (Mask[i] < 0)
4342         continue;
4343       Imm8 |= Mask[i] << (i*2);
4344     }
4345     return true;
4346   }
4347
4348   unsigned LaneSize = 4;
4349   SmallVector<int, 4> MaskVal(LaneSize, -1);
4350
4351   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4352     for (unsigned i = 0; i != LaneSize; ++i) {
4353       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4354         return false;
4355       if (Mask[i+l] < 0)
4356         continue;
4357       if (MaskVal[i] < 0) {
4358         MaskVal[i] = Mask[i+l] - l;
4359         Imm8 |= MaskVal[i] << (i*2);
4360         continue;
4361       }
4362       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4363         return false;
4364     }
4365   }
4366   return true;
4367 }
4368
4369 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4370 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4371 /// Note that VPERMIL mask matching is different depending whether theunderlying
4372 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4373 /// to the same elements of the low, but to the higher half of the source.
4374 /// In VPERMILPD the two lanes could be shuffled independently of each other
4375 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4376 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4377   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4378   if (VT.getSizeInBits() < 256 || EltSize < 32)
4379     return false;
4380   bool symetricMaskRequired = (EltSize == 32);
4381   unsigned NumElts = VT.getVectorNumElements();
4382
4383   unsigned NumLanes = VT.getSizeInBits()/128;
4384   unsigned LaneSize = NumElts/NumLanes;
4385   // 2 or 4 elements in one lane
4386
4387   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4388   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4389     for (unsigned i = 0; i != LaneSize; ++i) {
4390       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4391         return false;
4392       if (symetricMaskRequired) {
4393         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4394           ExpectedMaskVal[i] = Mask[i+l] - l;
4395           continue;
4396         }
4397         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4398           return false;
4399       }
4400     }
4401   }
4402   return true;
4403 }
4404
4405 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4406 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4407 /// element of vector 2 and the other elements to come from vector 1 in order.
4408 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4409                                bool V2IsSplat = false, bool V2IsUndef = false) {
4410   if (!VT.is128BitVector())
4411     return false;
4412
4413   unsigned NumOps = VT.getVectorNumElements();
4414   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4415     return false;
4416
4417   if (!isUndefOrEqual(Mask[0], 0))
4418     return false;
4419
4420   for (unsigned i = 1; i != NumOps; ++i)
4421     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4422           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4423           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4424       return false;
4425
4426   return true;
4427 }
4428
4429 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4431 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4432 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4433                            const X86Subtarget *Subtarget) {
4434   if (!Subtarget->hasSSE3())
4435     return false;
4436
4437   unsigned NumElems = VT.getVectorNumElements();
4438
4439   if ((VT.is128BitVector() && NumElems != 4) ||
4440       (VT.is256BitVector() && NumElems != 8) ||
4441       (VT.is512BitVector() && NumElems != 16))
4442     return false;
4443
4444   // "i+1" is the value the indexed mask element must have
4445   for (unsigned i = 0; i != NumElems; i += 2)
4446     if (!isUndefOrEqual(Mask[i], i+1) ||
4447         !isUndefOrEqual(Mask[i+1], i+1))
4448       return false;
4449
4450   return true;
4451 }
4452
4453 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4454 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4455 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4456 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4457                            const X86Subtarget *Subtarget) {
4458   if (!Subtarget->hasSSE3())
4459     return false;
4460
4461   unsigned NumElems = VT.getVectorNumElements();
4462
4463   if ((VT.is128BitVector() && NumElems != 4) ||
4464       (VT.is256BitVector() && NumElems != 8) ||
4465       (VT.is512BitVector() && NumElems != 16))
4466     return false;
4467
4468   // "i" is the value the indexed mask element must have
4469   for (unsigned i = 0; i != NumElems; i += 2)
4470     if (!isUndefOrEqual(Mask[i], i) ||
4471         !isUndefOrEqual(Mask[i+1], i))
4472       return false;
4473
4474   return true;
4475 }
4476
4477 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4478 /// specifies a shuffle of elements that is suitable for input to 256-bit
4479 /// version of MOVDDUP.
4480 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4481   if (!HasFp256 || !VT.is256BitVector())
4482     return false;
4483
4484   unsigned NumElts = VT.getVectorNumElements();
4485   if (NumElts != 4)
4486     return false;
4487
4488   for (unsigned i = 0; i != NumElts/2; ++i)
4489     if (!isUndefOrEqual(Mask[i], 0))
4490       return false;
4491   for (unsigned i = NumElts/2; i != NumElts; ++i)
4492     if (!isUndefOrEqual(Mask[i], NumElts/2))
4493       return false;
4494   return true;
4495 }
4496
4497 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to 128-bit
4499 /// version of MOVDDUP.
4500 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4501   if (!VT.is128BitVector())
4502     return false;
4503
4504   unsigned e = VT.getVectorNumElements() / 2;
4505   for (unsigned i = 0; i != e; ++i)
4506     if (!isUndefOrEqual(Mask[i], i))
4507       return false;
4508   for (unsigned i = 0; i != e; ++i)
4509     if (!isUndefOrEqual(Mask[e+i], i))
4510       return false;
4511   return true;
4512 }
4513
4514 /// isVEXTRACTIndex - Return true if the specified
4515 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4516 /// suitable for instruction that extract 128 or 256 bit vectors
4517 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4518   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4519   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4520     return false;
4521
4522   // The index should be aligned on a vecWidth-bit boundary.
4523   uint64_t Index =
4524     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4525
4526   MVT VT = N->getSimpleValueType(0);
4527   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4528   bool Result = (Index * ElSize) % vecWidth == 0;
4529
4530   return Result;
4531 }
4532
4533 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4534 /// operand specifies a subvector insert that is suitable for input to
4535 /// insertion of 128 or 256-bit subvectors
4536 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4537   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4538   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4539     return false;
4540   // The index should be aligned on a vecWidth-bit boundary.
4541   uint64_t Index =
4542     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4543
4544   MVT VT = N->getSimpleValueType(0);
4545   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4546   bool Result = (Index * ElSize) % vecWidth == 0;
4547
4548   return Result;
4549 }
4550
4551 bool X86::isVINSERT128Index(SDNode *N) {
4552   return isVINSERTIndex(N, 128);
4553 }
4554
4555 bool X86::isVINSERT256Index(SDNode *N) {
4556   return isVINSERTIndex(N, 256);
4557 }
4558
4559 bool X86::isVEXTRACT128Index(SDNode *N) {
4560   return isVEXTRACTIndex(N, 128);
4561 }
4562
4563 bool X86::isVEXTRACT256Index(SDNode *N) {
4564   return isVEXTRACTIndex(N, 256);
4565 }
4566
4567 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4568 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4569 /// Handles 128-bit and 256-bit.
4570 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4571   MVT VT = N->getSimpleValueType(0);
4572
4573   assert((VT.getSizeInBits() >= 128) &&
4574          "Unsupported vector type for PSHUF/SHUFP");
4575
4576   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4577   // independently on 128-bit lanes.
4578   unsigned NumElts = VT.getVectorNumElements();
4579   unsigned NumLanes = VT.getSizeInBits()/128;
4580   unsigned NumLaneElts = NumElts/NumLanes;
4581
4582   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4583          "Only supports 2, 4 or 8 elements per lane");
4584
4585   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4586   unsigned Mask = 0;
4587   for (unsigned i = 0; i != NumElts; ++i) {
4588     int Elt = N->getMaskElt(i);
4589     if (Elt < 0) continue;
4590     Elt &= NumLaneElts - 1;
4591     unsigned ShAmt = (i << Shift) % 8;
4592     Mask |= Elt << ShAmt;
4593   }
4594
4595   return Mask;
4596 }
4597
4598 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4600 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4601   MVT VT = N->getSimpleValueType(0);
4602
4603   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4604          "Unsupported vector type for PSHUFHW");
4605
4606   unsigned NumElts = VT.getVectorNumElements();
4607
4608   unsigned Mask = 0;
4609   for (unsigned l = 0; l != NumElts; l += 8) {
4610     // 8 nodes per lane, but we only care about the last 4.
4611     for (unsigned i = 0; i < 4; ++i) {
4612       int Elt = N->getMaskElt(l+i+4);
4613       if (Elt < 0) continue;
4614       Elt &= 0x3; // only 2-bits.
4615       Mask |= Elt << (i * 2);
4616     }
4617   }
4618
4619   return Mask;
4620 }
4621
4622 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4623 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4624 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4625   MVT VT = N->getSimpleValueType(0);
4626
4627   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4628          "Unsupported vector type for PSHUFHW");
4629
4630   unsigned NumElts = VT.getVectorNumElements();
4631
4632   unsigned Mask = 0;
4633   for (unsigned l = 0; l != NumElts; l += 8) {
4634     // 8 nodes per lane, but we only care about the first 4.
4635     for (unsigned i = 0; i < 4; ++i) {
4636       int Elt = N->getMaskElt(l+i);
4637       if (Elt < 0) continue;
4638       Elt &= 0x3; // only 2-bits
4639       Mask |= Elt << (i * 2);
4640     }
4641   }
4642
4643   return Mask;
4644 }
4645
4646 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4647 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4648 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4649   MVT VT = SVOp->getSimpleValueType(0);
4650   unsigned EltSize = VT.is512BitVector() ? 1 :
4651     VT.getVectorElementType().getSizeInBits() >> 3;
4652
4653   unsigned NumElts = VT.getVectorNumElements();
4654   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4655   unsigned NumLaneElts = NumElts/NumLanes;
4656
4657   int Val = 0;
4658   unsigned i;
4659   for (i = 0; i != NumElts; ++i) {
4660     Val = SVOp->getMaskElt(i);
4661     if (Val >= 0)
4662       break;
4663   }
4664   if (Val >= (int)NumElts)
4665     Val -= NumElts - NumLaneElts;
4666
4667   assert(Val - i > 0 && "PALIGNR imm should be positive");
4668   return (Val - i) * EltSize;
4669 }
4670
4671 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4672   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4674     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4675
4676   uint64_t Index =
4677     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4678
4679   MVT VecVT = N->getOperand(0).getSimpleValueType();
4680   MVT ElVT = VecVT.getVectorElementType();
4681
4682   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683   return Index / NumElemsPerChunk;
4684 }
4685
4686 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4687   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4688   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4689     llvm_unreachable("Illegal insert subvector for VINSERT");
4690
4691   uint64_t Index =
4692     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4693
4694   MVT VecVT = N->getSimpleValueType(0);
4695   MVT ElVT = VecVT.getVectorElementType();
4696
4697   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4698   return Index / NumElemsPerChunk;
4699 }
4700
4701 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4703 /// and VINSERTI128 instructions.
4704 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4705   return getExtractVEXTRACTImmediate(N, 128);
4706 }
4707
4708 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4709 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4710 /// and VINSERTI64x4 instructions.
4711 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4712   return getExtractVEXTRACTImmediate(N, 256);
4713 }
4714
4715 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4717 /// and VINSERTI128 instructions.
4718 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4719   return getInsertVINSERTImmediate(N, 128);
4720 }
4721
4722 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4723 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4724 /// and VINSERTI64x4 instructions.
4725 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4726   return getInsertVINSERTImmediate(N, 256);
4727 }
4728
4729 /// isZero - Returns true if Elt is a constant integer zero
4730 static bool isZero(SDValue V) {
4731   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4732   return C && C->isNullValue();
4733 }
4734
4735 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4736 /// constant +0.0.
4737 bool X86::isZeroNode(SDValue Elt) {
4738   if (isZero(Elt))
4739     return true;
4740   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4741     return CFP->getValueAPF().isPosZero();
4742   return false;
4743 }
4744
4745 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4746 /// their permute mask.
4747 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4748                                     SelectionDAG &DAG) {
4749   MVT VT = SVOp->getSimpleValueType(0);
4750   unsigned NumElems = VT.getVectorNumElements();
4751   SmallVector<int, 8> MaskVec;
4752
4753   for (unsigned i = 0; i != NumElems; ++i) {
4754     int Idx = SVOp->getMaskElt(i);
4755     if (Idx >= 0) {
4756       if (Idx < (int)NumElems)
4757         Idx += NumElems;
4758       else
4759         Idx -= NumElems;
4760     }
4761     MaskVec.push_back(Idx);
4762   }
4763   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4764                               SVOp->getOperand(0), &MaskVec[0]);
4765 }
4766
4767 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4768 /// match movhlps. The lower half elements should come from upper half of
4769 /// V1 (and in order), and the upper half elements should come from the upper
4770 /// half of V2 (and in order).
4771 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4772   if (!VT.is128BitVector())
4773     return false;
4774   if (VT.getVectorNumElements() != 4)
4775     return false;
4776   for (unsigned i = 0, e = 2; i != e; ++i)
4777     if (!isUndefOrEqual(Mask[i], i+2))
4778       return false;
4779   for (unsigned i = 2; i != 4; ++i)
4780     if (!isUndefOrEqual(Mask[i], i+4))
4781       return false;
4782   return true;
4783 }
4784
4785 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4786 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4787 /// required.
4788 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4789   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4790     return false;
4791   N = N->getOperand(0).getNode();
4792   if (!ISD::isNON_EXTLoad(N))
4793     return false;
4794   if (LD)
4795     *LD = cast<LoadSDNode>(N);
4796   return true;
4797 }
4798
4799 // Test whether the given value is a vector value which will be legalized
4800 // into a load.
4801 static bool WillBeConstantPoolLoad(SDNode *N) {
4802   if (N->getOpcode() != ISD::BUILD_VECTOR)
4803     return false;
4804
4805   // Check for any non-constant elements.
4806   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4807     switch (N->getOperand(i).getNode()->getOpcode()) {
4808     case ISD::UNDEF:
4809     case ISD::ConstantFP:
4810     case ISD::Constant:
4811       break;
4812     default:
4813       return false;
4814     }
4815
4816   // Vectors of all-zeros and all-ones are materialized with special
4817   // instructions rather than being loaded.
4818   return !ISD::isBuildVectorAllZeros(N) &&
4819          !ISD::isBuildVectorAllOnes(N);
4820 }
4821
4822 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4823 /// match movlp{s|d}. The lower half elements should come from lower half of
4824 /// V1 (and in order), and the upper half elements should come from the upper
4825 /// half of V2 (and in order). And since V1 will become the source of the
4826 /// MOVLP, it must be either a vector load or a scalar load to vector.
4827 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4828                                ArrayRef<int> Mask, MVT VT) {
4829   if (!VT.is128BitVector())
4830     return false;
4831
4832   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4833     return false;
4834   // Is V2 is a vector load, don't do this transformation. We will try to use
4835   // load folding shufps op.
4836   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4837     return false;
4838
4839   unsigned NumElems = VT.getVectorNumElements();
4840
4841   if (NumElems != 2 && NumElems != 4)
4842     return false;
4843   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4844     if (!isUndefOrEqual(Mask[i], i))
4845       return false;
4846   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4847     if (!isUndefOrEqual(Mask[i], i+NumElems))
4848       return false;
4849   return true;
4850 }
4851
4852 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4853 /// all the same.
4854 static bool isSplatVector(SDNode *N) {
4855   if (N->getOpcode() != ISD::BUILD_VECTOR)
4856     return false;
4857
4858   SDValue SplatValue = N->getOperand(0);
4859   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4860     if (N->getOperand(i) != SplatValue)
4861       return false;
4862   return true;
4863 }
4864
4865 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4866 /// to an zero vector.
4867 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4868 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4869   SDValue V1 = N->getOperand(0);
4870   SDValue V2 = N->getOperand(1);
4871   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4872   for (unsigned i = 0; i != NumElems; ++i) {
4873     int Idx = N->getMaskElt(i);
4874     if (Idx >= (int)NumElems) {
4875       unsigned Opc = V2.getOpcode();
4876       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4877         continue;
4878       if (Opc != ISD::BUILD_VECTOR ||
4879           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4880         return false;
4881     } else if (Idx >= 0) {
4882       unsigned Opc = V1.getOpcode();
4883       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4884         continue;
4885       if (Opc != ISD::BUILD_VECTOR ||
4886           !X86::isZeroNode(V1.getOperand(Idx)))
4887         return false;
4888     }
4889   }
4890   return true;
4891 }
4892
4893 /// getZeroVector - Returns a vector of specified type with all zero elements.
4894 ///
4895 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4896                              SelectionDAG &DAG, SDLoc dl) {
4897   assert(VT.isVector() && "Expected a vector type");
4898
4899   // Always build SSE zero vectors as <4 x i32> bitcasted
4900   // to their dest type. This ensures they get CSE'd.
4901   SDValue Vec;
4902   if (VT.is128BitVector()) {  // SSE
4903     if (Subtarget->hasSSE2()) {  // SSE2
4904       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4905       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4906     } else { // SSE1
4907       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4909     }
4910   } else if (VT.is256BitVector()) { // AVX
4911     if (Subtarget->hasInt256()) { // AVX2
4912       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4915     } else {
4916       // 256-bit logic and arithmetic instructions in AVX are all
4917       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4918       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4919       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4921     }
4922   } else if (VT.is512BitVector()) { // AVX-512
4923       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4924       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4925                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4926       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4927   } else if (VT.getScalarType() == MVT::i1) {
4928     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4929     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4930     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4931     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4932   } else
4933     llvm_unreachable("Unexpected vector type");
4934
4935   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4936 }
4937
4938 /// getOnesVector - Returns a vector of specified type with all bits set.
4939 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4940 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4941 /// Then bitcast to their original type, ensuring they get CSE'd.
4942 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4943                              SDLoc dl) {
4944   assert(VT.isVector() && "Expected a vector type");
4945
4946   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4947   SDValue Vec;
4948   if (VT.is256BitVector()) {
4949     if (HasInt256) { // AVX2
4950       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4952     } else { // AVX
4953       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4954       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4955     }
4956   } else if (VT.is128BitVector()) {
4957     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4958   } else
4959     llvm_unreachable("Unexpected vector type");
4960
4961   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4962 }
4963
4964 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4965 /// that point to V2 points to its first element.
4966 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4967   for (unsigned i = 0; i != NumElems; ++i) {
4968     if (Mask[i] > (int)NumElems) {
4969       Mask[i] = NumElems;
4970     }
4971   }
4972 }
4973
4974 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4975 /// operation of specified width.
4976 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4977                        SDValue V2) {
4978   unsigned NumElems = VT.getVectorNumElements();
4979   SmallVector<int, 8> Mask;
4980   Mask.push_back(NumElems);
4981   for (unsigned i = 1; i != NumElems; ++i)
4982     Mask.push_back(i);
4983   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4984 }
4985
4986 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4987 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4988                           SDValue V2) {
4989   unsigned NumElems = VT.getVectorNumElements();
4990   SmallVector<int, 8> Mask;
4991   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4992     Mask.push_back(i);
4993     Mask.push_back(i + NumElems);
4994   }
4995   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4996 }
4997
4998 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4999 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5000                           SDValue V2) {
5001   unsigned NumElems = VT.getVectorNumElements();
5002   SmallVector<int, 8> Mask;
5003   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5004     Mask.push_back(i + Half);
5005     Mask.push_back(i + NumElems + Half);
5006   }
5007   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5008 }
5009
5010 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5011 // a generic shuffle instruction because the target has no such instructions.
5012 // Generate shuffles which repeat i16 and i8 several times until they can be
5013 // represented by v4f32 and then be manipulated by target suported shuffles.
5014 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5015   MVT VT = V.getSimpleValueType();
5016   int NumElems = VT.getVectorNumElements();
5017   SDLoc dl(V);
5018
5019   while (NumElems > 4) {
5020     if (EltNo < NumElems/2) {
5021       V = getUnpackl(DAG, dl, VT, V, V);
5022     } else {
5023       V = getUnpackh(DAG, dl, VT, V, V);
5024       EltNo -= NumElems/2;
5025     }
5026     NumElems >>= 1;
5027   }
5028   return V;
5029 }
5030
5031 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5032 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5033   MVT VT = V.getSimpleValueType();
5034   SDLoc dl(V);
5035
5036   if (VT.is128BitVector()) {
5037     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5038     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5039     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5040                              &SplatMask[0]);
5041   } else if (VT.is256BitVector()) {
5042     // To use VPERMILPS to splat scalars, the second half of indicies must
5043     // refer to the higher part, which is a duplication of the lower one,
5044     // because VPERMILPS can only handle in-lane permutations.
5045     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5046                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5047
5048     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5049     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5050                              &SplatMask[0]);
5051   } else
5052     llvm_unreachable("Vector size not supported");
5053
5054   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5055 }
5056
5057 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5058 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5059   MVT SrcVT = SV->getSimpleValueType(0);
5060   SDValue V1 = SV->getOperand(0);
5061   SDLoc dl(SV);
5062
5063   int EltNo = SV->getSplatIndex();
5064   int NumElems = SrcVT.getVectorNumElements();
5065   bool Is256BitVec = SrcVT.is256BitVector();
5066
5067   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5068          "Unknown how to promote splat for type");
5069
5070   // Extract the 128-bit part containing the splat element and update
5071   // the splat element index when it refers to the higher register.
5072   if (Is256BitVec) {
5073     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5074     if (EltNo >= NumElems/2)
5075       EltNo -= NumElems/2;
5076   }
5077
5078   // All i16 and i8 vector types can't be used directly by a generic shuffle
5079   // instruction because the target has no such instruction. Generate shuffles
5080   // which repeat i16 and i8 several times until they fit in i32, and then can
5081   // be manipulated by target suported shuffles.
5082   MVT EltVT = SrcVT.getVectorElementType();
5083   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5084     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5085
5086   // Recreate the 256-bit vector and place the same 128-bit vector
5087   // into the low and high part. This is necessary because we want
5088   // to use VPERM* to shuffle the vectors
5089   if (Is256BitVec) {
5090     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5091   }
5092
5093   return getLegalSplat(DAG, V1, EltNo);
5094 }
5095
5096 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5097 /// vector of zero or undef vector.  This produces a shuffle where the low
5098 /// element of V2 is swizzled into the zero/undef vector, landing at element
5099 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5100 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5101                                            bool IsZero,
5102                                            const X86Subtarget *Subtarget,
5103                                            SelectionDAG &DAG) {
5104   MVT VT = V2.getSimpleValueType();
5105   SDValue V1 = IsZero
5106     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5107   unsigned NumElems = VT.getVectorNumElements();
5108   SmallVector<int, 16> MaskVec;
5109   for (unsigned i = 0; i != NumElems; ++i)
5110     // If this is the insertion idx, put the low elt of V2 here.
5111     MaskVec.push_back(i == Idx ? NumElems : i);
5112   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5113 }
5114
5115 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5116 /// target specific opcode. Returns true if the Mask could be calculated.
5117 /// Sets IsUnary to true if only uses one source.
5118 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5119                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5120   unsigned NumElems = VT.getVectorNumElements();
5121   SDValue ImmN;
5122
5123   IsUnary = false;
5124   switch(N->getOpcode()) {
5125   case X86ISD::SHUFP:
5126     ImmN = N->getOperand(N->getNumOperands()-1);
5127     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5128     break;
5129   case X86ISD::UNPCKH:
5130     DecodeUNPCKHMask(VT, Mask);
5131     break;
5132   case X86ISD::UNPCKL:
5133     DecodeUNPCKLMask(VT, Mask);
5134     break;
5135   case X86ISD::MOVHLPS:
5136     DecodeMOVHLPSMask(NumElems, Mask);
5137     break;
5138   case X86ISD::MOVLHPS:
5139     DecodeMOVLHPSMask(NumElems, Mask);
5140     break;
5141   case X86ISD::PALIGNR:
5142     ImmN = N->getOperand(N->getNumOperands()-1);
5143     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144     break;
5145   case X86ISD::PSHUFD:
5146   case X86ISD::VPERMILP:
5147     ImmN = N->getOperand(N->getNumOperands()-1);
5148     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5149     IsUnary = true;
5150     break;
5151   case X86ISD::PSHUFHW:
5152     ImmN = N->getOperand(N->getNumOperands()-1);
5153     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154     IsUnary = true;
5155     break;
5156   case X86ISD::PSHUFLW:
5157     ImmN = N->getOperand(N->getNumOperands()-1);
5158     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159     IsUnary = true;
5160     break;
5161   case X86ISD::VPERMI:
5162     ImmN = N->getOperand(N->getNumOperands()-1);
5163     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5164     IsUnary = true;
5165     break;
5166   case X86ISD::MOVSS:
5167   case X86ISD::MOVSD: {
5168     // The index 0 always comes from the first element of the second source,
5169     // this is why MOVSS and MOVSD are used in the first place. The other
5170     // elements come from the other positions of the first source vector
5171     Mask.push_back(NumElems);
5172     for (unsigned i = 1; i != NumElems; ++i) {
5173       Mask.push_back(i);
5174     }
5175     break;
5176   }
5177   case X86ISD::VPERM2X128:
5178     ImmN = N->getOperand(N->getNumOperands()-1);
5179     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180     if (Mask.empty()) return false;
5181     break;
5182   case X86ISD::MOVDDUP:
5183   case X86ISD::MOVLHPD:
5184   case X86ISD::MOVLPD:
5185   case X86ISD::MOVLPS:
5186   case X86ISD::MOVSHDUP:
5187   case X86ISD::MOVSLDUP:
5188     // Not yet implemented
5189     return false;
5190   default: llvm_unreachable("unknown target shuffle node");
5191   }
5192
5193   return true;
5194 }
5195
5196 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5197 /// element of the result of the vector shuffle.
5198 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5199                                    unsigned Depth) {
5200   if (Depth == 6)
5201     return SDValue();  // Limit search depth.
5202
5203   SDValue V = SDValue(N, 0);
5204   EVT VT = V.getValueType();
5205   unsigned Opcode = V.getOpcode();
5206
5207   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5208   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5209     int Elt = SV->getMaskElt(Index);
5210
5211     if (Elt < 0)
5212       return DAG.getUNDEF(VT.getVectorElementType());
5213
5214     unsigned NumElems = VT.getVectorNumElements();
5215     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5216                                          : SV->getOperand(1);
5217     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5218   }
5219
5220   // Recurse into target specific vector shuffles to find scalars.
5221   if (isTargetShuffle(Opcode)) {
5222     MVT ShufVT = V.getSimpleValueType();
5223     unsigned NumElems = ShufVT.getVectorNumElements();
5224     SmallVector<int, 16> ShuffleMask;
5225     bool IsUnary;
5226
5227     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5228       return SDValue();
5229
5230     int Elt = ShuffleMask[Index];
5231     if (Elt < 0)
5232       return DAG.getUNDEF(ShufVT.getVectorElementType());
5233
5234     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5235                                          : N->getOperand(1);
5236     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5237                                Depth+1);
5238   }
5239
5240   // Actual nodes that may contain scalar elements
5241   if (Opcode == ISD::BITCAST) {
5242     V = V.getOperand(0);
5243     EVT SrcVT = V.getValueType();
5244     unsigned NumElems = VT.getVectorNumElements();
5245
5246     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5247       return SDValue();
5248   }
5249
5250   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5251     return (Index == 0) ? V.getOperand(0)
5252                         : DAG.getUNDEF(VT.getVectorElementType());
5253
5254   if (V.getOpcode() == ISD::BUILD_VECTOR)
5255     return V.getOperand(Index);
5256
5257   return SDValue();
5258 }
5259
5260 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5261 /// shuffle operation which come from a consecutively from a zero. The
5262 /// search can start in two different directions, from left or right.
5263 /// We count undefs as zeros until PreferredNum is reached.
5264 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5265                                          unsigned NumElems, bool ZerosFromLeft,
5266                                          SelectionDAG &DAG,
5267                                          unsigned PreferredNum = -1U) {
5268   unsigned NumZeros = 0;
5269   for (unsigned i = 0; i != NumElems; ++i) {
5270     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5271     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5272     if (!Elt.getNode())
5273       break;
5274
5275     if (X86::isZeroNode(Elt))
5276       ++NumZeros;
5277     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5278       NumZeros = std::min(NumZeros + 1, PreferredNum);
5279     else
5280       break;
5281   }
5282
5283   return NumZeros;
5284 }
5285
5286 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5287 /// correspond consecutively to elements from one of the vector operands,
5288 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5289 static
5290 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5291                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5292                               unsigned NumElems, unsigned &OpNum) {
5293   bool SeenV1 = false;
5294   bool SeenV2 = false;
5295
5296   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5297     int Idx = SVOp->getMaskElt(i);
5298     // Ignore undef indicies
5299     if (Idx < 0)
5300       continue;
5301
5302     if (Idx < (int)NumElems)
5303       SeenV1 = true;
5304     else
5305       SeenV2 = true;
5306
5307     // Only accept consecutive elements from the same vector
5308     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5309       return false;
5310   }
5311
5312   OpNum = SeenV1 ? 0 : 1;
5313   return true;
5314 }
5315
5316 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5317 /// logical left shift of a vector.
5318 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5319                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5320   unsigned NumElems =
5321     SVOp->getSimpleValueType(0).getVectorNumElements();
5322   unsigned NumZeros = getNumOfConsecutiveZeros(
5323       SVOp, NumElems, false /* check zeros from right */, DAG,
5324       SVOp->getMaskElt(0));
5325   unsigned OpSrc;
5326
5327   if (!NumZeros)
5328     return false;
5329
5330   // Considering the elements in the mask that are not consecutive zeros,
5331   // check if they consecutively come from only one of the source vectors.
5332   //
5333   //               V1 = {X, A, B, C}     0
5334   //                         \  \  \    /
5335   //   vector_shuffle V1, V2 <1, 2, 3, X>
5336   //
5337   if (!isShuffleMaskConsecutive(SVOp,
5338             0,                   // Mask Start Index
5339             NumElems-NumZeros,   // Mask End Index(exclusive)
5340             NumZeros,            // Where to start looking in the src vector
5341             NumElems,            // Number of elements in vector
5342             OpSrc))              // Which source operand ?
5343     return false;
5344
5345   isLeft = false;
5346   ShAmt = NumZeros;
5347   ShVal = SVOp->getOperand(OpSrc);
5348   return true;
5349 }
5350
5351 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5352 /// logical left shift of a vector.
5353 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5354                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5355   unsigned NumElems =
5356     SVOp->getSimpleValueType(0).getVectorNumElements();
5357   unsigned NumZeros = getNumOfConsecutiveZeros(
5358       SVOp, NumElems, true /* check zeros from left */, DAG,
5359       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5360   unsigned OpSrc;
5361
5362   if (!NumZeros)
5363     return false;
5364
5365   // Considering the elements in the mask that are not consecutive zeros,
5366   // check if they consecutively come from only one of the source vectors.
5367   //
5368   //                           0    { A, B, X, X } = V2
5369   //                          / \    /  /
5370   //   vector_shuffle V1, V2 <X, X, 4, 5>
5371   //
5372   if (!isShuffleMaskConsecutive(SVOp,
5373             NumZeros,     // Mask Start Index
5374             NumElems,     // Mask End Index(exclusive)
5375             0,            // Where to start looking in the src vector
5376             NumElems,     // Number of elements in vector
5377             OpSrc))       // Which source operand ?
5378     return false;
5379
5380   isLeft = true;
5381   ShAmt = NumZeros;
5382   ShVal = SVOp->getOperand(OpSrc);
5383   return true;
5384 }
5385
5386 /// isVectorShift - Returns true if the shuffle can be implemented as a
5387 /// logical left or right shift of a vector.
5388 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5389                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5390   // Although the logic below support any bitwidth size, there are no
5391   // shift instructions which handle more than 128-bit vectors.
5392   if (!SVOp->getSimpleValueType(0).is128BitVector())
5393     return false;
5394
5395   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5396       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5397     return true;
5398
5399   return false;
5400 }
5401
5402 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5403 ///
5404 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5405                                        unsigned NumNonZero, unsigned NumZero,
5406                                        SelectionDAG &DAG,
5407                                        const X86Subtarget* Subtarget,
5408                                        const TargetLowering &TLI) {
5409   if (NumNonZero > 8)
5410     return SDValue();
5411
5412   SDLoc dl(Op);
5413   SDValue V;
5414   bool First = true;
5415   for (unsigned i = 0; i < 16; ++i) {
5416     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5417     if (ThisIsNonZero && First) {
5418       if (NumZero)
5419         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5420       else
5421         V = DAG.getUNDEF(MVT::v8i16);
5422       First = false;
5423     }
5424
5425     if ((i & 1) != 0) {
5426       SDValue ThisElt, LastElt;
5427       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5428       if (LastIsNonZero) {
5429         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5430                               MVT::i16, Op.getOperand(i-1));
5431       }
5432       if (ThisIsNonZero) {
5433         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5434         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5435                               ThisElt, DAG.getConstant(8, MVT::i8));
5436         if (LastIsNonZero)
5437           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5438       } else
5439         ThisElt = LastElt;
5440
5441       if (ThisElt.getNode())
5442         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5443                         DAG.getIntPtrConstant(i/2));
5444     }
5445   }
5446
5447   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5448 }
5449
5450 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5451 ///
5452 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5453                                      unsigned NumNonZero, unsigned NumZero,
5454                                      SelectionDAG &DAG,
5455                                      const X86Subtarget* Subtarget,
5456                                      const TargetLowering &TLI) {
5457   if (NumNonZero > 4)
5458     return SDValue();
5459
5460   SDLoc dl(Op);
5461   SDValue V;
5462   bool First = true;
5463   for (unsigned i = 0; i < 8; ++i) {
5464     bool isNonZero = (NonZeros & (1 << i)) != 0;
5465     if (isNonZero) {
5466       if (First) {
5467         if (NumZero)
5468           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5469         else
5470           V = DAG.getUNDEF(MVT::v8i16);
5471         First = false;
5472       }
5473       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5474                       MVT::v8i16, V, Op.getOperand(i),
5475                       DAG.getIntPtrConstant(i));
5476     }
5477   }
5478
5479   return V;
5480 }
5481
5482 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5483 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5484                                      unsigned NonZeros, unsigned NumNonZero,
5485                                      unsigned NumZero, SelectionDAG &DAG,
5486                                      const X86Subtarget *Subtarget,
5487                                      const TargetLowering &TLI) {
5488   // We know there's at least one non-zero element
5489   unsigned FirstNonZeroIdx = 0;
5490   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5492          X86::isZeroNode(FirstNonZero)) {
5493     ++FirstNonZeroIdx;
5494     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5495   }
5496
5497   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5498       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5499     return SDValue();
5500
5501   SDValue V = FirstNonZero.getOperand(0);
5502   MVT VVT = V.getSimpleValueType();
5503   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5504     return SDValue();
5505
5506   unsigned FirstNonZeroDst =
5507       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5508   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5509   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5510   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5511
5512   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5513     SDValue Elem = Op.getOperand(Idx);
5514     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5515       continue;
5516
5517     // TODO: What else can be here? Deal with it.
5518     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5519       return SDValue();
5520
5521     // TODO: Some optimizations are still possible here
5522     // ex: Getting one element from a vector, and the rest from another.
5523     if (Elem.getOperand(0) != V)
5524       return SDValue();
5525
5526     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5527     if (Dst == Idx)
5528       ++CorrectIdx;
5529     else if (IncorrectIdx == -1U) {
5530       IncorrectIdx = Idx;
5531       IncorrectDst = Dst;
5532     } else
5533       // There was already one element with an incorrect index.
5534       // We can't optimize this case to an insertps.
5535       return SDValue();
5536   }
5537
5538   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5539     SDLoc dl(Op);
5540     EVT VT = Op.getSimpleValueType();
5541     unsigned ElementMoveMask = 0;
5542     if (IncorrectIdx == -1U)
5543       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5544     else
5545       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5546
5547     SDValue InsertpsMask =
5548         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5549     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5550   }
5551
5552   return SDValue();
5553 }
5554
5555 /// getVShift - Return a vector logical shift node.
5556 ///
5557 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5558                          unsigned NumBits, SelectionDAG &DAG,
5559                          const TargetLowering &TLI, SDLoc dl) {
5560   assert(VT.is128BitVector() && "Unknown type for VShift");
5561   EVT ShVT = MVT::v2i64;
5562   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5563   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5564   return DAG.getNode(ISD::BITCAST, dl, VT,
5565                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5566                              DAG.getConstant(NumBits,
5567                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5568 }
5569
5570 static SDValue
5571 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5572
5573   // Check if the scalar load can be widened into a vector load. And if
5574   // the address is "base + cst" see if the cst can be "absorbed" into
5575   // the shuffle mask.
5576   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5577     SDValue Ptr = LD->getBasePtr();
5578     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5579       return SDValue();
5580     EVT PVT = LD->getValueType(0);
5581     if (PVT != MVT::i32 && PVT != MVT::f32)
5582       return SDValue();
5583
5584     int FI = -1;
5585     int64_t Offset = 0;
5586     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5587       FI = FINode->getIndex();
5588       Offset = 0;
5589     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5590                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5591       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5592       Offset = Ptr.getConstantOperandVal(1);
5593       Ptr = Ptr.getOperand(0);
5594     } else {
5595       return SDValue();
5596     }
5597
5598     // FIXME: 256-bit vector instructions don't require a strict alignment,
5599     // improve this code to support it better.
5600     unsigned RequiredAlign = VT.getSizeInBits()/8;
5601     SDValue Chain = LD->getChain();
5602     // Make sure the stack object alignment is at least 16 or 32.
5603     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5604     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5605       if (MFI->isFixedObjectIndex(FI)) {
5606         // Can't change the alignment. FIXME: It's possible to compute
5607         // the exact stack offset and reference FI + adjust offset instead.
5608         // If someone *really* cares about this. That's the way to implement it.
5609         return SDValue();
5610       } else {
5611         MFI->setObjectAlignment(FI, RequiredAlign);
5612       }
5613     }
5614
5615     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5616     // Ptr + (Offset & ~15).
5617     if (Offset < 0)
5618       return SDValue();
5619     if ((Offset % RequiredAlign) & 3)
5620       return SDValue();
5621     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5622     if (StartOffset)
5623       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5624                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5625
5626     int EltNo = (Offset - StartOffset) >> 2;
5627     unsigned NumElems = VT.getVectorNumElements();
5628
5629     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5630     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5631                              LD->getPointerInfo().getWithOffset(StartOffset),
5632                              false, false, false, 0);
5633
5634     SmallVector<int, 8> Mask;
5635     for (unsigned i = 0; i != NumElems; ++i)
5636       Mask.push_back(EltNo);
5637
5638     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5639   }
5640
5641   return SDValue();
5642 }
5643
5644 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5645 /// vector of type 'VT', see if the elements can be replaced by a single large
5646 /// load which has the same value as a build_vector whose operands are 'elts'.
5647 ///
5648 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5649 ///
5650 /// FIXME: we'd also like to handle the case where the last elements are zero
5651 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5652 /// There's even a handy isZeroNode for that purpose.
5653 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5654                                         SDLoc &DL, SelectionDAG &DAG,
5655                                         bool isAfterLegalize) {
5656   EVT EltVT = VT.getVectorElementType();
5657   unsigned NumElems = Elts.size();
5658
5659   LoadSDNode *LDBase = nullptr;
5660   unsigned LastLoadedElt = -1U;
5661
5662   // For each element in the initializer, see if we've found a load or an undef.
5663   // If we don't find an initial load element, or later load elements are
5664   // non-consecutive, bail out.
5665   for (unsigned i = 0; i < NumElems; ++i) {
5666     SDValue Elt = Elts[i];
5667
5668     if (!Elt.getNode() ||
5669         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5670       return SDValue();
5671     if (!LDBase) {
5672       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5673         return SDValue();
5674       LDBase = cast<LoadSDNode>(Elt.getNode());
5675       LastLoadedElt = i;
5676       continue;
5677     }
5678     if (Elt.getOpcode() == ISD::UNDEF)
5679       continue;
5680
5681     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5682     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5683       return SDValue();
5684     LastLoadedElt = i;
5685   }
5686
5687   // If we have found an entire vector of loads and undefs, then return a large
5688   // load of the entire vector width starting at the base pointer.  If we found
5689   // consecutive loads for the low half, generate a vzext_load node.
5690   if (LastLoadedElt == NumElems - 1) {
5691
5692     if (isAfterLegalize &&
5693         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5694       return SDValue();
5695
5696     SDValue NewLd = SDValue();
5697
5698     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5699       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700                           LDBase->getPointerInfo(),
5701                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5702                           LDBase->isInvariant(), 0);
5703     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5704                         LDBase->getPointerInfo(),
5705                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5706                         LDBase->isInvariant(), LDBase->getAlignment());
5707
5708     if (LDBase->hasAnyUseOfValue(1)) {
5709       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5710                                      SDValue(LDBase, 1),
5711                                      SDValue(NewLd.getNode(), 1));
5712       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5713       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5714                              SDValue(NewLd.getNode(), 1));
5715     }
5716
5717     return NewLd;
5718   }
5719   if (NumElems == 4 && LastLoadedElt == 1 &&
5720       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5721     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5722     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5723     SDValue ResNode =
5724         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5725                                 LDBase->getPointerInfo(),
5726                                 LDBase->getAlignment(),
5727                                 false/*isVolatile*/, true/*ReadMem*/,
5728                                 false/*WriteMem*/);
5729
5730     // Make sure the newly-created LOAD is in the same position as LDBase in
5731     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5732     // update uses of LDBase's output chain to use the TokenFactor.
5733     if (LDBase->hasAnyUseOfValue(1)) {
5734       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5735                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5736       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5737       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5738                              SDValue(ResNode.getNode(), 1));
5739     }
5740
5741     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5742   }
5743   return SDValue();
5744 }
5745
5746 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5747 /// to generate a splat value for the following cases:
5748 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5749 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5750 /// a scalar load, or a constant.
5751 /// The VBROADCAST node is returned when a pattern is found,
5752 /// or SDValue() otherwise.
5753 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5754                                     SelectionDAG &DAG) {
5755   if (!Subtarget->hasFp256())
5756     return SDValue();
5757
5758   MVT VT = Op.getSimpleValueType();
5759   SDLoc dl(Op);
5760
5761   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5762          "Unsupported vector type for broadcast.");
5763
5764   SDValue Ld;
5765   bool ConstSplatVal;
5766
5767   switch (Op.getOpcode()) {
5768     default:
5769       // Unknown pattern found.
5770       return SDValue();
5771
5772     case ISD::BUILD_VECTOR: {
5773       // The BUILD_VECTOR node must be a splat.
5774       if (!isSplatVector(Op.getNode()))
5775         return SDValue();
5776
5777       Ld = Op.getOperand(0);
5778       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5779                      Ld.getOpcode() == ISD::ConstantFP);
5780
5781       // The suspected load node has several users. Make sure that all
5782       // of its users are from the BUILD_VECTOR node.
5783       // Constants may have multiple users.
5784       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5785         return SDValue();
5786       break;
5787     }
5788
5789     case ISD::VECTOR_SHUFFLE: {
5790       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5791
5792       // Shuffles must have a splat mask where the first element is
5793       // broadcasted.
5794       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5795         return SDValue();
5796
5797       SDValue Sc = Op.getOperand(0);
5798       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5799           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5800
5801         if (!Subtarget->hasInt256())
5802           return SDValue();
5803
5804         // Use the register form of the broadcast instruction available on AVX2.
5805         if (VT.getSizeInBits() >= 256)
5806           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5807         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5808       }
5809
5810       Ld = Sc.getOperand(0);
5811       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5812                        Ld.getOpcode() == ISD::ConstantFP);
5813
5814       // The scalar_to_vector node and the suspected
5815       // load node must have exactly one user.
5816       // Constants may have multiple users.
5817
5818       // AVX-512 has register version of the broadcast
5819       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5820         Ld.getValueType().getSizeInBits() >= 32;
5821       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822           !hasRegVer))
5823         return SDValue();
5824       break;
5825     }
5826   }
5827
5828   bool IsGE256 = (VT.getSizeInBits() >= 256);
5829
5830   // Handle the broadcasting a single constant scalar from the constant pool
5831   // into a vector. On Sandybridge it is still better to load a constant vector
5832   // from the constant pool and not to broadcast it from a scalar.
5833   if (ConstSplatVal && Subtarget->hasInt256()) {
5834     EVT CVT = Ld.getValueType();
5835     assert(!CVT.isVector() && "Must not broadcast a vector type");
5836     unsigned ScalarSize = CVT.getSizeInBits();
5837
5838     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5839       const Constant *C = nullptr;
5840       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5841         C = CI->getConstantIntValue();
5842       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5843         C = CF->getConstantFPValue();
5844
5845       assert(C && "Invalid constant type");
5846
5847       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5848       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5849       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5850       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5851                        MachinePointerInfo::getConstantPool(),
5852                        false, false, false, Alignment);
5853
5854       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5855     }
5856   }
5857
5858   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5859   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5860
5861   // Handle AVX2 in-register broadcasts.
5862   if (!IsLoad && Subtarget->hasInt256() &&
5863       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5864     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865
5866   // The scalar source must be a normal load.
5867   if (!IsLoad)
5868     return SDValue();
5869
5870   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5871     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872
5873   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5874   // double since there is no vbroadcastsd xmm
5875   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5876     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5877       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5878   }
5879
5880   // Unsupported broadcast.
5881   return SDValue();
5882 }
5883
5884 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5885 /// underlying vector and index.
5886 ///
5887 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5888 /// index.
5889 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5890                                          SDValue ExtIdx) {
5891   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5892   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5893     return Idx;
5894
5895   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5896   // lowered this:
5897   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5898   // to:
5899   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5900   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5901   //                           undef)
5902   //                       Constant<0>)
5903   // In this case the vector is the extract_subvector expression and the index
5904   // is 2, as specified by the shuffle.
5905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5906   SDValue ShuffleVec = SVOp->getOperand(0);
5907   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5908   assert(ShuffleVecVT.getVectorElementType() ==
5909          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5910
5911   int ShuffleIdx = SVOp->getMaskElt(Idx);
5912   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5913     ExtractedFromVec = ShuffleVec;
5914     return ShuffleIdx;
5915   }
5916   return Idx;
5917 }
5918
5919 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5920   MVT VT = Op.getSimpleValueType();
5921
5922   // Skip if insert_vec_elt is not supported.
5923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5925     return SDValue();
5926
5927   SDLoc DL(Op);
5928   unsigned NumElems = Op.getNumOperands();
5929
5930   SDValue VecIn1;
5931   SDValue VecIn2;
5932   SmallVector<unsigned, 4> InsertIndices;
5933   SmallVector<int, 8> Mask(NumElems, -1);
5934
5935   for (unsigned i = 0; i != NumElems; ++i) {
5936     unsigned Opc = Op.getOperand(i).getOpcode();
5937
5938     if (Opc == ISD::UNDEF)
5939       continue;
5940
5941     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5942       // Quit if more than 1 elements need inserting.
5943       if (InsertIndices.size() > 1)
5944         return SDValue();
5945
5946       InsertIndices.push_back(i);
5947       continue;
5948     }
5949
5950     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5951     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5952     // Quit if non-constant index.
5953     if (!isa<ConstantSDNode>(ExtIdx))
5954       return SDValue();
5955     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5956
5957     // Quit if extracted from vector of different type.
5958     if (ExtractedFromVec.getValueType() != VT)
5959       return SDValue();
5960
5961     if (!VecIn1.getNode())
5962       VecIn1 = ExtractedFromVec;
5963     else if (VecIn1 != ExtractedFromVec) {
5964       if (!VecIn2.getNode())
5965         VecIn2 = ExtractedFromVec;
5966       else if (VecIn2 != ExtractedFromVec)
5967         // Quit if more than 2 vectors to shuffle
5968         return SDValue();
5969     }
5970
5971     if (ExtractedFromVec == VecIn1)
5972       Mask[i] = Idx;
5973     else if (ExtractedFromVec == VecIn2)
5974       Mask[i] = Idx + NumElems;
5975   }
5976
5977   if (!VecIn1.getNode())
5978     return SDValue();
5979
5980   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5981   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5982   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5983     unsigned Idx = InsertIndices[i];
5984     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5985                      DAG.getIntPtrConstant(Idx));
5986   }
5987
5988   return NV;
5989 }
5990
5991 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5992 SDValue
5993 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5994
5995   MVT VT = Op.getSimpleValueType();
5996   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5997          "Unexpected type in LowerBUILD_VECTORvXi1!");
5998
5999   SDLoc dl(Op);
6000   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6001     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6002     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6004   }
6005
6006   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6007     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6008     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6009     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6010   }
6011
6012   bool AllContants = true;
6013   uint64_t Immediate = 0;
6014   int NonConstIdx = -1;
6015   bool IsSplat = true;
6016   unsigned NumNonConsts = 0;
6017   unsigned NumConsts = 0;
6018   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6019     SDValue In = Op.getOperand(idx);
6020     if (In.getOpcode() == ISD::UNDEF)
6021       continue;
6022     if (!isa<ConstantSDNode>(In)) {
6023       AllContants = false;
6024       NonConstIdx = idx;
6025       NumNonConsts++;
6026     }
6027     else {
6028       NumConsts++;
6029       if (cast<ConstantSDNode>(In)->getZExtValue())
6030       Immediate |= (1ULL << idx);
6031     }
6032     if (In != Op.getOperand(0))
6033       IsSplat = false;
6034   }
6035
6036   if (AllContants) {
6037     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6038       DAG.getConstant(Immediate, MVT::i16));
6039     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6040                        DAG.getIntPtrConstant(0));
6041   }
6042
6043   if (NumNonConsts == 1 && NonConstIdx != 0) {
6044     SDValue DstVec;
6045     if (NumConsts) {
6046       SDValue VecAsImm = DAG.getConstant(Immediate,
6047                                          MVT::getIntegerVT(VT.getSizeInBits()));
6048       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6049     }
6050     else 
6051       DstVec = DAG.getUNDEF(VT);
6052     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6053                        Op.getOperand(NonConstIdx),
6054                        DAG.getIntPtrConstant(NonConstIdx));
6055   }
6056   if (!IsSplat && (NonConstIdx != 0))
6057     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6058   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6059   SDValue Select;
6060   if (IsSplat)
6061     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6062                           DAG.getConstant(-1, SelectVT),
6063                           DAG.getConstant(0, SelectVT));
6064   else
6065     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6066                          DAG.getConstant((Immediate | 1), SelectVT),
6067                          DAG.getConstant(Immediate, SelectVT));
6068   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6069 }
6070
6071 /// \brief Return true if \p N implements a horizontal binop and return the
6072 /// operands for the horizontal binop into V0 and V1.
6073 /// 
6074 /// This is a helper function of PerformBUILD_VECTORCombine.
6075 /// This function checks that the build_vector \p N in input implements a
6076 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6077 /// operation to match.
6078 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6079 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6080 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6081 /// arithmetic sub.
6082 ///
6083 /// This function only analyzes elements of \p N whose indices are
6084 /// in range [BaseIdx, LastIdx).
6085 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6086                               SelectionDAG &DAG,
6087                               unsigned BaseIdx, unsigned LastIdx,
6088                               SDValue &V0, SDValue &V1) {
6089   EVT VT = N->getValueType(0);
6090
6091   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6092   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6093          "Invalid Vector in input!");
6094   
6095   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6096   bool CanFold = true;
6097   unsigned ExpectedVExtractIdx = BaseIdx;
6098   unsigned NumElts = LastIdx - BaseIdx;
6099   V0 = DAG.getUNDEF(VT);
6100   V1 = DAG.getUNDEF(VT);
6101
6102   // Check if N implements a horizontal binop.
6103   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6104     SDValue Op = N->getOperand(i + BaseIdx);
6105
6106     // Skip UNDEFs.
6107     if (Op->getOpcode() == ISD::UNDEF) {
6108       // Update the expected vector extract index.
6109       if (i * 2 == NumElts)
6110         ExpectedVExtractIdx = BaseIdx;
6111       ExpectedVExtractIdx += 2;
6112       continue;
6113     }
6114
6115     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6116
6117     if (!CanFold)
6118       break;
6119
6120     SDValue Op0 = Op.getOperand(0);
6121     SDValue Op1 = Op.getOperand(1);
6122
6123     // Try to match the following pattern:
6124     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6125     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127         Op0.getOperand(0) == Op1.getOperand(0) &&
6128         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6129         isa<ConstantSDNode>(Op1.getOperand(1)));
6130     if (!CanFold)
6131       break;
6132
6133     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6135
6136     if (i * 2 < NumElts) {
6137       if (V0.getOpcode() == ISD::UNDEF)
6138         V0 = Op0.getOperand(0);
6139     } else {
6140       if (V1.getOpcode() == ISD::UNDEF)
6141         V1 = Op0.getOperand(0);
6142       if (i * 2 == NumElts)
6143         ExpectedVExtractIdx = BaseIdx;
6144     }
6145
6146     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6147     if (I0 == ExpectedVExtractIdx)
6148       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6149     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6150       // Try to match the following dag sequence:
6151       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6152       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6153     } else
6154       CanFold = false;
6155
6156     ExpectedVExtractIdx += 2;
6157   }
6158
6159   return CanFold;
6160 }
6161
6162 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6163 /// a concat_vector. 
6164 ///
6165 /// This is a helper function of PerformBUILD_VECTORCombine.
6166 /// This function expects two 256-bit vectors called V0 and V1.
6167 /// At first, each vector is split into two separate 128-bit vectors.
6168 /// Then, the resulting 128-bit vectors are used to implement two
6169 /// horizontal binary operations. 
6170 ///
6171 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6172 ///
6173 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6174 /// the two new horizontal binop.
6175 /// When Mode is set, the first horizontal binop dag node would take as input
6176 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6177 /// horizontal binop dag node would take as input the lower 128-bit of V1
6178 /// and the upper 128-bit of V1.
6179 ///   Example:
6180 ///     HADD V0_LO, V0_HI
6181 ///     HADD V1_LO, V1_HI
6182 ///
6183 /// Otherwise, the first horizontal binop dag node takes as input the lower
6184 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6185 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6186 ///   Example:
6187 ///     HADD V0_LO, V1_LO
6188 ///     HADD V0_HI, V1_HI
6189 ///
6190 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6191 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6192 /// the upper 128-bits of the result.
6193 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6194                                      SDLoc DL, SelectionDAG &DAG,
6195                                      unsigned X86Opcode, bool Mode,
6196                                      bool isUndefLO, bool isUndefHI) {
6197   EVT VT = V0.getValueType();
6198   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6199          "Invalid nodes in input!");
6200
6201   unsigned NumElts = VT.getVectorNumElements();
6202   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6203   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6204   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6205   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6206   EVT NewVT = V0_LO.getValueType();
6207
6208   SDValue LO = DAG.getUNDEF(NewVT);
6209   SDValue HI = DAG.getUNDEF(NewVT);
6210
6211   if (Mode) {
6212     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6214       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6215     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6216       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6217   } else {
6218     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6219     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6220                        V1_LO->getOpcode() != ISD::UNDEF))
6221       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6222
6223     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6224                        V1_HI->getOpcode() != ISD::UNDEF))
6225       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6226   }
6227
6228   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6229 }
6230
6231 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6232 /// sequence of 'vadd + vsub + blendi'.
6233 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6234                            const X86Subtarget *Subtarget) {
6235   SDLoc DL(BV);
6236   EVT VT = BV->getValueType(0);
6237   unsigned NumElts = VT.getVectorNumElements();
6238   SDValue InVec0 = DAG.getUNDEF(VT);
6239   SDValue InVec1 = DAG.getUNDEF(VT);
6240
6241   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6242           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6243
6244   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6247     return SDValue();
6248
6249   // Odd-numbered elements in the input build vector are obtained from
6250   // adding two integer/float elements.
6251   // Even-numbered elements in the input build vector are obtained from
6252   // subtracting two integer/float elements.
6253   unsigned ExpectedOpcode = ISD::FSUB;
6254   unsigned NextExpectedOpcode = ISD::FADD;
6255   bool AddFound = false;
6256   bool SubFound = false;
6257
6258   for (unsigned i = 0, e = NumElts; i != e; i++) {
6259     SDValue Op = BV->getOperand(i);
6260       
6261     // Skip 'undef' values.
6262     unsigned Opcode = Op.getOpcode();
6263     if (Opcode == ISD::UNDEF) {
6264       std::swap(ExpectedOpcode, NextExpectedOpcode);
6265       continue;
6266     }
6267       
6268     // Early exit if we found an unexpected opcode.
6269     if (Opcode != ExpectedOpcode)
6270       return SDValue();
6271
6272     SDValue Op0 = Op.getOperand(0);
6273     SDValue Op1 = Op.getOperand(1);
6274
6275     // Try to match the following pattern:
6276     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6277     // Early exit if we cannot match that sequence.
6278     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6281         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6282         Op0.getOperand(1) != Op1.getOperand(1))
6283       return SDValue();
6284
6285     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6286     if (I0 != i)
6287       return SDValue();
6288
6289     // We found a valid add/sub node. Update the information accordingly.
6290     if (i & 1)
6291       AddFound = true;
6292     else
6293       SubFound = true;
6294
6295     // Update InVec0 and InVec1.
6296     if (InVec0.getOpcode() == ISD::UNDEF)
6297       InVec0 = Op0.getOperand(0);
6298     if (InVec1.getOpcode() == ISD::UNDEF)
6299       InVec1 = Op1.getOperand(0);
6300
6301     // Make sure that operands in input to each add/sub node always
6302     // come from a same pair of vectors.
6303     if (InVec0 != Op0.getOperand(0)) {
6304       if (ExpectedOpcode == ISD::FSUB)
6305         return SDValue();
6306
6307       // FADD is commutable. Try to commute the operands
6308       // and then test again.
6309       std::swap(Op0, Op1);
6310       if (InVec0 != Op0.getOperand(0))
6311         return SDValue();
6312     }
6313
6314     if (InVec1 != Op1.getOperand(0))
6315       return SDValue();
6316
6317     // Update the pair of expected opcodes.
6318     std::swap(ExpectedOpcode, NextExpectedOpcode);
6319   }
6320
6321   // Don't try to fold this build_vector into a VSELECT if it has
6322   // too many UNDEF operands.
6323   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6324       InVec1.getOpcode() != ISD::UNDEF) {
6325     // Emit a sequence of vector add and sub followed by a VSELECT.
6326     // The new VSELECT will be lowered into a BLENDI.
6327     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6328     // and emit a single ADDSUB instruction.
6329     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6330     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6331
6332     // Construct the VSELECT mask.
6333     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6334     EVT SVT = MaskVT.getVectorElementType();
6335     unsigned SVTBits = SVT.getSizeInBits();
6336     SmallVector<SDValue, 8> Ops;
6337
6338     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6339       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6340                             APInt::getAllOnesValue(SVTBits);
6341       SDValue Constant = DAG.getConstant(Value, SVT);
6342       Ops.push_back(Constant);
6343     }
6344
6345     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6346     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6347   }
6348   
6349   return SDValue();
6350 }
6351
6352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6353                                           const X86Subtarget *Subtarget) {
6354   SDLoc DL(N);
6355   EVT VT = N->getValueType(0);
6356   unsigned NumElts = VT.getVectorNumElements();
6357   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6358   SDValue InVec0, InVec1;
6359
6360   // Try to match an ADDSUB.
6361   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6362       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6363     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6364     if (Value.getNode())
6365       return Value;
6366   }
6367
6368   // Try to match horizontal ADD/SUB.
6369   unsigned NumUndefsLO = 0;
6370   unsigned NumUndefsHI = 0;
6371   unsigned Half = NumElts/2;
6372
6373   // Count the number of UNDEF operands in the build_vector in input.
6374   for (unsigned i = 0, e = Half; i != e; ++i)
6375     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6376       NumUndefsLO++;
6377
6378   for (unsigned i = Half, e = NumElts; i != e; ++i)
6379     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6380       NumUndefsHI++;
6381
6382   // Early exit if this is either a build_vector of all UNDEFs or all the
6383   // operands but one are UNDEF.
6384   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6385     return SDValue();
6386
6387   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6388     // Try to match an SSE3 float HADD/HSUB.
6389     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6390       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6391     
6392     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6393       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6394   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6395     // Try to match an SSSE3 integer HADD/HSUB.
6396     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6397       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6398     
6399     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6400       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6401   }
6402   
6403   if (!Subtarget->hasAVX())
6404     return SDValue();
6405
6406   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6407     // Try to match an AVX horizontal add/sub of packed single/double
6408     // precision floating point values from 256-bit vectors.
6409     SDValue InVec2, InVec3;
6410     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6411         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6412         ((InVec0.getOpcode() == ISD::UNDEF ||
6413           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6414         ((InVec1.getOpcode() == ISD::UNDEF ||
6415           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6416       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6417
6418     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6419         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6420         ((InVec0.getOpcode() == ISD::UNDEF ||
6421           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6422         ((InVec1.getOpcode() == ISD::UNDEF ||
6423           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6424       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6425   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6426     // Try to match an AVX2 horizontal add/sub of signed integers.
6427     SDValue InVec2, InVec3;
6428     unsigned X86Opcode;
6429     bool CanFold = true;
6430
6431     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6432         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6433         ((InVec0.getOpcode() == ISD::UNDEF ||
6434           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435         ((InVec1.getOpcode() == ISD::UNDEF ||
6436           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437       X86Opcode = X86ISD::HADD;
6438     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6439         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6440         ((InVec0.getOpcode() == ISD::UNDEF ||
6441           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6442         ((InVec1.getOpcode() == ISD::UNDEF ||
6443           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6444       X86Opcode = X86ISD::HSUB;
6445     else
6446       CanFold = false;
6447
6448     if (CanFold) {
6449       // Fold this build_vector into a single horizontal add/sub.
6450       // Do this only if the target has AVX2.
6451       if (Subtarget->hasAVX2())
6452         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6453  
6454       // Do not try to expand this build_vector into a pair of horizontal
6455       // add/sub if we can emit a pair of scalar add/sub.
6456       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6457         return SDValue();
6458
6459       // Convert this build_vector into a pair of horizontal binop followed by
6460       // a concat vector.
6461       bool isUndefLO = NumUndefsLO == Half;
6462       bool isUndefHI = NumUndefsHI == Half;
6463       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6464                                    isUndefLO, isUndefHI);
6465     }
6466   }
6467
6468   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6469        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6470     unsigned X86Opcode;
6471     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6472       X86Opcode = X86ISD::HADD;
6473     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6474       X86Opcode = X86ISD::HSUB;
6475     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6476       X86Opcode = X86ISD::FHADD;
6477     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6478       X86Opcode = X86ISD::FHSUB;
6479     else
6480       return SDValue();
6481
6482     // Don't try to expand this build_vector into a pair of horizontal add/sub
6483     // if we can simply emit a pair of scalar add/sub.
6484     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6485       return SDValue();
6486
6487     // Convert this build_vector into two horizontal add/sub followed by
6488     // a concat vector.
6489     bool isUndefLO = NumUndefsLO == Half;
6490     bool isUndefHI = NumUndefsHI == Half;
6491     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6492                                  isUndefLO, isUndefHI);
6493   }
6494
6495   return SDValue();
6496 }
6497
6498 SDValue
6499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6500   SDLoc dl(Op);
6501
6502   MVT VT = Op.getSimpleValueType();
6503   MVT ExtVT = VT.getVectorElementType();
6504   unsigned NumElems = Op.getNumOperands();
6505
6506   // Generate vectors for predicate vectors.
6507   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6508     return LowerBUILD_VECTORvXi1(Op, DAG);
6509
6510   // Vectors containing all zeros can be matched by pxor and xorps later
6511   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6512     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6513     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6514     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6515       return Op;
6516
6517     return getZeroVector(VT, Subtarget, DAG, dl);
6518   }
6519
6520   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6521   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6522   // vpcmpeqd on 256-bit vectors.
6523   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6524     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6525       return Op;
6526
6527     if (!VT.is512BitVector())
6528       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6529   }
6530
6531   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6532   if (Broadcast.getNode())
6533     return Broadcast;
6534
6535   unsigned EVTBits = ExtVT.getSizeInBits();
6536
6537   unsigned NumZero  = 0;
6538   unsigned NumNonZero = 0;
6539   unsigned NonZeros = 0;
6540   bool IsAllConstants = true;
6541   SmallSet<SDValue, 8> Values;
6542   for (unsigned i = 0; i < NumElems; ++i) {
6543     SDValue Elt = Op.getOperand(i);
6544     if (Elt.getOpcode() == ISD::UNDEF)
6545       continue;
6546     Values.insert(Elt);
6547     if (Elt.getOpcode() != ISD::Constant &&
6548         Elt.getOpcode() != ISD::ConstantFP)
6549       IsAllConstants = false;
6550     if (X86::isZeroNode(Elt))
6551       NumZero++;
6552     else {
6553       NonZeros |= (1 << i);
6554       NumNonZero++;
6555     }
6556   }
6557
6558   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6559   if (NumNonZero == 0)
6560     return DAG.getUNDEF(VT);
6561
6562   // Special case for single non-zero, non-undef, element.
6563   if (NumNonZero == 1) {
6564     unsigned Idx = countTrailingZeros(NonZeros);
6565     SDValue Item = Op.getOperand(Idx);
6566
6567     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6568     // the value are obviously zero, truncate the value to i32 and do the
6569     // insertion that way.  Only do this if the value is non-constant or if the
6570     // value is a constant being inserted into element 0.  It is cheaper to do
6571     // a constant pool load than it is to do a movd + shuffle.
6572     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6573         (!IsAllConstants || Idx == 0)) {
6574       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6575         // Handle SSE only.
6576         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6577         EVT VecVT = MVT::v4i32;
6578         unsigned VecElts = 4;
6579
6580         // Truncate the value (which may itself be a constant) to i32, and
6581         // convert it to a vector with movd (S2V+shuffle to zero extend).
6582         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6583         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6584         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6585
6586         // Now we have our 32-bit value zero extended in the low element of
6587         // a vector.  If Idx != 0, swizzle it into place.
6588         if (Idx != 0) {
6589           SmallVector<int, 4> Mask;
6590           Mask.push_back(Idx);
6591           for (unsigned i = 1; i != VecElts; ++i)
6592             Mask.push_back(i);
6593           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6594                                       &Mask[0]);
6595         }
6596         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6597       }
6598     }
6599
6600     // If we have a constant or non-constant insertion into the low element of
6601     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6602     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6603     // depending on what the source datatype is.
6604     if (Idx == 0) {
6605       if (NumZero == 0)
6606         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6607
6608       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6609           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6610         if (VT.is256BitVector() || VT.is512BitVector()) {
6611           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6612           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6613                              Item, DAG.getIntPtrConstant(0));
6614         }
6615         assert(VT.is128BitVector() && "Expected an SSE value type!");
6616         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6617         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6618         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6619       }
6620
6621       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6622         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6623         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6624         if (VT.is256BitVector()) {
6625           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6626           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6627         } else {
6628           assert(VT.is128BitVector() && "Expected an SSE value type!");
6629           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6630         }
6631         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6632       }
6633     }
6634
6635     // Is it a vector logical left shift?
6636     if (NumElems == 2 && Idx == 1 &&
6637         X86::isZeroNode(Op.getOperand(0)) &&
6638         !X86::isZeroNode(Op.getOperand(1))) {
6639       unsigned NumBits = VT.getSizeInBits();
6640       return getVShift(true, VT,
6641                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6642                                    VT, Op.getOperand(1)),
6643                        NumBits/2, DAG, *this, dl);
6644     }
6645
6646     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6647       return SDValue();
6648
6649     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6650     // is a non-constant being inserted into an element other than the low one,
6651     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6652     // movd/movss) to move this into the low element, then shuffle it into
6653     // place.
6654     if (EVTBits == 32) {
6655       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6656
6657       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6658       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6659       SmallVector<int, 8> MaskVec;
6660       for (unsigned i = 0; i != NumElems; ++i)
6661         MaskVec.push_back(i == Idx ? 0 : 1);
6662       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6663     }
6664   }
6665
6666   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6667   if (Values.size() == 1) {
6668     if (EVTBits == 32) {
6669       // Instead of a shuffle like this:
6670       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6671       // Check if it's possible to issue this instead.
6672       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6673       unsigned Idx = countTrailingZeros(NonZeros);
6674       SDValue Item = Op.getOperand(Idx);
6675       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6676         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6677     }
6678     return SDValue();
6679   }
6680
6681   // A vector full of immediates; various special cases are already
6682   // handled, so this is best done with a single constant-pool load.
6683   if (IsAllConstants)
6684     return SDValue();
6685
6686   // For AVX-length vectors, build the individual 128-bit pieces and use
6687   // shuffles to put them in place.
6688   if (VT.is256BitVector() || VT.is512BitVector()) {
6689     SmallVector<SDValue, 64> V;
6690     for (unsigned i = 0; i != NumElems; ++i)
6691       V.push_back(Op.getOperand(i));
6692
6693     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6694
6695     // Build both the lower and upper subvector.
6696     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6697                                 makeArrayRef(&V[0], NumElems/2));
6698     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6699                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6700
6701     // Recreate the wider vector with the lower and upper part.
6702     if (VT.is256BitVector())
6703       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6704     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6705   }
6706
6707   // Let legalizer expand 2-wide build_vectors.
6708   if (EVTBits == 64) {
6709     if (NumNonZero == 1) {
6710       // One half is zero or undef.
6711       unsigned Idx = countTrailingZeros(NonZeros);
6712       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6713                                  Op.getOperand(Idx));
6714       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6715     }
6716     return SDValue();
6717   }
6718
6719   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6720   if (EVTBits == 8 && NumElems == 16) {
6721     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6722                                         Subtarget, *this);
6723     if (V.getNode()) return V;
6724   }
6725
6726   if (EVTBits == 16 && NumElems == 8) {
6727     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6728                                       Subtarget, *this);
6729     if (V.getNode()) return V;
6730   }
6731
6732   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6733   if (EVTBits == 32 && NumElems == 4) {
6734     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6735                                       NumZero, DAG, Subtarget, *this);
6736     if (V.getNode())
6737       return V;
6738   }
6739
6740   // If element VT is == 32 bits, turn it into a number of shuffles.
6741   SmallVector<SDValue, 8> V(NumElems);
6742   if (NumElems == 4 && NumZero > 0) {
6743     for (unsigned i = 0; i < 4; ++i) {
6744       bool isZero = !(NonZeros & (1 << i));
6745       if (isZero)
6746         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6747       else
6748         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6749     }
6750
6751     for (unsigned i = 0; i < 2; ++i) {
6752       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6753         default: break;
6754         case 0:
6755           V[i] = V[i*2];  // Must be a zero vector.
6756           break;
6757         case 1:
6758           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6759           break;
6760         case 2:
6761           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6762           break;
6763         case 3:
6764           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6765           break;
6766       }
6767     }
6768
6769     bool Reverse1 = (NonZeros & 0x3) == 2;
6770     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6771     int MaskVec[] = {
6772       Reverse1 ? 1 : 0,
6773       Reverse1 ? 0 : 1,
6774       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6775       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6776     };
6777     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6778   }
6779
6780   if (Values.size() > 1 && VT.is128BitVector()) {
6781     // Check for a build vector of consecutive loads.
6782     for (unsigned i = 0; i < NumElems; ++i)
6783       V[i] = Op.getOperand(i);
6784
6785     // Check for elements which are consecutive loads.
6786     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6787     if (LD.getNode())
6788       return LD;
6789
6790     // Check for a build vector from mostly shuffle plus few inserting.
6791     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6792     if (Sh.getNode())
6793       return Sh;
6794
6795     // For SSE 4.1, use insertps to put the high elements into the low element.
6796     if (getSubtarget()->hasSSE41()) {
6797       SDValue Result;
6798       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6799         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6800       else
6801         Result = DAG.getUNDEF(VT);
6802
6803       for (unsigned i = 1; i < NumElems; ++i) {
6804         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6805         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6806                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6807       }
6808       return Result;
6809     }
6810
6811     // Otherwise, expand into a number of unpckl*, start by extending each of
6812     // our (non-undef) elements to the full vector width with the element in the
6813     // bottom slot of the vector (which generates no code for SSE).
6814     for (unsigned i = 0; i < NumElems; ++i) {
6815       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6816         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6817       else
6818         V[i] = DAG.getUNDEF(VT);
6819     }
6820
6821     // Next, we iteratively mix elements, e.g. for v4f32:
6822     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6823     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6824     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6825     unsigned EltStride = NumElems >> 1;
6826     while (EltStride != 0) {
6827       for (unsigned i = 0; i < EltStride; ++i) {
6828         // If V[i+EltStride] is undef and this is the first round of mixing,
6829         // then it is safe to just drop this shuffle: V[i] is already in the
6830         // right place, the one element (since it's the first round) being
6831         // inserted as undef can be dropped.  This isn't safe for successive
6832         // rounds because they will permute elements within both vectors.
6833         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6834             EltStride == NumElems/2)
6835           continue;
6836
6837         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6838       }
6839       EltStride >>= 1;
6840     }
6841     return V[0];
6842   }
6843   return SDValue();
6844 }
6845
6846 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6847 // to create 256-bit vectors from two other 128-bit ones.
6848 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6849   SDLoc dl(Op);
6850   MVT ResVT = Op.getSimpleValueType();
6851
6852   assert((ResVT.is256BitVector() ||
6853           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6854
6855   SDValue V1 = Op.getOperand(0);
6856   SDValue V2 = Op.getOperand(1);
6857   unsigned NumElems = ResVT.getVectorNumElements();
6858   if(ResVT.is256BitVector())
6859     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6860
6861   if (Op.getNumOperands() == 4) {
6862     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6863                                 ResVT.getVectorNumElements()/2);
6864     SDValue V3 = Op.getOperand(2);
6865     SDValue V4 = Op.getOperand(3);
6866     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6867       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6868   }
6869   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6870 }
6871
6872 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6874   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6875          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6876           Op.getNumOperands() == 4)));
6877
6878   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6879   // from two other 128-bit ones.
6880
6881   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6882   return LowerAVXCONCAT_VECTORS(Op, DAG);
6883 }
6884
6885
6886 //===----------------------------------------------------------------------===//
6887 // Vector shuffle lowering
6888 //
6889 // This is an experimental code path for lowering vector shuffles on x86. It is
6890 // designed to handle arbitrary vector shuffles and blends, gracefully
6891 // degrading performance as necessary. It works hard to recognize idiomatic
6892 // shuffles and lower them to optimal instruction patterns without leaving
6893 // a framework that allows reasonably efficient handling of all vector shuffle
6894 // patterns.
6895 //===----------------------------------------------------------------------===//
6896
6897 /// \brief Tiny helper function to identify a no-op mask.
6898 ///
6899 /// This is a somewhat boring predicate function. It checks whether the mask
6900 /// array input, which is assumed to be a single-input shuffle mask of the kind
6901 /// used by the X86 shuffle instructions (not a fully general
6902 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6903 /// in-place shuffle are 'no-op's.
6904 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906     if (Mask[i] != -1 && Mask[i] != i)
6907       return false;
6908   return true;
6909 }
6910
6911 /// \brief Helper function to classify a mask as a single-input mask.
6912 ///
6913 /// This isn't a generic single-input test because in the vector shuffle
6914 /// lowering we canonicalize single inputs to be the first input operand. This
6915 /// means we can more quickly test for a single input by only checking whether
6916 /// an input from the second operand exists. We also assume that the size of
6917 /// mask corresponds to the size of the input vectors which isn't true in the
6918 /// fully general case.
6919 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6920   for (int M : Mask)
6921     if (M >= (int)Mask.size())
6922       return false;
6923   return true;
6924 }
6925
6926 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6927 ///
6928 /// This helper function produces an 8-bit shuffle immediate corresponding to
6929 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6930 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6931 /// example.
6932 ///
6933 /// NB: We rely heavily on "undef" masks preserving the input lane.
6934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6935                                           SelectionDAG &DAG) {
6936   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6937   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6938   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6939   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6940   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6941
6942   unsigned Imm = 0;
6943   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6944   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6945   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6946   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6947   return DAG.getConstant(Imm, MVT::i8);
6948 }
6949
6950 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6951 ///
6952 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6953 /// support for floating point shuffles but not integer shuffles. These
6954 /// instructions will incur a domain crossing penalty on some chips though so
6955 /// it is better to avoid lowering through this for integer vectors where
6956 /// possible.
6957 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6958                                        const X86Subtarget *Subtarget,
6959                                        SelectionDAG &DAG) {
6960   SDLoc DL(Op);
6961   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6962   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6965   ArrayRef<int> Mask = SVOp->getMask();
6966   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6967
6968   if (isSingleInputShuffleMask(Mask)) {
6969     // Straight shuffle of a single input vector. Simulate this by using the
6970     // single input as both of the "inputs" to this instruction..
6971     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6972     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6973                        DAG.getConstant(SHUFPDMask, MVT::i8));
6974   }
6975   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6976   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6977
6978   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6979   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6980                      DAG.getConstant(SHUFPDMask, MVT::i8));
6981 }
6982
6983 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6984 ///
6985 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6986 /// the integer unit to minimize domain crossing penalties. However, for blends
6987 /// it falls back to the floating point shuffle operation with appropriate bit
6988 /// casting.
6989 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6990                                        const X86Subtarget *Subtarget,
6991                                        SelectionDAG &DAG) {
6992   SDLoc DL(Op);
6993   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6994   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6997   ArrayRef<int> Mask = SVOp->getMask();
6998   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6999
7000   if (isSingleInputShuffleMask(Mask)) {
7001     // Straight shuffle of a single input vector. For everything from SSE2
7002     // onward this has a single fast instruction with no scary immediates.
7003     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7004     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7005     int WidenedMask[4] = {
7006         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7007         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7008     return DAG.getNode(
7009         ISD::BITCAST, DL, MVT::v2i64,
7010         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7011                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7012   }
7013
7014   // We implement this with SHUFPD which is pretty lame because it will likely
7015   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7016   // However, all the alternatives are still more cycles and newer chips don't
7017   // have this problem. It would be really nice if x86 had better shuffles here.
7018   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7019   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7020   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7021                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7022 }
7023
7024 /// \brief Lower 4-lane 32-bit floating point shuffles.
7025 ///
7026 /// Uses instructions exclusively from the floating point unit to minimize
7027 /// domain crossing penalties, as these are sufficient to implement all v4f32
7028 /// shuffles.
7029 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7030                                        const X86Subtarget *Subtarget,
7031                                        SelectionDAG &DAG) {
7032   SDLoc DL(Op);
7033   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7034   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7037   ArrayRef<int> Mask = SVOp->getMask();
7038   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7039
7040   SDValue LowV = V1, HighV = V2;
7041   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7042
7043   int NumV2Elements =
7044       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7045
7046   if (NumV2Elements == 0)
7047     // Straight shuffle of a single input vector. We pass the input vector to
7048     // both operands to simulate this with a SHUFPS.
7049     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7050                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7051
7052   if (NumV2Elements == 1) {
7053     int V2Index =
7054         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7055         Mask.begin();
7056     // Compute the index adjacent to V2Index and in the same half by toggling
7057     // the low bit.
7058     int V2AdjIndex = V2Index ^ 1;
7059
7060     if (Mask[V2AdjIndex] == -1) {
7061       // Handles all the cases where we have a single V2 element and an undef.
7062       // This will only ever happen in the high lanes because we commute the
7063       // vector otherwise.
7064       if (V2Index < 2)
7065         std::swap(LowV, HighV);
7066       NewMask[V2Index] -= 4;
7067     } else {
7068       // Handle the case where the V2 element ends up adjacent to a V1 element.
7069       // To make this work, blend them together as the first step.
7070       int V1Index = V2AdjIndex;
7071       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7072       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7073                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7074
7075       // Now proceed to reconstruct the final blend as we have the necessary
7076       // high or low half formed.
7077       if (V2Index < 2) {
7078         LowV = V2;
7079         HighV = V1;
7080       } else {
7081         HighV = V2;
7082       }
7083       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7084       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7085     }
7086   } else if (NumV2Elements == 2) {
7087     if (Mask[0] < 4 && Mask[1] < 4) {
7088       // Handle the easy case where we have V1 in the low lanes and V2 in the
7089       // high lanes. We never see this reversed because we sort the shuffle.
7090       NewMask[2] -= 4;
7091       NewMask[3] -= 4;
7092     } else {
7093       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7094       // trying to place elements directly, just blend them and set up the final
7095       // shuffle to place them.
7096
7097       // The first two blend mask elements are for V1, the second two are for
7098       // V2.
7099       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7100                           Mask[2] < 4 ? Mask[2] : Mask[3],
7101                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7102                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7103       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7104                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7105
7106       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7107       // a blend.
7108       HighV = V1;
7109       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7110       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7111       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7112       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7113     }
7114   }
7115   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7116                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7117 }
7118
7119 /// \brief Lower 4-lane i32 vector shuffles.
7120 ///
7121 /// We try to handle these with integer-domain shuffles where we can, but for
7122 /// blends we use the floating point domain blend instructions.
7123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7124                                        const X86Subtarget *Subtarget,
7125                                        SelectionDAG &DAG) {
7126   SDLoc DL(Op);
7127   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7128   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   ArrayRef<int> Mask = SVOp->getMask();
7132   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7133
7134   if (isSingleInputShuffleMask(Mask))
7135     // Straight shuffle of a single input vector. For everything from SSE2
7136     // onward this has a single fast instruction with no scary immediates.
7137     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7138                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7139
7140   // We implement this with SHUFPS because it can blend from two vectors.
7141   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7142   // up the inputs, bypassing domain shift penalties that we would encur if we
7143   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7144   // relevant.
7145   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7146                      DAG.getVectorShuffle(
7147                          MVT::v4f32, DL,
7148                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7149                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7150 }
7151
7152 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7153 /// shuffle lowering, and the most complex part.
7154 ///
7155 /// The lowering strategy is to try to form pairs of input lanes which are
7156 /// targeted at the same half of the final vector, and then use a dword shuffle
7157 /// to place them onto the right half, and finally unpack the paired lanes into
7158 /// their final position.
7159 ///
7160 /// The exact breakdown of how to form these dword pairs and align them on the
7161 /// correct sides is really tricky. See the comments within the function for
7162 /// more of the details.
7163 static SDValue lowerV8I16SingleInputVectorShuffle(
7164     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7165     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7166   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7167   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7168   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7169
7170   SmallVector<int, 4> LoInputs;
7171   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7172                [](int M) { return M >= 0; });
7173   std::sort(LoInputs.begin(), LoInputs.end());
7174   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7175   SmallVector<int, 4> HiInputs;
7176   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7177                [](int M) { return M >= 0; });
7178   std::sort(HiInputs.begin(), HiInputs.end());
7179   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7180   int NumLToL =
7181       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7182   int NumHToL = LoInputs.size() - NumLToL;
7183   int NumLToH =
7184       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7185   int NumHToH = HiInputs.size() - NumLToH;
7186   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7187   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7188   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7189   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7190
7191   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7192   // such inputs we can swap two of the dwords across the half mark and end up
7193   // with <=2 inputs to each half in each half. Once there, we can fall through
7194   // to the generic code below. For example:
7195   //
7196   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7197   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7198   //
7199   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7200   // and 2-2.
7201   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7202                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7203     // Compute the index of dword with only one word among the three inputs in
7204     // a half by taking the sum of the half with three inputs and subtracting
7205     // the sum of the actual three inputs. The difference is the remaining
7206     // slot.
7207     int DWordA = (ThreeInputHalfSum -
7208                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7209                  2;
7210     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7211
7212     int PSHUFDMask[] = {0, 1, 2, 3};
7213     PSHUFDMask[DWordA] = DWordB;
7214     PSHUFDMask[DWordB] = DWordA;
7215     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7216                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7217                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7218                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7219
7220     // Adjust the mask to match the new locations of A and B.
7221     for (int &M : Mask)
7222       if (M != -1 && M/2 == DWordA)
7223         M = 2 * DWordB + M % 2;
7224       else if (M != -1 && M/2 == DWordB)
7225         M = 2 * DWordA + M % 2;
7226
7227     // Recurse back into this routine to re-compute state now that this isn't
7228     // a 3 and 1 problem.
7229     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7230                                 Mask);
7231   };
7232   if (NumLToL == 3 && NumHToL == 1)
7233     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7234   else if (NumLToL == 1 && NumHToL == 3)
7235     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7236   else if (NumLToH == 1 && NumHToH == 3)
7237     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7238   else if (NumLToH == 3 && NumHToH == 1)
7239     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7240
7241   // At this point there are at most two inputs to the low and high halves from
7242   // each half. That means the inputs can always be grouped into dwords and
7243   // those dwords can then be moved to the correct half with a dword shuffle.
7244   // We use at most one low and one high word shuffle to collect these paired
7245   // inputs into dwords, and finally a dword shuffle to place them.
7246   int PSHUFLMask[4] = {-1, -1, -1, -1};
7247   int PSHUFHMask[4] = {-1, -1, -1, -1};
7248   int PSHUFDMask[4] = {-1, -1, -1, -1};
7249
7250   // First fix the masks for all the inputs that are staying in their
7251   // original halves. This will then dictate the targets of the cross-half
7252   // shuffles.
7253   auto fixInPlaceInputs = [&PSHUFDMask](
7254       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7255       MutableArrayRef<int> HalfMask, int HalfOffset) {
7256     if (InPlaceInputs.empty())
7257       return;
7258     if (InPlaceInputs.size() == 1) {
7259       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7260           InPlaceInputs[0] - HalfOffset;
7261       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7262       return;
7263     }
7264
7265     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7266     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7267         InPlaceInputs[0] - HalfOffset;
7268     // Put the second input next to the first so that they are packed into
7269     // a dword. We find the adjacent index by toggling the low bit.
7270     int AdjIndex = InPlaceInputs[0] ^ 1;
7271     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7272     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7273     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7274   };
7275   if (!HToLInputs.empty())
7276     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7277   if (!LToHInputs.empty())
7278     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7279
7280   // Now gather the cross-half inputs and place them into a free dword of
7281   // their target half.
7282   // FIXME: This operation could almost certainly be simplified dramatically to
7283   // look more like the 3-1 fixing operation.
7284   auto moveInputsToRightHalf = [&PSHUFDMask](
7285       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7286       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7287       int SourceOffset, int DestOffset) {
7288     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7289       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7290     };
7291     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7292                                                int Word) {
7293       int LowWord = Word & ~1;
7294       int HighWord = Word | 1;
7295       return isWordClobbered(SourceHalfMask, LowWord) ||
7296              isWordClobbered(SourceHalfMask, HighWord);
7297     };
7298
7299     if (IncomingInputs.empty())
7300       return;
7301
7302     if (ExistingInputs.empty()) {
7303       // Map any dwords with inputs from them into the right half.
7304       for (int Input : IncomingInputs) {
7305         // If the source half mask maps over the inputs, turn those into
7306         // swaps and use the swapped lane.
7307         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7308           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7309             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7310                 Input - SourceOffset;
7311             // We have to swap the uses in our half mask in one sweep.
7312             for (int &M : HalfMask)
7313               if (M == SourceHalfMask[Input - SourceOffset])
7314                 M = Input;
7315               else if (M == Input)
7316                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7317           } else {
7318             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7319                        Input - SourceOffset &&
7320                    "Previous placement doesn't match!");
7321           }
7322           // Note that this correctly re-maps both when we do a swap and when
7323           // we observe the other side of the swap above. We rely on that to
7324           // avoid swapping the members of the input list directly.
7325           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7326         }
7327
7328         // Map the input's dword into the correct half.
7329         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7330           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7331         else
7332           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7333                      Input / 2 &&
7334                  "Previous placement doesn't match!");
7335       }
7336
7337       // And just directly shift any other-half mask elements to be same-half
7338       // as we will have mirrored the dword containing the element into the
7339       // same position within that half.
7340       for (int &M : HalfMask)
7341         if (M >= SourceOffset && M < SourceOffset + 4) {
7342           M = M - SourceOffset + DestOffset;
7343           assert(M >= 0 && "This should never wrap below zero!");
7344         }
7345       return;
7346     }
7347
7348     // Ensure we have the input in a viable dword of its current half. This
7349     // is particularly tricky because the original position may be clobbered
7350     // by inputs being moved and *staying* in that half.
7351     if (IncomingInputs.size() == 1) {
7352       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7353         int InputFixed = std::find(std::begin(SourceHalfMask),
7354                                    std::end(SourceHalfMask), -1) -
7355                          std::begin(SourceHalfMask) + SourceOffset;
7356         SourceHalfMask[InputFixed - SourceOffset] =
7357             IncomingInputs[0] - SourceOffset;
7358         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7359                      InputFixed);
7360         IncomingInputs[0] = InputFixed;
7361       }
7362     } else if (IncomingInputs.size() == 2) {
7363       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7364           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7365         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7366         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7367                "Not all dwords can be clobbered!");
7368         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7369         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7370         for (int &M : HalfMask)
7371           if (M == IncomingInputs[0])
7372             M = SourceDWordBase + SourceOffset;
7373           else if (M == IncomingInputs[1])
7374             M = SourceDWordBase + 1 + SourceOffset;
7375         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7376         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7377       }
7378     } else {
7379       llvm_unreachable("Unhandled input size!");
7380     }
7381
7382     // Now hoist the DWord down to the right half.
7383     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7384     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7385     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7386     for (int Input : IncomingInputs)
7387       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7388                    FreeDWord * 2 + Input % 2);
7389   };
7390   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7391                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7392   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7393                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7394
7395   // Now enact all the shuffles we've computed to move the inputs into their
7396   // target half.
7397   if (!isNoopShuffleMask(PSHUFLMask))
7398     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7399                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7400   if (!isNoopShuffleMask(PSHUFHMask))
7401     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7402                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7403   if (!isNoopShuffleMask(PSHUFDMask))
7404     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7405                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7406                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7407                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7408
7409   // At this point, each half should contain all its inputs, and we can then
7410   // just shuffle them into their final position.
7411   assert(std::count_if(LoMask.begin(), LoMask.end(),
7412                        [](int M) { return M >= 4; }) == 0 &&
7413          "Failed to lift all the high half inputs to the low mask!");
7414   assert(std::count_if(HiMask.begin(), HiMask.end(),
7415                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7416          "Failed to lift all the low half inputs to the high mask!");
7417
7418   // Do a half shuffle for the low mask.
7419   if (!isNoopShuffleMask(LoMask))
7420     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7421                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7422
7423   // Do a half shuffle with the high mask after shifting its values down.
7424   for (int &M : HiMask)
7425     if (M >= 0)
7426       M -= 4;
7427   if (!isNoopShuffleMask(HiMask))
7428     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7429                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7430
7431   return V;
7432 }
7433
7434 /// \brief Detect whether the mask pattern should be lowered through
7435 /// interleaving.
7436 ///
7437 /// This essentially tests whether viewing the mask as an interleaving of two
7438 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7439 /// lowering it through interleaving is a significantly better strategy.
7440 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7441   int NumEvenInputs[2] = {0, 0};
7442   int NumOddInputs[2] = {0, 0};
7443   int NumLoInputs[2] = {0, 0};
7444   int NumHiInputs[2] = {0, 0};
7445   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7446     if (Mask[i] < 0)
7447       continue;
7448
7449     int InputIdx = Mask[i] >= Size;
7450
7451     if (i < Size / 2)
7452       ++NumLoInputs[InputIdx];
7453     else
7454       ++NumHiInputs[InputIdx];
7455
7456     if ((i % 2) == 0)
7457       ++NumEvenInputs[InputIdx];
7458     else
7459       ++NumOddInputs[InputIdx];
7460   }
7461
7462   // The minimum number of cross-input results for both the interleaved and
7463   // split cases. If interleaving results in fewer cross-input results, return
7464   // true.
7465   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7466                                     NumEvenInputs[0] + NumOddInputs[1]);
7467   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7468                               NumLoInputs[0] + NumHiInputs[1]);
7469   return InterleavedCrosses < SplitCrosses;
7470 }
7471
7472 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7473 ///
7474 /// This strategy only works when the inputs from each vector fit into a single
7475 /// half of that vector, and generally there are not so many inputs as to leave
7476 /// the in-place shuffles required highly constrained (and thus expensive). It
7477 /// shifts all the inputs into a single side of both input vectors and then
7478 /// uses an unpack to interleave these inputs in a single vector. At that
7479 /// point, we will fall back on the generic single input shuffle lowering.
7480 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7481                                                  SDValue V2,
7482                                                  MutableArrayRef<int> Mask,
7483                                                  const X86Subtarget *Subtarget,
7484                                                  SelectionDAG &DAG) {
7485   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7486   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7488   for (int i = 0; i < 8; ++i)
7489     if (Mask[i] >= 0 && Mask[i] < 4)
7490       LoV1Inputs.push_back(i);
7491     else if (Mask[i] >= 4 && Mask[i] < 8)
7492       HiV1Inputs.push_back(i);
7493     else if (Mask[i] >= 8 && Mask[i] < 12)
7494       LoV2Inputs.push_back(i);
7495     else if (Mask[i] >= 12)
7496       HiV2Inputs.push_back(i);
7497
7498   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7499   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7500   (void)NumV1Inputs;
7501   (void)NumV2Inputs;
7502   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7503   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7504   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7505
7506   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7507                      HiV1Inputs.size() + HiV2Inputs.size();
7508
7509   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7510                               ArrayRef<int> HiInputs, bool MoveToLo,
7511                               int MaskOffset) {
7512     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7513     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7514     if (BadInputs.empty())
7515       return V;
7516
7517     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7518     int MoveOffset = MoveToLo ? 0 : 4;
7519
7520     if (GoodInputs.empty()) {
7521       for (int BadInput : BadInputs) {
7522         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7523         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7524       }
7525     } else {
7526       if (GoodInputs.size() == 2) {
7527         // If the low inputs are spread across two dwords, pack them into
7528         // a single dword.
7529         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7530             Mask[GoodInputs[0]] - MaskOffset;
7531         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7532             Mask[GoodInputs[1]] - MaskOffset;
7533         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7534         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535       } else {
7536         // Otherwise pin the low inputs.
7537         for (int GoodInput : GoodInputs)
7538           MoveMask[Mask[GoodInput]] = Mask[GoodInput] - MaskOffset;
7539       }
7540
7541       int MoveMaskIdx =
7542           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7543           std::begin(MoveMask);
7544       assert(MoveMaskIdx >= MoveOffset && "Established above");
7545
7546       if (BadInputs.size() == 2) {
7547         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7548         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7549         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7550             Mask[BadInputs[0]] - MaskOffset;
7551         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7552             Mask[BadInputs[1]] - MaskOffset;
7553         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7554         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7555       } else {
7556         assert(BadInputs.size() == 1 && "All sizes handled");
7557         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7558         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7559       }
7560     }
7561
7562     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7563                                 MoveMask);
7564   };
7565   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7566                         /*MaskOffset*/ 0);
7567   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7568                         /*MaskOffset*/ 8);
7569
7570   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7571   // cross-half traffic in the final shuffle.
7572
7573   // Munge the mask to be a single-input mask after the unpack merges the
7574   // results.
7575   for (int &M : Mask)
7576     if (M != -1)
7577       M = 2 * (M % 4) + (M / 8);
7578
7579   return DAG.getVectorShuffle(
7580       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7581                                   DL, MVT::v8i16, V1, V2),
7582       DAG.getUNDEF(MVT::v8i16), Mask);
7583 }
7584
7585 /// \brief Generic lowering of 8-lane i16 shuffles.
7586 ///
7587 /// This handles both single-input shuffles and combined shuffle/blends with
7588 /// two inputs. The single input shuffles are immediately delegated to
7589 /// a dedicated lowering routine.
7590 ///
7591 /// The blends are lowered in one of three fundamental ways. If there are few
7592 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7593 /// of the input is significantly cheaper when lowered as an interleaving of
7594 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7595 /// halves of the inputs separately (making them have relatively few inputs)
7596 /// and then concatenate them.
7597 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7598                                        const X86Subtarget *Subtarget,
7599                                        SelectionDAG &DAG) {
7600   SDLoc DL(Op);
7601   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7602   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7605   ArrayRef<int> OrigMask = SVOp->getMask();
7606   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7607                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7608   MutableArrayRef<int> Mask(MaskStorage);
7609
7610   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7611
7612   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7613   auto isV2 = [](int M) { return M >= 8; };
7614
7615   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7616   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7617
7618   if (NumV2Inputs == 0)
7619     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7620
7621   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7622                             "to be V1-input shuffles.");
7623
7624   if (NumV1Inputs + NumV2Inputs <= 4)
7625     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7626
7627   // Check whether an interleaving lowering is likely to be more efficient.
7628   // This isn't perfect but it is a strong heuristic that tends to work well on
7629   // the kinds of shuffles that show up in practice.
7630   //
7631   // FIXME: Handle 1x, 2x, and 4x interleaving.
7632   if (shouldLowerAsInterleaving(Mask)) {
7633     // FIXME: Figure out whether we should pack these into the low or high
7634     // halves.
7635
7636     int EMask[8], OMask[8];
7637     for (int i = 0; i < 4; ++i) {
7638       EMask[i] = Mask[2*i];
7639       OMask[i] = Mask[2*i + 1];
7640       EMask[i + 4] = -1;
7641       OMask[i + 4] = -1;
7642     }
7643
7644     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7645     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7646
7647     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7648   }
7649
7650   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7651   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652
7653   for (int i = 0; i < 4; ++i) {
7654     LoBlendMask[i] = Mask[i];
7655     HiBlendMask[i] = Mask[i + 4];
7656   }
7657
7658   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7659   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7660   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7661   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7662
7663   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7664                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7665 }
7666
7667 /// \brief Generic lowering of v16i8 shuffles.
7668 ///
7669 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7670 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7671 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7672 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7673 /// back together.
7674 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7675                                        const X86Subtarget *Subtarget,
7676                                        SelectionDAG &DAG) {
7677   SDLoc DL(Op);
7678   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7679   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7680   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7682   ArrayRef<int> OrigMask = SVOp->getMask();
7683   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7684   int MaskStorage[16] = {
7685       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7686       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7687       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7688       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7689   MutableArrayRef<int> Mask(MaskStorage);
7690   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7691   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7692
7693   // Check whether an interleaving lowering is likely to be more efficient.
7694   // This isn't perfect but it is a strong heuristic that tends to work well on
7695   // the kinds of shuffles that show up in practice.
7696   //
7697   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7698   if (shouldLowerAsInterleaving(Mask)) {
7699     // FIXME: Figure out whether we should pack these into the low or high
7700     // halves.
7701
7702     int EMask[16], OMask[16];
7703     for (int i = 0; i < 8; ++i) {
7704       EMask[i] = Mask[2*i];
7705       OMask[i] = Mask[2*i + 1];
7706       EMask[i + 8] = -1;
7707       OMask[i + 8] = -1;
7708     }
7709
7710     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7711     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7712
7713     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7714   }
7715
7716   SDValue LoV1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7717                              DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1,
7718                                          DAG.getUNDEF(MVT::v8i16)));
7719   SDValue HiV1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7720                              DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1,
7721                                          DAG.getUNDEF(MVT::v8i16)));
7722   SDValue LoV2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7723                              DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2,
7724                                          DAG.getUNDEF(MVT::v8i16)));
7725   SDValue HiV2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7726                              DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2,
7727                                          DAG.getUNDEF(MVT::v8i16)));
7728
7729   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7730   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7731   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7732   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7733
7734   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7735                             MutableArrayRef<int> V1HalfBlendMask,
7736                             MutableArrayRef<int> V2HalfBlendMask) {
7737     for (int i = 0; i < 8; ++i)
7738       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7739         V1HalfBlendMask[i] = HalfMask[i];
7740         HalfMask[i] = i;
7741       } else if (HalfMask[i] >= 16) {
7742         V2HalfBlendMask[i] = HalfMask[i] - 16;
7743         HalfMask[i] = i + 8;
7744       }
7745   };
7746   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7747   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7748
7749   SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7750   SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7751   SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7752   SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7753
7754   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7755   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7756
7757   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7758 }
7759
7760 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7761 ///
7762 /// This routine breaks down the specific type of 128-bit shuffle and
7763 /// dispatches to the lowering routines accordingly.
7764 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7765                                         MVT VT, const X86Subtarget *Subtarget,
7766                                         SelectionDAG &DAG) {
7767   switch (VT.SimpleTy) {
7768   case MVT::v2i64:
7769     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7770   case MVT::v2f64:
7771     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7772   case MVT::v4i32:
7773     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7774   case MVT::v4f32:
7775     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7776   case MVT::v8i16:
7777     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7778   case MVT::v16i8:
7779     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7780
7781   default:
7782     llvm_unreachable("Unimplemented!");
7783   }
7784 }
7785
7786 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7787 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7788   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7789     if (Mask[i] + 1 != Mask[i+1])
7790       return false;
7791
7792   return true;
7793 }
7794
7795 /// \brief Top-level lowering for x86 vector shuffles.
7796 ///
7797 /// This handles decomposition, canonicalization, and lowering of all x86
7798 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7799 /// above in helper routines. The canonicalization attempts to widen shuffles
7800 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7801 /// s.t. only one of the two inputs needs to be tested, etc.
7802 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7803                                   SelectionDAG &DAG) {
7804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7805   ArrayRef<int> Mask = SVOp->getMask();
7806   SDValue V1 = Op.getOperand(0);
7807   SDValue V2 = Op.getOperand(1);
7808   MVT VT = Op.getSimpleValueType();
7809   int NumElements = VT.getVectorNumElements();
7810   SDLoc dl(Op);
7811
7812   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7813
7814   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7815   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7816   if (V1IsUndef && V2IsUndef)
7817     return DAG.getUNDEF(VT);
7818
7819   // When we create a shuffle node we put the UNDEF node to second operand,
7820   // but in some cases the first operand may be transformed to UNDEF.
7821   // In this case we should just commute the node.
7822   if (V1IsUndef)
7823     return CommuteVectorShuffle(SVOp, DAG);
7824
7825   // Check for non-undef masks pointing at an undef vector and make the masks
7826   // undef as well. This makes it easier to match the shuffle based solely on
7827   // the mask.
7828   if (V2IsUndef)
7829     for (int M : Mask)
7830       if (M >= NumElements) {
7831         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7832         for (int &M : NewMask)
7833           if (M >= NumElements)
7834             M = -1;
7835         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7836       }
7837
7838   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7839   // lanes but wider integers. We cap this to not form integers larger than i64
7840   // but it might be interesting to form i128 integers to handle flipping the
7841   // low and high halves of AVX 256-bit vectors.
7842   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7843       areAdjacentMasksSequential(Mask)) {
7844     SmallVector<int, 8> NewMask;
7845     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7846       NewMask.push_back(Mask[i] / 2);
7847     MVT NewVT =
7848         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7849                          VT.getVectorNumElements() / 2);
7850     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7851     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7852     return DAG.getNode(ISD::BITCAST, dl, VT,
7853                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7854   }
7855
7856   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7857   for (int M : SVOp->getMask())
7858     if (M < 0)
7859       ++NumUndefElements;
7860     else if (M < NumElements)
7861       ++NumV1Elements;
7862     else
7863       ++NumV2Elements;
7864
7865   // Commute the shuffle as needed such that more elements come from V1 than
7866   // V2. This allows us to match the shuffle pattern strictly on how many
7867   // elements come from V1 without handling the symmetric cases.
7868   if (NumV2Elements > NumV1Elements)
7869     return CommuteVectorShuffle(SVOp, DAG);
7870
7871   // When the number of V1 and V2 elements are the same, try to minimize the
7872   // number of uses of V2 in the low half of the vector.
7873   if (NumV1Elements == NumV2Elements) {
7874     int LowV1Elements = 0, LowV2Elements = 0;
7875     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7876       if (M >= NumElements)
7877         ++LowV2Elements;
7878       else if (M >= 0)
7879         ++LowV1Elements;
7880     if (LowV2Elements > LowV1Elements)
7881       return CommuteVectorShuffle(SVOp, DAG);
7882   }
7883
7884   // For each vector width, delegate to a specialized lowering routine.
7885   if (VT.getSizeInBits() == 128)
7886     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7887
7888   llvm_unreachable("Unimplemented!");
7889 }
7890
7891
7892 //===----------------------------------------------------------------------===//
7893 // Legacy vector shuffle lowering
7894 //
7895 // This code is the legacy code handling vector shuffles until the above
7896 // replaces its functionality and performance.
7897 //===----------------------------------------------------------------------===//
7898
7899 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7900                         bool hasInt256, unsigned *MaskOut = nullptr) {
7901   MVT EltVT = VT.getVectorElementType();
7902
7903   // There is no blend with immediate in AVX-512.
7904   if (VT.is512BitVector())
7905     return false;
7906
7907   if (!hasSSE41 || EltVT == MVT::i8)
7908     return false;
7909   if (!hasInt256 && VT == MVT::v16i16)
7910     return false;
7911
7912   unsigned MaskValue = 0;
7913   unsigned NumElems = VT.getVectorNumElements();
7914   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7915   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7916   unsigned NumElemsInLane = NumElems / NumLanes;
7917
7918   // Blend for v16i16 should be symetric for the both lanes.
7919   for (unsigned i = 0; i < NumElemsInLane; ++i) {
7920
7921     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
7922     int EltIdx = MaskVals[i];
7923
7924     if ((EltIdx < 0 || EltIdx == (int)i) &&
7925         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
7926       continue;
7927
7928     if (((unsigned)EltIdx == (i + NumElems)) &&
7929         (SndLaneEltIdx < 0 ||
7930          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
7931       MaskValue |= (1 << i);
7932     else
7933       return false;
7934   }
7935
7936   if (MaskOut)
7937     *MaskOut = MaskValue;
7938   return true;
7939 }
7940
7941 // Try to lower a shuffle node into a simple blend instruction.
7942 // This function assumes isBlendMask returns true for this
7943 // SuffleVectorSDNode
7944 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
7945                                           unsigned MaskValue,
7946                                           const X86Subtarget *Subtarget,
7947                                           SelectionDAG &DAG) {
7948   MVT VT = SVOp->getSimpleValueType(0);
7949   MVT EltVT = VT.getVectorElementType();
7950   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
7951                      Subtarget->hasInt256() && "Trying to lower a "
7952                                                "VECTOR_SHUFFLE to a Blend but "
7953                                                "with the wrong mask"));
7954   SDValue V1 = SVOp->getOperand(0);
7955   SDValue V2 = SVOp->getOperand(1);
7956   SDLoc dl(SVOp);
7957   unsigned NumElems = VT.getVectorNumElements();
7958
7959   // Convert i32 vectors to floating point if it is not AVX2.
7960   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
7961   MVT BlendVT = VT;
7962   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
7963     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
7964                                NumElems);
7965     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
7966     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
7967   }
7968
7969   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
7970                             DAG.getConstant(MaskValue, MVT::i32));
7971   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
7972 }
7973
7974 /// In vector type \p VT, return true if the element at index \p InputIdx
7975 /// falls on a different 128-bit lane than \p OutputIdx.
7976 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
7977                                      unsigned OutputIdx) {
7978   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
7979   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
7980 }
7981
7982 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
7983 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
7984 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
7985 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
7986 /// zero.
7987 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
7988                          SelectionDAG &DAG) {
7989   MVT VT = V1.getSimpleValueType();
7990   assert(VT.is128BitVector() || VT.is256BitVector());
7991
7992   MVT EltVT = VT.getVectorElementType();
7993   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
7994   unsigned NumElts = VT.getVectorNumElements();
7995
7996   SmallVector<SDValue, 32> PshufbMask;
7997   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
7998     int InputIdx = MaskVals[OutputIdx];
7999     unsigned InputByteIdx;
8000
8001     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8002       InputByteIdx = 0x80;
8003     else {
8004       // Cross lane is not allowed.
8005       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8006         return SDValue();
8007       InputByteIdx = InputIdx * EltSizeInBytes;
8008       // Index is an byte offset within the 128-bit lane.
8009       InputByteIdx &= 0xf;
8010     }
8011
8012     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8013       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8014       if (InputByteIdx != 0x80)
8015         ++InputByteIdx;
8016     }
8017   }
8018
8019   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8020   if (ShufVT != VT)
8021     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8022   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8023                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8024 }
8025
8026 // v8i16 shuffles - Prefer shuffles in the following order:
8027 // 1. [all]   pshuflw, pshufhw, optional move
8028 // 2. [ssse3] 1 x pshufb
8029 // 3. [ssse3] 2 x pshufb + 1 x por
8030 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8031 static SDValue
8032 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8033                          SelectionDAG &DAG) {
8034   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8035   SDValue V1 = SVOp->getOperand(0);
8036   SDValue V2 = SVOp->getOperand(1);
8037   SDLoc dl(SVOp);
8038   SmallVector<int, 8> MaskVals;
8039
8040   // Determine if more than 1 of the words in each of the low and high quadwords
8041   // of the result come from the same quadword of one of the two inputs.  Undef
8042   // mask values count as coming from any quadword, for better codegen.
8043   //
8044   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8045   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8046   unsigned LoQuad[] = { 0, 0, 0, 0 };
8047   unsigned HiQuad[] = { 0, 0, 0, 0 };
8048   // Indices of quads used.
8049   std::bitset<4> InputQuads;
8050   for (unsigned i = 0; i < 8; ++i) {
8051     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8052     int EltIdx = SVOp->getMaskElt(i);
8053     MaskVals.push_back(EltIdx);
8054     if (EltIdx < 0) {
8055       ++Quad[0];
8056       ++Quad[1];
8057       ++Quad[2];
8058       ++Quad[3];
8059       continue;
8060     }
8061     ++Quad[EltIdx / 4];
8062     InputQuads.set(EltIdx / 4);
8063   }
8064
8065   int BestLoQuad = -1;
8066   unsigned MaxQuad = 1;
8067   for (unsigned i = 0; i < 4; ++i) {
8068     if (LoQuad[i] > MaxQuad) {
8069       BestLoQuad = i;
8070       MaxQuad = LoQuad[i];
8071     }
8072   }
8073
8074   int BestHiQuad = -1;
8075   MaxQuad = 1;
8076   for (unsigned i = 0; i < 4; ++i) {
8077     if (HiQuad[i] > MaxQuad) {
8078       BestHiQuad = i;
8079       MaxQuad = HiQuad[i];
8080     }
8081   }
8082
8083   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8084   // of the two input vectors, shuffle them into one input vector so only a
8085   // single pshufb instruction is necessary. If there are more than 2 input
8086   // quads, disable the next transformation since it does not help SSSE3.
8087   bool V1Used = InputQuads[0] || InputQuads[1];
8088   bool V2Used = InputQuads[2] || InputQuads[3];
8089   if (Subtarget->hasSSSE3()) {
8090     if (InputQuads.count() == 2 && V1Used && V2Used) {
8091       BestLoQuad = InputQuads[0] ? 0 : 1;
8092       BestHiQuad = InputQuads[2] ? 2 : 3;
8093     }
8094     if (InputQuads.count() > 2) {
8095       BestLoQuad = -1;
8096       BestHiQuad = -1;
8097     }
8098   }
8099
8100   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8101   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8102   // words from all 4 input quadwords.
8103   SDValue NewV;
8104   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8105     int MaskV[] = {
8106       BestLoQuad < 0 ? 0 : BestLoQuad,
8107       BestHiQuad < 0 ? 1 : BestHiQuad
8108     };
8109     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8110                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8111                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8112     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8113
8114     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8115     // source words for the shuffle, to aid later transformations.
8116     bool AllWordsInNewV = true;
8117     bool InOrder[2] = { true, true };
8118     for (unsigned i = 0; i != 8; ++i) {
8119       int idx = MaskVals[i];
8120       if (idx != (int)i)
8121         InOrder[i/4] = false;
8122       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8123         continue;
8124       AllWordsInNewV = false;
8125       break;
8126     }
8127
8128     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8129     if (AllWordsInNewV) {
8130       for (int i = 0; i != 8; ++i) {
8131         int idx = MaskVals[i];
8132         if (idx < 0)
8133           continue;
8134         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8135         if ((idx != i) && idx < 4)
8136           pshufhw = false;
8137         if ((idx != i) && idx > 3)
8138           pshuflw = false;
8139       }
8140       V1 = NewV;
8141       V2Used = false;
8142       BestLoQuad = 0;
8143       BestHiQuad = 1;
8144     }
8145
8146     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8147     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8148     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8149       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8150       unsigned TargetMask = 0;
8151       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8152                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8153       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8154       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8155                              getShufflePSHUFLWImmediate(SVOp);
8156       V1 = NewV.getOperand(0);
8157       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8158     }
8159   }
8160
8161   // Promote splats to a larger type which usually leads to more efficient code.
8162   // FIXME: Is this true if pshufb is available?
8163   if (SVOp->isSplat())
8164     return PromoteSplat(SVOp, DAG);
8165
8166   // If we have SSSE3, and all words of the result are from 1 input vector,
8167   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8168   // is present, fall back to case 4.
8169   if (Subtarget->hasSSSE3()) {
8170     SmallVector<SDValue,16> pshufbMask;
8171
8172     // If we have elements from both input vectors, set the high bit of the
8173     // shuffle mask element to zero out elements that come from V2 in the V1
8174     // mask, and elements that come from V1 in the V2 mask, so that the two
8175     // results can be OR'd together.
8176     bool TwoInputs = V1Used && V2Used;
8177     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8178     if (!TwoInputs)
8179       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8180
8181     // Calculate the shuffle mask for the second input, shuffle it, and
8182     // OR it with the first shuffled input.
8183     CommuteVectorShuffleMask(MaskVals, 8);
8184     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8185     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8186     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8187   }
8188
8189   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8190   // and update MaskVals with new element order.
8191   std::bitset<8> InOrder;
8192   if (BestLoQuad >= 0) {
8193     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8194     for (int i = 0; i != 4; ++i) {
8195       int idx = MaskVals[i];
8196       if (idx < 0) {
8197         InOrder.set(i);
8198       } else if ((idx / 4) == BestLoQuad) {
8199         MaskV[i] = idx & 3;
8200         InOrder.set(i);
8201       }
8202     }
8203     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8204                                 &MaskV[0]);
8205
8206     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8207       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8208       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8209                                   NewV.getOperand(0),
8210                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8211     }
8212   }
8213
8214   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8215   // and update MaskVals with the new element order.
8216   if (BestHiQuad >= 0) {
8217     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8218     for (unsigned i = 4; i != 8; ++i) {
8219       int idx = MaskVals[i];
8220       if (idx < 0) {
8221         InOrder.set(i);
8222       } else if ((idx / 4) == BestHiQuad) {
8223         MaskV[i] = (idx & 3) + 4;
8224         InOrder.set(i);
8225       }
8226     }
8227     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8228                                 &MaskV[0]);
8229
8230     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8231       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8232       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8233                                   NewV.getOperand(0),
8234                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8235     }
8236   }
8237
8238   // In case BestHi & BestLo were both -1, which means each quadword has a word
8239   // from each of the four input quadwords, calculate the InOrder bitvector now
8240   // before falling through to the insert/extract cleanup.
8241   if (BestLoQuad == -1 && BestHiQuad == -1) {
8242     NewV = V1;
8243     for (int i = 0; i != 8; ++i)
8244       if (MaskVals[i] < 0 || MaskVals[i] == i)
8245         InOrder.set(i);
8246   }
8247
8248   // The other elements are put in the right place using pextrw and pinsrw.
8249   for (unsigned i = 0; i != 8; ++i) {
8250     if (InOrder[i])
8251       continue;
8252     int EltIdx = MaskVals[i];
8253     if (EltIdx < 0)
8254       continue;
8255     SDValue ExtOp = (EltIdx < 8) ?
8256       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8257                   DAG.getIntPtrConstant(EltIdx)) :
8258       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8259                   DAG.getIntPtrConstant(EltIdx - 8));
8260     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8261                        DAG.getIntPtrConstant(i));
8262   }
8263   return NewV;
8264 }
8265
8266 /// \brief v16i16 shuffles
8267 ///
8268 /// FIXME: We only support generation of a single pshufb currently.  We can
8269 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8270 /// well (e.g 2 x pshufb + 1 x por).
8271 static SDValue
8272 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8273   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8274   SDValue V1 = SVOp->getOperand(0);
8275   SDValue V2 = SVOp->getOperand(1);
8276   SDLoc dl(SVOp);
8277
8278   if (V2.getOpcode() != ISD::UNDEF)
8279     return SDValue();
8280
8281   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8282   return getPSHUFB(MaskVals, V1, dl, DAG);
8283 }
8284
8285 // v16i8 shuffles - Prefer shuffles in the following order:
8286 // 1. [ssse3] 1 x pshufb
8287 // 2. [ssse3] 2 x pshufb + 1 x por
8288 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8289 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8290                                         const X86Subtarget* Subtarget,
8291                                         SelectionDAG &DAG) {
8292   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8293   SDValue V1 = SVOp->getOperand(0);
8294   SDValue V2 = SVOp->getOperand(1);
8295   SDLoc dl(SVOp);
8296   ArrayRef<int> MaskVals = SVOp->getMask();
8297
8298   // Promote splats to a larger type which usually leads to more efficient code.
8299   // FIXME: Is this true if pshufb is available?
8300   if (SVOp->isSplat())
8301     return PromoteSplat(SVOp, DAG);
8302
8303   // If we have SSSE3, case 1 is generated when all result bytes come from
8304   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8305   // present, fall back to case 3.
8306
8307   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8308   if (Subtarget->hasSSSE3()) {
8309     SmallVector<SDValue,16> pshufbMask;
8310
8311     // If all result elements are from one input vector, then only translate
8312     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8313     //
8314     // Otherwise, we have elements from both input vectors, and must zero out
8315     // elements that come from V2 in the first mask, and V1 in the second mask
8316     // so that we can OR them together.
8317     for (unsigned i = 0; i != 16; ++i) {
8318       int EltIdx = MaskVals[i];
8319       if (EltIdx < 0 || EltIdx >= 16)
8320         EltIdx = 0x80;
8321       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8322     }
8323     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8324                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8325                                  MVT::v16i8, pshufbMask));
8326
8327     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8328     // the 2nd operand if it's undefined or zero.
8329     if (V2.getOpcode() == ISD::UNDEF ||
8330         ISD::isBuildVectorAllZeros(V2.getNode()))
8331       return V1;
8332
8333     // Calculate the shuffle mask for the second input, shuffle it, and
8334     // OR it with the first shuffled input.
8335     pshufbMask.clear();
8336     for (unsigned i = 0; i != 16; ++i) {
8337       int EltIdx = MaskVals[i];
8338       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8339       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8340     }
8341     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8342                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8343                                  MVT::v16i8, pshufbMask));
8344     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8345   }
8346
8347   // No SSSE3 - Calculate in place words and then fix all out of place words
8348   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8349   // the 16 different words that comprise the two doublequadword input vectors.
8350   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8351   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8352   SDValue NewV = V1;
8353   for (int i = 0; i != 8; ++i) {
8354     int Elt0 = MaskVals[i*2];
8355     int Elt1 = MaskVals[i*2+1];
8356
8357     // This word of the result is all undef, skip it.
8358     if (Elt0 < 0 && Elt1 < 0)
8359       continue;
8360
8361     // This word of the result is already in the correct place, skip it.
8362     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8363       continue;
8364
8365     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8366     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8367     SDValue InsElt;
8368
8369     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8370     // using a single extract together, load it and store it.
8371     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8372       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8373                            DAG.getIntPtrConstant(Elt1 / 2));
8374       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8375                         DAG.getIntPtrConstant(i));
8376       continue;
8377     }
8378
8379     // If Elt1 is defined, extract it from the appropriate source.  If the
8380     // source byte is not also odd, shift the extracted word left 8 bits
8381     // otherwise clear the bottom 8 bits if we need to do an or.
8382     if (Elt1 >= 0) {
8383       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8384                            DAG.getIntPtrConstant(Elt1 / 2));
8385       if ((Elt1 & 1) == 0)
8386         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8387                              DAG.getConstant(8,
8388                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8389       else if (Elt0 >= 0)
8390         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8391                              DAG.getConstant(0xFF00, MVT::i16));
8392     }
8393     // If Elt0 is defined, extract it from the appropriate source.  If the
8394     // source byte is not also even, shift the extracted word right 8 bits. If
8395     // Elt1 was also defined, OR the extracted values together before
8396     // inserting them in the result.
8397     if (Elt0 >= 0) {
8398       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8399                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8400       if ((Elt0 & 1) != 0)
8401         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8402                               DAG.getConstant(8,
8403                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8404       else if (Elt1 >= 0)
8405         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8406                              DAG.getConstant(0x00FF, MVT::i16));
8407       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8408                          : InsElt0;
8409     }
8410     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8411                        DAG.getIntPtrConstant(i));
8412   }
8413   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8414 }
8415
8416 // v32i8 shuffles - Translate to VPSHUFB if possible.
8417 static
8418 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8419                                  const X86Subtarget *Subtarget,
8420                                  SelectionDAG &DAG) {
8421   MVT VT = SVOp->getSimpleValueType(0);
8422   SDValue V1 = SVOp->getOperand(0);
8423   SDValue V2 = SVOp->getOperand(1);
8424   SDLoc dl(SVOp);
8425   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8426
8427   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8428   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8429   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8430
8431   // VPSHUFB may be generated if
8432   // (1) one of input vector is undefined or zeroinitializer.
8433   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8434   // And (2) the mask indexes don't cross the 128-bit lane.
8435   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8436       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8437     return SDValue();
8438
8439   if (V1IsAllZero && !V2IsAllZero) {
8440     CommuteVectorShuffleMask(MaskVals, 32);
8441     V1 = V2;
8442   }
8443   return getPSHUFB(MaskVals, V1, dl, DAG);
8444 }
8445
8446 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8447 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8448 /// done when every pair / quad of shuffle mask elements point to elements in
8449 /// the right sequence. e.g.
8450 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8451 static
8452 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8453                                  SelectionDAG &DAG) {
8454   MVT VT = SVOp->getSimpleValueType(0);
8455   SDLoc dl(SVOp);
8456   unsigned NumElems = VT.getVectorNumElements();
8457   MVT NewVT;
8458   unsigned Scale;
8459   switch (VT.SimpleTy) {
8460   default: llvm_unreachable("Unexpected!");
8461   case MVT::v2i64:
8462   case MVT::v2f64:
8463            return SDValue(SVOp, 0);
8464   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8465   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8466   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8467   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8468   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8469   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8470   }
8471
8472   SmallVector<int, 8> MaskVec;
8473   for (unsigned i = 0; i != NumElems; i += Scale) {
8474     int StartIdx = -1;
8475     for (unsigned j = 0; j != Scale; ++j) {
8476       int EltIdx = SVOp->getMaskElt(i+j);
8477       if (EltIdx < 0)
8478         continue;
8479       if (StartIdx < 0)
8480         StartIdx = (EltIdx / Scale);
8481       if (EltIdx != (int)(StartIdx*Scale + j))
8482         return SDValue();
8483     }
8484     MaskVec.push_back(StartIdx);
8485   }
8486
8487   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8488   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8489   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8490 }
8491
8492 /// getVZextMovL - Return a zero-extending vector move low node.
8493 ///
8494 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8495                             SDValue SrcOp, SelectionDAG &DAG,
8496                             const X86Subtarget *Subtarget, SDLoc dl) {
8497   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8498     LoadSDNode *LD = nullptr;
8499     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8500       LD = dyn_cast<LoadSDNode>(SrcOp);
8501     if (!LD) {
8502       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8503       // instead.
8504       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8505       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8506           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8507           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8508           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8509         // PR2108
8510         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8511         return DAG.getNode(ISD::BITCAST, dl, VT,
8512                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8513                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8514                                                    OpVT,
8515                                                    SrcOp.getOperand(0)
8516                                                           .getOperand(0))));
8517       }
8518     }
8519   }
8520
8521   return DAG.getNode(ISD::BITCAST, dl, VT,
8522                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8523                                  DAG.getNode(ISD::BITCAST, dl,
8524                                              OpVT, SrcOp)));
8525 }
8526
8527 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8528 /// which could not be matched by any known target speficic shuffle
8529 static SDValue
8530 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8531
8532   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8533   if (NewOp.getNode())
8534     return NewOp;
8535
8536   MVT VT = SVOp->getSimpleValueType(0);
8537
8538   unsigned NumElems = VT.getVectorNumElements();
8539   unsigned NumLaneElems = NumElems / 2;
8540
8541   SDLoc dl(SVOp);
8542   MVT EltVT = VT.getVectorElementType();
8543   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8544   SDValue Output[2];
8545
8546   SmallVector<int, 16> Mask;
8547   for (unsigned l = 0; l < 2; ++l) {
8548     // Build a shuffle mask for the output, discovering on the fly which
8549     // input vectors to use as shuffle operands (recorded in InputUsed).
8550     // If building a suitable shuffle vector proves too hard, then bail
8551     // out with UseBuildVector set.
8552     bool UseBuildVector = false;
8553     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8554     unsigned LaneStart = l * NumLaneElems;
8555     for (unsigned i = 0; i != NumLaneElems; ++i) {
8556       // The mask element.  This indexes into the input.
8557       int Idx = SVOp->getMaskElt(i+LaneStart);
8558       if (Idx < 0) {
8559         // the mask element does not index into any input vector.
8560         Mask.push_back(-1);
8561         continue;
8562       }
8563
8564       // The input vector this mask element indexes into.
8565       int Input = Idx / NumLaneElems;
8566
8567       // Turn the index into an offset from the start of the input vector.
8568       Idx -= Input * NumLaneElems;
8569
8570       // Find or create a shuffle vector operand to hold this input.
8571       unsigned OpNo;
8572       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8573         if (InputUsed[OpNo] == Input)
8574           // This input vector is already an operand.
8575           break;
8576         if (InputUsed[OpNo] < 0) {
8577           // Create a new operand for this input vector.
8578           InputUsed[OpNo] = Input;
8579           break;
8580         }
8581       }
8582
8583       if (OpNo >= array_lengthof(InputUsed)) {
8584         // More than two input vectors used!  Give up on trying to create a
8585         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8586         UseBuildVector = true;
8587         break;
8588       }
8589
8590       // Add the mask index for the new shuffle vector.
8591       Mask.push_back(Idx + OpNo * NumLaneElems);
8592     }
8593
8594     if (UseBuildVector) {
8595       SmallVector<SDValue, 16> SVOps;
8596       for (unsigned i = 0; i != NumLaneElems; ++i) {
8597         // The mask element.  This indexes into the input.
8598         int Idx = SVOp->getMaskElt(i+LaneStart);
8599         if (Idx < 0) {
8600           SVOps.push_back(DAG.getUNDEF(EltVT));
8601           continue;
8602         }
8603
8604         // The input vector this mask element indexes into.
8605         int Input = Idx / NumElems;
8606
8607         // Turn the index into an offset from the start of the input vector.
8608         Idx -= Input * NumElems;
8609
8610         // Extract the vector element by hand.
8611         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8612                                     SVOp->getOperand(Input),
8613                                     DAG.getIntPtrConstant(Idx)));
8614       }
8615
8616       // Construct the output using a BUILD_VECTOR.
8617       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8618     } else if (InputUsed[0] < 0) {
8619       // No input vectors were used! The result is undefined.
8620       Output[l] = DAG.getUNDEF(NVT);
8621     } else {
8622       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8623                                         (InputUsed[0] % 2) * NumLaneElems,
8624                                         DAG, dl);
8625       // If only one input was used, use an undefined vector for the other.
8626       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8627         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8628                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8629       // At least one input vector was used. Create a new shuffle vector.
8630       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8631     }
8632
8633     Mask.clear();
8634   }
8635
8636   // Concatenate the result back
8637   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8638 }
8639
8640 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8641 /// 4 elements, and match them with several different shuffle types.
8642 static SDValue
8643 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8644   SDValue V1 = SVOp->getOperand(0);
8645   SDValue V2 = SVOp->getOperand(1);
8646   SDLoc dl(SVOp);
8647   MVT VT = SVOp->getSimpleValueType(0);
8648
8649   assert(VT.is128BitVector() && "Unsupported vector size");
8650
8651   std::pair<int, int> Locs[4];
8652   int Mask1[] = { -1, -1, -1, -1 };
8653   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8654
8655   unsigned NumHi = 0;
8656   unsigned NumLo = 0;
8657   for (unsigned i = 0; i != 4; ++i) {
8658     int Idx = PermMask[i];
8659     if (Idx < 0) {
8660       Locs[i] = std::make_pair(-1, -1);
8661     } else {
8662       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8663       if (Idx < 4) {
8664         Locs[i] = std::make_pair(0, NumLo);
8665         Mask1[NumLo] = Idx;
8666         NumLo++;
8667       } else {
8668         Locs[i] = std::make_pair(1, NumHi);
8669         if (2+NumHi < 4)
8670           Mask1[2+NumHi] = Idx;
8671         NumHi++;
8672       }
8673     }
8674   }
8675
8676   if (NumLo <= 2 && NumHi <= 2) {
8677     // If no more than two elements come from either vector. This can be
8678     // implemented with two shuffles. First shuffle gather the elements.
8679     // The second shuffle, which takes the first shuffle as both of its
8680     // vector operands, put the elements into the right order.
8681     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8682
8683     int Mask2[] = { -1, -1, -1, -1 };
8684
8685     for (unsigned i = 0; i != 4; ++i)
8686       if (Locs[i].first != -1) {
8687         unsigned Idx = (i < 2) ? 0 : 4;
8688         Idx += Locs[i].first * 2 + Locs[i].second;
8689         Mask2[i] = Idx;
8690       }
8691
8692     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8693   }
8694
8695   if (NumLo == 3 || NumHi == 3) {
8696     // Otherwise, we must have three elements from one vector, call it X, and
8697     // one element from the other, call it Y.  First, use a shufps to build an
8698     // intermediate vector with the one element from Y and the element from X
8699     // that will be in the same half in the final destination (the indexes don't
8700     // matter). Then, use a shufps to build the final vector, taking the half
8701     // containing the element from Y from the intermediate, and the other half
8702     // from X.
8703     if (NumHi == 3) {
8704       // Normalize it so the 3 elements come from V1.
8705       CommuteVectorShuffleMask(PermMask, 4);
8706       std::swap(V1, V2);
8707     }
8708
8709     // Find the element from V2.
8710     unsigned HiIndex;
8711     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8712       int Val = PermMask[HiIndex];
8713       if (Val < 0)
8714         continue;
8715       if (Val >= 4)
8716         break;
8717     }
8718
8719     Mask1[0] = PermMask[HiIndex];
8720     Mask1[1] = -1;
8721     Mask1[2] = PermMask[HiIndex^1];
8722     Mask1[3] = -1;
8723     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8724
8725     if (HiIndex >= 2) {
8726       Mask1[0] = PermMask[0];
8727       Mask1[1] = PermMask[1];
8728       Mask1[2] = HiIndex & 1 ? 6 : 4;
8729       Mask1[3] = HiIndex & 1 ? 4 : 6;
8730       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8731     }
8732
8733     Mask1[0] = HiIndex & 1 ? 2 : 0;
8734     Mask1[1] = HiIndex & 1 ? 0 : 2;
8735     Mask1[2] = PermMask[2];
8736     Mask1[3] = PermMask[3];
8737     if (Mask1[2] >= 0)
8738       Mask1[2] += 4;
8739     if (Mask1[3] >= 0)
8740       Mask1[3] += 4;
8741     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8742   }
8743
8744   // Break it into (shuffle shuffle_hi, shuffle_lo).
8745   int LoMask[] = { -1, -1, -1, -1 };
8746   int HiMask[] = { -1, -1, -1, -1 };
8747
8748   int *MaskPtr = LoMask;
8749   unsigned MaskIdx = 0;
8750   unsigned LoIdx = 0;
8751   unsigned HiIdx = 2;
8752   for (unsigned i = 0; i != 4; ++i) {
8753     if (i == 2) {
8754       MaskPtr = HiMask;
8755       MaskIdx = 1;
8756       LoIdx = 0;
8757       HiIdx = 2;
8758     }
8759     int Idx = PermMask[i];
8760     if (Idx < 0) {
8761       Locs[i] = std::make_pair(-1, -1);
8762     } else if (Idx < 4) {
8763       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8764       MaskPtr[LoIdx] = Idx;
8765       LoIdx++;
8766     } else {
8767       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8768       MaskPtr[HiIdx] = Idx;
8769       HiIdx++;
8770     }
8771   }
8772
8773   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8774   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8775   int MaskOps[] = { -1, -1, -1, -1 };
8776   for (unsigned i = 0; i != 4; ++i)
8777     if (Locs[i].first != -1)
8778       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8779   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8780 }
8781
8782 static bool MayFoldVectorLoad(SDValue V) {
8783   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8784     V = V.getOperand(0);
8785
8786   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8787     V = V.getOperand(0);
8788   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8789       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8790     // BUILD_VECTOR (load), undef
8791     V = V.getOperand(0);
8792
8793   return MayFoldLoad(V);
8794 }
8795
8796 static
8797 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8798   MVT VT = Op.getSimpleValueType();
8799
8800   // Canonizalize to v2f64.
8801   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8802   return DAG.getNode(ISD::BITCAST, dl, VT,
8803                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8804                                           V1, DAG));
8805 }
8806
8807 static
8808 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8809                         bool HasSSE2) {
8810   SDValue V1 = Op.getOperand(0);
8811   SDValue V2 = Op.getOperand(1);
8812   MVT VT = Op.getSimpleValueType();
8813
8814   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8815
8816   if (HasSSE2 && VT == MVT::v2f64)
8817     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8818
8819   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8820   return DAG.getNode(ISD::BITCAST, dl, VT,
8821                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8822                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8823                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8824 }
8825
8826 static
8827 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8828   SDValue V1 = Op.getOperand(0);
8829   SDValue V2 = Op.getOperand(1);
8830   MVT VT = Op.getSimpleValueType();
8831
8832   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8833          "unsupported shuffle type");
8834
8835   if (V2.getOpcode() == ISD::UNDEF)
8836     V2 = V1;
8837
8838   // v4i32 or v4f32
8839   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8840 }
8841
8842 static
8843 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8844   SDValue V1 = Op.getOperand(0);
8845   SDValue V2 = Op.getOperand(1);
8846   MVT VT = Op.getSimpleValueType();
8847   unsigned NumElems = VT.getVectorNumElements();
8848
8849   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8850   // operand of these instructions is only memory, so check if there's a
8851   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8852   // same masks.
8853   bool CanFoldLoad = false;
8854
8855   // Trivial case, when V2 comes from a load.
8856   if (MayFoldVectorLoad(V2))
8857     CanFoldLoad = true;
8858
8859   // When V1 is a load, it can be folded later into a store in isel, example:
8860   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8861   //    turns into:
8862   //  (MOVLPSmr addr:$src1, VR128:$src2)
8863   // So, recognize this potential and also use MOVLPS or MOVLPD
8864   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8865     CanFoldLoad = true;
8866
8867   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8868   if (CanFoldLoad) {
8869     if (HasSSE2 && NumElems == 2)
8870       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8871
8872     if (NumElems == 4)
8873       // If we don't care about the second element, proceed to use movss.
8874       if (SVOp->getMaskElt(1) != -1)
8875         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8876   }
8877
8878   // movl and movlp will both match v2i64, but v2i64 is never matched by
8879   // movl earlier because we make it strict to avoid messing with the movlp load
8880   // folding logic (see the code above getMOVLP call). Match it here then,
8881   // this is horrible, but will stay like this until we move all shuffle
8882   // matching to x86 specific nodes. Note that for the 1st condition all
8883   // types are matched with movsd.
8884   if (HasSSE2) {
8885     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8886     // as to remove this logic from here, as much as possible
8887     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8888       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8889     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8890   }
8891
8892   assert(VT != MVT::v4i32 && "unsupported shuffle type");
8893
8894   // Invert the operand order and use SHUFPS to match it.
8895   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8896                               getShuffleSHUFImmediate(SVOp), DAG);
8897 }
8898
8899 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8900                                          SelectionDAG &DAG) {
8901   SDLoc dl(Load);
8902   MVT VT = Load->getSimpleValueType(0);
8903   MVT EVT = VT.getVectorElementType();
8904   SDValue Addr = Load->getOperand(1);
8905   SDValue NewAddr = DAG.getNode(
8906       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8907       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8908
8909   SDValue NewLoad =
8910       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8911                   DAG.getMachineFunction().getMachineMemOperand(
8912                       Load->getMemOperand(), 0, EVT.getStoreSize()));
8913   return NewLoad;
8914 }
8915
8916 // It is only safe to call this function if isINSERTPSMask is true for
8917 // this shufflevector mask.
8918 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8919                            SelectionDAG &DAG) {
8920   // Generate an insertps instruction when inserting an f32 from memory onto a
8921   // v4f32 or when copying a member from one v4f32 to another.
8922   // We also use it for transferring i32 from one register to another,
8923   // since it simply copies the same bits.
8924   // If we're transferring an i32 from memory to a specific element in a
8925   // register, we output a generic DAG that will match the PINSRD
8926   // instruction.
8927   MVT VT = SVOp->getSimpleValueType(0);
8928   MVT EVT = VT.getVectorElementType();
8929   SDValue V1 = SVOp->getOperand(0);
8930   SDValue V2 = SVOp->getOperand(1);
8931   auto Mask = SVOp->getMask();
8932   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
8933          "unsupported vector type for insertps/pinsrd");
8934
8935   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
8936   auto FromV2Predicate = [](const int &i) { return i >= 4; };
8937   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
8938
8939   SDValue From;
8940   SDValue To;
8941   unsigned DestIndex;
8942   if (FromV1 == 1) {
8943     From = V1;
8944     To = V2;
8945     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
8946                 Mask.begin();
8947   } else {
8948     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
8949            "More than one element from V1 and from V2, or no elements from one "
8950            "of the vectors. This case should not have returned true from "
8951            "isINSERTPSMask");
8952     From = V2;
8953     To = V1;
8954     DestIndex =
8955         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
8956   }
8957
8958   unsigned SrcIndex = Mask[DestIndex] % 4;
8959   if (MayFoldLoad(From)) {
8960     // Trivial case, when From comes from a load and is only used by the
8961     // shuffle. Make it use insertps from the vector that we need from that
8962     // load.
8963     SDValue NewLoad =
8964         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
8965     if (!NewLoad.getNode())
8966       return SDValue();
8967
8968     if (EVT == MVT::f32) {
8969       // Create this as a scalar to vector to match the instruction pattern.
8970       SDValue LoadScalarToVector =
8971           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
8972       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
8973       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
8974                          InsertpsMask);
8975     } else { // EVT == MVT::i32
8976       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
8977       // instruction, to match the PINSRD instruction, which loads an i32 to a
8978       // certain vector element.
8979       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
8980                          DAG.getConstant(DestIndex, MVT::i32));
8981     }
8982   }
8983
8984   // Vector-element-to-vector
8985   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
8986   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
8987 }
8988
8989 // Reduce a vector shuffle to zext.
8990 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
8991                                     SelectionDAG &DAG) {
8992   // PMOVZX is only available from SSE41.
8993   if (!Subtarget->hasSSE41())
8994     return SDValue();
8995
8996   MVT VT = Op.getSimpleValueType();
8997
8998   // Only AVX2 support 256-bit vector integer extending.
8999   if (!Subtarget->hasInt256() && VT.is256BitVector())
9000     return SDValue();
9001
9002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9003   SDLoc DL(Op);
9004   SDValue V1 = Op.getOperand(0);
9005   SDValue V2 = Op.getOperand(1);
9006   unsigned NumElems = VT.getVectorNumElements();
9007
9008   // Extending is an unary operation and the element type of the source vector
9009   // won't be equal to or larger than i64.
9010   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9011       VT.getVectorElementType() == MVT::i64)
9012     return SDValue();
9013
9014   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9015   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9016   while ((1U << Shift) < NumElems) {
9017     if (SVOp->getMaskElt(1U << Shift) == 1)
9018       break;
9019     Shift += 1;
9020     // The maximal ratio is 8, i.e. from i8 to i64.
9021     if (Shift > 3)
9022       return SDValue();
9023   }
9024
9025   // Check the shuffle mask.
9026   unsigned Mask = (1U << Shift) - 1;
9027   for (unsigned i = 0; i != NumElems; ++i) {
9028     int EltIdx = SVOp->getMaskElt(i);
9029     if ((i & Mask) != 0 && EltIdx != -1)
9030       return SDValue();
9031     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9032       return SDValue();
9033   }
9034
9035   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9036   MVT NeVT = MVT::getIntegerVT(NBits);
9037   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9038
9039   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9040     return SDValue();
9041
9042   // Simplify the operand as it's prepared to be fed into shuffle.
9043   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9044   if (V1.getOpcode() == ISD::BITCAST &&
9045       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9046       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9047       V1.getOperand(0).getOperand(0)
9048         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9049     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9050     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9051     ConstantSDNode *CIdx =
9052       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9053     // If it's foldable, i.e. normal load with single use, we will let code
9054     // selection to fold it. Otherwise, we will short the conversion sequence.
9055     if (CIdx && CIdx->getZExtValue() == 0 &&
9056         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9057       MVT FullVT = V.getSimpleValueType();
9058       MVT V1VT = V1.getSimpleValueType();
9059       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9060         // The "ext_vec_elt" node is wider than the result node.
9061         // In this case we should extract subvector from V.
9062         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9063         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9064         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9065                                         FullVT.getVectorNumElements()/Ratio);
9066         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9067                         DAG.getIntPtrConstant(0));
9068       }
9069       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9070     }
9071   }
9072
9073   return DAG.getNode(ISD::BITCAST, DL, VT,
9074                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9075 }
9076
9077 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9078                                       SelectionDAG &DAG) {
9079   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9080   MVT VT = Op.getSimpleValueType();
9081   SDLoc dl(Op);
9082   SDValue V1 = Op.getOperand(0);
9083   SDValue V2 = Op.getOperand(1);
9084
9085   if (isZeroShuffle(SVOp))
9086     return getZeroVector(VT, Subtarget, DAG, dl);
9087
9088   // Handle splat operations
9089   if (SVOp->isSplat()) {
9090     // Use vbroadcast whenever the splat comes from a foldable load
9091     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9092     if (Broadcast.getNode())
9093       return Broadcast;
9094   }
9095
9096   // Check integer expanding shuffles.
9097   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9098   if (NewOp.getNode())
9099     return NewOp;
9100
9101   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9102   // do it!
9103   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9104       VT == MVT::v32i8) {
9105     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9106     if (NewOp.getNode())
9107       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9108   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9109     // FIXME: Figure out a cleaner way to do this.
9110     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9111       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9112       if (NewOp.getNode()) {
9113         MVT NewVT = NewOp.getSimpleValueType();
9114         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9115                                NewVT, true, false))
9116           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9117                               dl);
9118       }
9119     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9120       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9121       if (NewOp.getNode()) {
9122         MVT NewVT = NewOp.getSimpleValueType();
9123         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9124           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9125                               dl);
9126       }
9127     }
9128   }
9129   return SDValue();
9130 }
9131
9132 SDValue
9133 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9135   SDValue V1 = Op.getOperand(0);
9136   SDValue V2 = Op.getOperand(1);
9137   MVT VT = Op.getSimpleValueType();
9138   SDLoc dl(Op);
9139   unsigned NumElems = VT.getVectorNumElements();
9140   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9141   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9142   bool V1IsSplat = false;
9143   bool V2IsSplat = false;
9144   bool HasSSE2 = Subtarget->hasSSE2();
9145   bool HasFp256    = Subtarget->hasFp256();
9146   bool HasInt256   = Subtarget->hasInt256();
9147   MachineFunction &MF = DAG.getMachineFunction();
9148   bool OptForSize = MF.getFunction()->getAttributes().
9149     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9150
9151   // Check if we should use the experimental vector shuffle lowering. If so,
9152   // delegate completely to that code path.
9153   if (ExperimentalVectorShuffleLowering)
9154     return lowerVectorShuffle(Op, Subtarget, DAG);
9155
9156   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9157
9158   if (V1IsUndef && V2IsUndef)
9159     return DAG.getUNDEF(VT);
9160
9161   // When we create a shuffle node we put the UNDEF node to second operand,
9162   // but in some cases the first operand may be transformed to UNDEF.
9163   // In this case we should just commute the node.
9164   if (V1IsUndef)
9165     return CommuteVectorShuffle(SVOp, DAG);
9166
9167   // Vector shuffle lowering takes 3 steps:
9168   //
9169   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9170   //    narrowing and commutation of operands should be handled.
9171   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9172   //    shuffle nodes.
9173   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9174   //    so the shuffle can be broken into other shuffles and the legalizer can
9175   //    try the lowering again.
9176   //
9177   // The general idea is that no vector_shuffle operation should be left to
9178   // be matched during isel, all of them must be converted to a target specific
9179   // node here.
9180
9181   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9182   // narrowing and commutation of operands should be handled. The actual code
9183   // doesn't include all of those, work in progress...
9184   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9185   if (NewOp.getNode())
9186     return NewOp;
9187
9188   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9189
9190   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9191   // unpckh_undef). Only use pshufd if speed is more important than size.
9192   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9193     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9194   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9195     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9196
9197   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9198       V2IsUndef && MayFoldVectorLoad(V1))
9199     return getMOVDDup(Op, dl, V1, DAG);
9200
9201   if (isMOVHLPS_v_undef_Mask(M, VT))
9202     return getMOVHighToLow(Op, dl, DAG);
9203
9204   // Use to match splats
9205   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9206       (VT == MVT::v2f64 || VT == MVT::v2i64))
9207     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9208
9209   if (isPSHUFDMask(M, VT)) {
9210     // The actual implementation will match the mask in the if above and then
9211     // during isel it can match several different instructions, not only pshufd
9212     // as its name says, sad but true, emulate the behavior for now...
9213     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9214       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9215
9216     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9217
9218     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9219       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9220
9221     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9222       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9223                                   DAG);
9224
9225     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9226                                 TargetMask, DAG);
9227   }
9228
9229   if (isPALIGNRMask(M, VT, Subtarget))
9230     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9231                                 getShufflePALIGNRImmediate(SVOp),
9232                                 DAG);
9233
9234   // Check if this can be converted into a logical shift.
9235   bool isLeft = false;
9236   unsigned ShAmt = 0;
9237   SDValue ShVal;
9238   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9239   if (isShift && ShVal.hasOneUse()) {
9240     // If the shifted value has multiple uses, it may be cheaper to use
9241     // v_set0 + movlhps or movhlps, etc.
9242     MVT EltVT = VT.getVectorElementType();
9243     ShAmt *= EltVT.getSizeInBits();
9244     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9245   }
9246
9247   if (isMOVLMask(M, VT)) {
9248     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9249       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9250     if (!isMOVLPMask(M, VT)) {
9251       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9252         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9253
9254       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9255         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9256     }
9257   }
9258
9259   // FIXME: fold these into legal mask.
9260   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9261     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9262
9263   if (isMOVHLPSMask(M, VT))
9264     return getMOVHighToLow(Op, dl, DAG);
9265
9266   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9267     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9268
9269   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9270     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9271
9272   if (isMOVLPMask(M, VT))
9273     return getMOVLP(Op, dl, DAG, HasSSE2);
9274
9275   if (ShouldXformToMOVHLPS(M, VT) ||
9276       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9277     return CommuteVectorShuffle(SVOp, DAG);
9278
9279   if (isShift) {
9280     // No better options. Use a vshldq / vsrldq.
9281     MVT EltVT = VT.getVectorElementType();
9282     ShAmt *= EltVT.getSizeInBits();
9283     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9284   }
9285
9286   bool Commuted = false;
9287   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9288   // 1,1,1,1 -> v8i16 though.
9289   V1IsSplat = isSplatVector(V1.getNode());
9290   V2IsSplat = isSplatVector(V2.getNode());
9291
9292   // Canonicalize the splat or undef, if present, to be on the RHS.
9293   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9294     CommuteVectorShuffleMask(M, NumElems);
9295     std::swap(V1, V2);
9296     std::swap(V1IsSplat, V2IsSplat);
9297     Commuted = true;
9298   }
9299
9300   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9301     // Shuffling low element of v1 into undef, just return v1.
9302     if (V2IsUndef)
9303       return V1;
9304     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9305     // the instruction selector will not match, so get a canonical MOVL with
9306     // swapped operands to undo the commute.
9307     return getMOVL(DAG, dl, VT, V2, V1);
9308   }
9309
9310   if (isUNPCKLMask(M, VT, HasInt256))
9311     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9312
9313   if (isUNPCKHMask(M, VT, HasInt256))
9314     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9315
9316   if (V2IsSplat) {
9317     // Normalize mask so all entries that point to V2 points to its first
9318     // element then try to match unpck{h|l} again. If match, return a
9319     // new vector_shuffle with the corrected mask.p
9320     SmallVector<int, 8> NewMask(M.begin(), M.end());
9321     NormalizeMask(NewMask, NumElems);
9322     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9323       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9324     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9325       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9326   }
9327
9328   if (Commuted) {
9329     // Commute is back and try unpck* again.
9330     // FIXME: this seems wrong.
9331     CommuteVectorShuffleMask(M, NumElems);
9332     std::swap(V1, V2);
9333     std::swap(V1IsSplat, V2IsSplat);
9334
9335     if (isUNPCKLMask(M, VT, HasInt256))
9336       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9337
9338     if (isUNPCKHMask(M, VT, HasInt256))
9339       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9340   }
9341
9342   // Normalize the node to match x86 shuffle ops if needed
9343   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9344     return CommuteVectorShuffle(SVOp, DAG);
9345
9346   // The checks below are all present in isShuffleMaskLegal, but they are
9347   // inlined here right now to enable us to directly emit target specific
9348   // nodes, and remove one by one until they don't return Op anymore.
9349
9350   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9351       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9352     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9353       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9354   }
9355
9356   if (isPSHUFHWMask(M, VT, HasInt256))
9357     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9358                                 getShufflePSHUFHWImmediate(SVOp),
9359                                 DAG);
9360
9361   if (isPSHUFLWMask(M, VT, HasInt256))
9362     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9363                                 getShufflePSHUFLWImmediate(SVOp),
9364                                 DAG);
9365
9366   unsigned MaskValue;
9367   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9368                   &MaskValue))
9369     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9370
9371   if (isSHUFPMask(M, VT))
9372     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9373                                 getShuffleSHUFImmediate(SVOp), DAG);
9374
9375   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9376     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9377   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9378     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9379
9380   //===--------------------------------------------------------------------===//
9381   // Generate target specific nodes for 128 or 256-bit shuffles only
9382   // supported in the AVX instruction set.
9383   //
9384
9385   // Handle VMOVDDUPY permutations
9386   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9387     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9388
9389   // Handle VPERMILPS/D* permutations
9390   if (isVPERMILPMask(M, VT)) {
9391     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9392       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9393                                   getShuffleSHUFImmediate(SVOp), DAG);
9394     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9395                                 getShuffleSHUFImmediate(SVOp), DAG);
9396   }
9397
9398   unsigned Idx;
9399   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9400     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9401                               Idx*(NumElems/2), DAG, dl);
9402
9403   // Handle VPERM2F128/VPERM2I128 permutations
9404   if (isVPERM2X128Mask(M, VT, HasFp256))
9405     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9406                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9407
9408   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9409     return getINSERTPS(SVOp, dl, DAG);
9410
9411   unsigned Imm8;
9412   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9413     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9414
9415   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9416       VT.is512BitVector()) {
9417     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9418     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9419     SmallVector<SDValue, 16> permclMask;
9420     for (unsigned i = 0; i != NumElems; ++i) {
9421       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9422     }
9423
9424     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9425     if (V2IsUndef)
9426       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9427       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9428                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9429     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9430                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9431   }
9432
9433   //===--------------------------------------------------------------------===//
9434   // Since no target specific shuffle was selected for this generic one,
9435   // lower it into other known shuffles. FIXME: this isn't true yet, but
9436   // this is the plan.
9437   //
9438
9439   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9440   if (VT == MVT::v8i16) {
9441     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9442     if (NewOp.getNode())
9443       return NewOp;
9444   }
9445
9446   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9447     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9448     if (NewOp.getNode())
9449       return NewOp;
9450   }
9451
9452   if (VT == MVT::v16i8) {
9453     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9454     if (NewOp.getNode())
9455       return NewOp;
9456   }
9457
9458   if (VT == MVT::v32i8) {
9459     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9460     if (NewOp.getNode())
9461       return NewOp;
9462   }
9463
9464   // Handle all 128-bit wide vectors with 4 elements, and match them with
9465   // several different shuffle types.
9466   if (NumElems == 4 && VT.is128BitVector())
9467     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9468
9469   // Handle general 256-bit shuffles
9470   if (VT.is256BitVector())
9471     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9472
9473   return SDValue();
9474 }
9475
9476 // This function assumes its argument is a BUILD_VECTOR of constants or
9477 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9478 // true.
9479 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9480                                     unsigned &MaskValue) {
9481   MaskValue = 0;
9482   unsigned NumElems = BuildVector->getNumOperands();
9483   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9484   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9485   unsigned NumElemsInLane = NumElems / NumLanes;
9486
9487   // Blend for v16i16 should be symetric for the both lanes.
9488   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9489     SDValue EltCond = BuildVector->getOperand(i);
9490     SDValue SndLaneEltCond =
9491         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9492
9493     int Lane1Cond = -1, Lane2Cond = -1;
9494     if (isa<ConstantSDNode>(EltCond))
9495       Lane1Cond = !isZero(EltCond);
9496     if (isa<ConstantSDNode>(SndLaneEltCond))
9497       Lane2Cond = !isZero(SndLaneEltCond);
9498
9499     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9500       // Lane1Cond != 0, means we want the first argument.
9501       // Lane1Cond == 0, means we want the second argument.
9502       // The encoding of this argument is 0 for the first argument, 1
9503       // for the second. Therefore, invert the condition.
9504       MaskValue |= !Lane1Cond << i;
9505     else if (Lane1Cond < 0)
9506       MaskValue |= !Lane2Cond << i;
9507     else
9508       return false;
9509   }
9510   return true;
9511 }
9512
9513 // Try to lower a vselect node into a simple blend instruction.
9514 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9515                                    SelectionDAG &DAG) {
9516   SDValue Cond = Op.getOperand(0);
9517   SDValue LHS = Op.getOperand(1);
9518   SDValue RHS = Op.getOperand(2);
9519   SDLoc dl(Op);
9520   MVT VT = Op.getSimpleValueType();
9521   MVT EltVT = VT.getVectorElementType();
9522   unsigned NumElems = VT.getVectorNumElements();
9523
9524   // There is no blend with immediate in AVX-512.
9525   if (VT.is512BitVector())
9526     return SDValue();
9527
9528   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9529     return SDValue();
9530   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9531     return SDValue();
9532
9533   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9534     return SDValue();
9535
9536   // Check the mask for BLEND and build the value.
9537   unsigned MaskValue = 0;
9538   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9539     return SDValue();
9540
9541   // Convert i32 vectors to floating point if it is not AVX2.
9542   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9543   MVT BlendVT = VT;
9544   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9545     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9546                                NumElems);
9547     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9548     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9549   }
9550
9551   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9552                             DAG.getConstant(MaskValue, MVT::i32));
9553   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9554 }
9555
9556 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9557   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9558   if (BlendOp.getNode())
9559     return BlendOp;
9560
9561   // Some types for vselect were previously set to Expand, not Legal or
9562   // Custom. Return an empty SDValue so we fall-through to Expand, after
9563   // the Custom lowering phase.
9564   MVT VT = Op.getSimpleValueType();
9565   switch (VT.SimpleTy) {
9566   default:
9567     break;
9568   case MVT::v8i16:
9569   case MVT::v16i16:
9570     return SDValue();
9571   }
9572
9573   // We couldn't create a "Blend with immediate" node.
9574   // This node should still be legal, but we'll have to emit a blendv*
9575   // instruction.
9576   return Op;
9577 }
9578
9579 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9580   MVT VT = Op.getSimpleValueType();
9581   SDLoc dl(Op);
9582
9583   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9584     return SDValue();
9585
9586   if (VT.getSizeInBits() == 8) {
9587     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9588                                   Op.getOperand(0), Op.getOperand(1));
9589     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9590                                   DAG.getValueType(VT));
9591     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9592   }
9593
9594   if (VT.getSizeInBits() == 16) {
9595     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9596     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9597     if (Idx == 0)
9598       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9599                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9600                                      DAG.getNode(ISD::BITCAST, dl,
9601                                                  MVT::v4i32,
9602                                                  Op.getOperand(0)),
9603                                      Op.getOperand(1)));
9604     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9605                                   Op.getOperand(0), Op.getOperand(1));
9606     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9607                                   DAG.getValueType(VT));
9608     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9609   }
9610
9611   if (VT == MVT::f32) {
9612     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9613     // the result back to FR32 register. It's only worth matching if the
9614     // result has a single use which is a store or a bitcast to i32.  And in
9615     // the case of a store, it's not worth it if the index is a constant 0,
9616     // because a MOVSSmr can be used instead, which is smaller and faster.
9617     if (!Op.hasOneUse())
9618       return SDValue();
9619     SDNode *User = *Op.getNode()->use_begin();
9620     if ((User->getOpcode() != ISD::STORE ||
9621          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9622           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9623         (User->getOpcode() != ISD::BITCAST ||
9624          User->getValueType(0) != MVT::i32))
9625       return SDValue();
9626     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9627                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9628                                               Op.getOperand(0)),
9629                                               Op.getOperand(1));
9630     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9631   }
9632
9633   if (VT == MVT::i32 || VT == MVT::i64) {
9634     // ExtractPS/pextrq works with constant index.
9635     if (isa<ConstantSDNode>(Op.getOperand(1)))
9636       return Op;
9637   }
9638   return SDValue();
9639 }
9640
9641 /// Extract one bit from mask vector, like v16i1 or v8i1.
9642 /// AVX-512 feature.
9643 SDValue
9644 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9645   SDValue Vec = Op.getOperand(0);
9646   SDLoc dl(Vec);
9647   MVT VecVT = Vec.getSimpleValueType();
9648   SDValue Idx = Op.getOperand(1);
9649   MVT EltVT = Op.getSimpleValueType();
9650
9651   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9652
9653   // variable index can't be handled in mask registers,
9654   // extend vector to VR512
9655   if (!isa<ConstantSDNode>(Idx)) {
9656     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9657     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9658     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9659                               ExtVT.getVectorElementType(), Ext, Idx);
9660     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9661   }
9662
9663   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9664   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9665   unsigned MaxSift = rc->getSize()*8 - 1;
9666   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9667                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9668   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9669                     DAG.getConstant(MaxSift, MVT::i8));
9670   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9671                        DAG.getIntPtrConstant(0));
9672 }
9673
9674 SDValue
9675 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9676                                            SelectionDAG &DAG) const {
9677   SDLoc dl(Op);
9678   SDValue Vec = Op.getOperand(0);
9679   MVT VecVT = Vec.getSimpleValueType();
9680   SDValue Idx = Op.getOperand(1);
9681
9682   if (Op.getSimpleValueType() == MVT::i1)
9683     return ExtractBitFromMaskVector(Op, DAG);
9684
9685   if (!isa<ConstantSDNode>(Idx)) {
9686     if (VecVT.is512BitVector() ||
9687         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9688          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9689
9690       MVT MaskEltVT =
9691         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9692       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9693                                     MaskEltVT.getSizeInBits());
9694
9695       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9696       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9697                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9698                                 Idx, DAG.getConstant(0, getPointerTy()));
9699       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9700       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9701                         Perm, DAG.getConstant(0, getPointerTy()));
9702     }
9703     return SDValue();
9704   }
9705
9706   // If this is a 256-bit vector result, first extract the 128-bit vector and
9707   // then extract the element from the 128-bit vector.
9708   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9709
9710     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9711     // Get the 128-bit vector.
9712     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9713     MVT EltVT = VecVT.getVectorElementType();
9714
9715     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9716
9717     //if (IdxVal >= NumElems/2)
9718     //  IdxVal -= NumElems/2;
9719     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9720     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9721                        DAG.getConstant(IdxVal, MVT::i32));
9722   }
9723
9724   assert(VecVT.is128BitVector() && "Unexpected vector length");
9725
9726   if (Subtarget->hasSSE41()) {
9727     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9728     if (Res.getNode())
9729       return Res;
9730   }
9731
9732   MVT VT = Op.getSimpleValueType();
9733   // TODO: handle v16i8.
9734   if (VT.getSizeInBits() == 16) {
9735     SDValue Vec = Op.getOperand(0);
9736     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9737     if (Idx == 0)
9738       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9739                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9740                                      DAG.getNode(ISD::BITCAST, dl,
9741                                                  MVT::v4i32, Vec),
9742                                      Op.getOperand(1)));
9743     // Transform it so it match pextrw which produces a 32-bit result.
9744     MVT EltVT = MVT::i32;
9745     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9746                                   Op.getOperand(0), Op.getOperand(1));
9747     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9748                                   DAG.getValueType(VT));
9749     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9750   }
9751
9752   if (VT.getSizeInBits() == 32) {
9753     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9754     if (Idx == 0)
9755       return Op;
9756
9757     // SHUFPS the element to the lowest double word, then movss.
9758     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9759     MVT VVT = Op.getOperand(0).getSimpleValueType();
9760     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9761                                        DAG.getUNDEF(VVT), Mask);
9762     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9763                        DAG.getIntPtrConstant(0));
9764   }
9765
9766   if (VT.getSizeInBits() == 64) {
9767     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9768     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9769     //        to match extract_elt for f64.
9770     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9771     if (Idx == 0)
9772       return Op;
9773
9774     // UNPCKHPD the element to the lowest double word, then movsd.
9775     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9776     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9777     int Mask[2] = { 1, -1 };
9778     MVT VVT = Op.getOperand(0).getSimpleValueType();
9779     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9780                                        DAG.getUNDEF(VVT), Mask);
9781     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9782                        DAG.getIntPtrConstant(0));
9783   }
9784
9785   return SDValue();
9786 }
9787
9788 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9789   MVT VT = Op.getSimpleValueType();
9790   MVT EltVT = VT.getVectorElementType();
9791   SDLoc dl(Op);
9792
9793   SDValue N0 = Op.getOperand(0);
9794   SDValue N1 = Op.getOperand(1);
9795   SDValue N2 = Op.getOperand(2);
9796
9797   if (!VT.is128BitVector())
9798     return SDValue();
9799
9800   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9801       isa<ConstantSDNode>(N2)) {
9802     unsigned Opc;
9803     if (VT == MVT::v8i16)
9804       Opc = X86ISD::PINSRW;
9805     else if (VT == MVT::v16i8)
9806       Opc = X86ISD::PINSRB;
9807     else
9808       Opc = X86ISD::PINSRB;
9809
9810     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9811     // argument.
9812     if (N1.getValueType() != MVT::i32)
9813       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9814     if (N2.getValueType() != MVT::i32)
9815       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9816     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9817   }
9818
9819   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9820     // Bits [7:6] of the constant are the source select.  This will always be
9821     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9822     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9823     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9824     // Bits [5:4] of the constant are the destination select.  This is the
9825     //  value of the incoming immediate.
9826     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9827     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9828     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9829     // Create this as a scalar to vector..
9830     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9831     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9832   }
9833
9834   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9835     // PINSR* works with constant index.
9836     return Op;
9837   }
9838   return SDValue();
9839 }
9840
9841 /// Insert one bit to mask vector, like v16i1 or v8i1.
9842 /// AVX-512 feature.
9843 SDValue 
9844 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9845   SDLoc dl(Op);
9846   SDValue Vec = Op.getOperand(0);
9847   SDValue Elt = Op.getOperand(1);
9848   SDValue Idx = Op.getOperand(2);
9849   MVT VecVT = Vec.getSimpleValueType();
9850
9851   if (!isa<ConstantSDNode>(Idx)) {
9852     // Non constant index. Extend source and destination,
9853     // insert element and then truncate the result.
9854     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9855     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9856     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9857       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9858       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9859     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9860   }
9861
9862   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9863   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9864   if (Vec.getOpcode() == ISD::UNDEF)
9865     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9866                        DAG.getConstant(IdxVal, MVT::i8));
9867   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9868   unsigned MaxSift = rc->getSize()*8 - 1;
9869   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9870                     DAG.getConstant(MaxSift, MVT::i8));
9871   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9872                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9873   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9874 }
9875 SDValue
9876 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9877   MVT VT = Op.getSimpleValueType();
9878   MVT EltVT = VT.getVectorElementType();
9879   
9880   if (EltVT == MVT::i1)
9881     return InsertBitToMaskVector(Op, DAG);
9882
9883   SDLoc dl(Op);
9884   SDValue N0 = Op.getOperand(0);
9885   SDValue N1 = Op.getOperand(1);
9886   SDValue N2 = Op.getOperand(2);
9887
9888   // If this is a 256-bit vector result, first extract the 128-bit vector,
9889   // insert the element into the extracted half and then place it back.
9890   if (VT.is256BitVector() || VT.is512BitVector()) {
9891     if (!isa<ConstantSDNode>(N2))
9892       return SDValue();
9893
9894     // Get the desired 128-bit vector half.
9895     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9896     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9897
9898     // Insert the element into the desired half.
9899     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9900     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9901
9902     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9903                     DAG.getConstant(IdxIn128, MVT::i32));
9904
9905     // Insert the changed part back to the 256-bit vector
9906     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9907   }
9908
9909   if (Subtarget->hasSSE41())
9910     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9911
9912   if (EltVT == MVT::i8)
9913     return SDValue();
9914
9915   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9916     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9917     // as its second argument.
9918     if (N1.getValueType() != MVT::i32)
9919       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9920     if (N2.getValueType() != MVT::i32)
9921       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9922     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
9923   }
9924   return SDValue();
9925 }
9926
9927 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
9928   SDLoc dl(Op);
9929   MVT OpVT = Op.getSimpleValueType();
9930
9931   // If this is a 256-bit vector result, first insert into a 128-bit
9932   // vector and then insert into the 256-bit vector.
9933   if (!OpVT.is128BitVector()) {
9934     // Insert into a 128-bit vector.
9935     unsigned SizeFactor = OpVT.getSizeInBits()/128;
9936     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
9937                                  OpVT.getVectorNumElements() / SizeFactor);
9938
9939     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
9940
9941     // Insert the 128-bit vector.
9942     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
9943   }
9944
9945   if (OpVT == MVT::v1i64 &&
9946       Op.getOperand(0).getValueType() == MVT::i64)
9947     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
9948
9949   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
9950   assert(OpVT.is128BitVector() && "Expected an SSE type!");
9951   return DAG.getNode(ISD::BITCAST, dl, OpVT,
9952                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
9953 }
9954
9955 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
9956 // a simple subregister reference or explicit instructions to grab
9957 // upper bits of a vector.
9958 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
9959                                       SelectionDAG &DAG) {
9960   SDLoc dl(Op);
9961   SDValue In =  Op.getOperand(0);
9962   SDValue Idx = Op.getOperand(1);
9963   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9964   MVT ResVT   = Op.getSimpleValueType();
9965   MVT InVT    = In.getSimpleValueType();
9966
9967   if (Subtarget->hasFp256()) {
9968     if (ResVT.is128BitVector() &&
9969         (InVT.is256BitVector() || InVT.is512BitVector()) &&
9970         isa<ConstantSDNode>(Idx)) {
9971       return Extract128BitVector(In, IdxVal, DAG, dl);
9972     }
9973     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
9974         isa<ConstantSDNode>(Idx)) {
9975       return Extract256BitVector(In, IdxVal, DAG, dl);
9976     }
9977   }
9978   return SDValue();
9979 }
9980
9981 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
9982 // simple superregister reference or explicit instructions to insert
9983 // the upper bits of a vector.
9984 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
9985                                      SelectionDAG &DAG) {
9986   if (Subtarget->hasFp256()) {
9987     SDLoc dl(Op.getNode());
9988     SDValue Vec = Op.getNode()->getOperand(0);
9989     SDValue SubVec = Op.getNode()->getOperand(1);
9990     SDValue Idx = Op.getNode()->getOperand(2);
9991
9992     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
9993          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
9994         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
9995         isa<ConstantSDNode>(Idx)) {
9996       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9997       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
9998     }
9999
10000     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10001         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10002         isa<ConstantSDNode>(Idx)) {
10003       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10004       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10005     }
10006   }
10007   return SDValue();
10008 }
10009
10010 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10011 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10012 // one of the above mentioned nodes. It has to be wrapped because otherwise
10013 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10014 // be used to form addressing mode. These wrapped nodes will be selected
10015 // into MOV32ri.
10016 SDValue
10017 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10018   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10019
10020   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10021   // global base reg.
10022   unsigned char OpFlag = 0;
10023   unsigned WrapperKind = X86ISD::Wrapper;
10024   CodeModel::Model M = DAG.getTarget().getCodeModel();
10025
10026   if (Subtarget->isPICStyleRIPRel() &&
10027       (M == CodeModel::Small || M == CodeModel::Kernel))
10028     WrapperKind = X86ISD::WrapperRIP;
10029   else if (Subtarget->isPICStyleGOT())
10030     OpFlag = X86II::MO_GOTOFF;
10031   else if (Subtarget->isPICStyleStubPIC())
10032     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10033
10034   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10035                                              CP->getAlignment(),
10036                                              CP->getOffset(), OpFlag);
10037   SDLoc DL(CP);
10038   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10039   // With PIC, the address is actually $g + Offset.
10040   if (OpFlag) {
10041     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10042                          DAG.getNode(X86ISD::GlobalBaseReg,
10043                                      SDLoc(), getPointerTy()),
10044                          Result);
10045   }
10046
10047   return Result;
10048 }
10049
10050 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10051   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10052
10053   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10054   // global base reg.
10055   unsigned char OpFlag = 0;
10056   unsigned WrapperKind = X86ISD::Wrapper;
10057   CodeModel::Model M = DAG.getTarget().getCodeModel();
10058
10059   if (Subtarget->isPICStyleRIPRel() &&
10060       (M == CodeModel::Small || M == CodeModel::Kernel))
10061     WrapperKind = X86ISD::WrapperRIP;
10062   else if (Subtarget->isPICStyleGOT())
10063     OpFlag = X86II::MO_GOTOFF;
10064   else if (Subtarget->isPICStyleStubPIC())
10065     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10066
10067   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10068                                           OpFlag);
10069   SDLoc DL(JT);
10070   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10071
10072   // With PIC, the address is actually $g + Offset.
10073   if (OpFlag)
10074     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10075                          DAG.getNode(X86ISD::GlobalBaseReg,
10076                                      SDLoc(), getPointerTy()),
10077                          Result);
10078
10079   return Result;
10080 }
10081
10082 SDValue
10083 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10084   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10085
10086   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10087   // global base reg.
10088   unsigned char OpFlag = 0;
10089   unsigned WrapperKind = X86ISD::Wrapper;
10090   CodeModel::Model M = DAG.getTarget().getCodeModel();
10091
10092   if (Subtarget->isPICStyleRIPRel() &&
10093       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10094     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10095       OpFlag = X86II::MO_GOTPCREL;
10096     WrapperKind = X86ISD::WrapperRIP;
10097   } else if (Subtarget->isPICStyleGOT()) {
10098     OpFlag = X86II::MO_GOT;
10099   } else if (Subtarget->isPICStyleStubPIC()) {
10100     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10101   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10102     OpFlag = X86II::MO_DARWIN_NONLAZY;
10103   }
10104
10105   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10106
10107   SDLoc DL(Op);
10108   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10109
10110   // With PIC, the address is actually $g + Offset.
10111   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10112       !Subtarget->is64Bit()) {
10113     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10114                          DAG.getNode(X86ISD::GlobalBaseReg,
10115                                      SDLoc(), getPointerTy()),
10116                          Result);
10117   }
10118
10119   // For symbols that require a load from a stub to get the address, emit the
10120   // load.
10121   if (isGlobalStubReference(OpFlag))
10122     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10123                          MachinePointerInfo::getGOT(), false, false, false, 0);
10124
10125   return Result;
10126 }
10127
10128 SDValue
10129 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10130   // Create the TargetBlockAddressAddress node.
10131   unsigned char OpFlags =
10132     Subtarget->ClassifyBlockAddressReference();
10133   CodeModel::Model M = DAG.getTarget().getCodeModel();
10134   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10135   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10136   SDLoc dl(Op);
10137   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10138                                              OpFlags);
10139
10140   if (Subtarget->isPICStyleRIPRel() &&
10141       (M == CodeModel::Small || M == CodeModel::Kernel))
10142     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10143   else
10144     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10145
10146   // With PIC, the address is actually $g + Offset.
10147   if (isGlobalRelativeToPICBase(OpFlags)) {
10148     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10149                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10150                          Result);
10151   }
10152
10153   return Result;
10154 }
10155
10156 SDValue
10157 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10158                                       int64_t Offset, SelectionDAG &DAG) const {
10159   // Create the TargetGlobalAddress node, folding in the constant
10160   // offset if it is legal.
10161   unsigned char OpFlags =
10162       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10163   CodeModel::Model M = DAG.getTarget().getCodeModel();
10164   SDValue Result;
10165   if (OpFlags == X86II::MO_NO_FLAG &&
10166       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10167     // A direct static reference to a global.
10168     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10169     Offset = 0;
10170   } else {
10171     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10172   }
10173
10174   if (Subtarget->isPICStyleRIPRel() &&
10175       (M == CodeModel::Small || M == CodeModel::Kernel))
10176     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10177   else
10178     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10179
10180   // With PIC, the address is actually $g + Offset.
10181   if (isGlobalRelativeToPICBase(OpFlags)) {
10182     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10183                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10184                          Result);
10185   }
10186
10187   // For globals that require a load from a stub to get the address, emit the
10188   // load.
10189   if (isGlobalStubReference(OpFlags))
10190     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10191                          MachinePointerInfo::getGOT(), false, false, false, 0);
10192
10193   // If there was a non-zero offset that we didn't fold, create an explicit
10194   // addition for it.
10195   if (Offset != 0)
10196     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10197                          DAG.getConstant(Offset, getPointerTy()));
10198
10199   return Result;
10200 }
10201
10202 SDValue
10203 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10204   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10205   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10206   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10207 }
10208
10209 static SDValue
10210 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10211            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10212            unsigned char OperandFlags, bool LocalDynamic = false) {
10213   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10214   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10215   SDLoc dl(GA);
10216   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10217                                            GA->getValueType(0),
10218                                            GA->getOffset(),
10219                                            OperandFlags);
10220
10221   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10222                                            : X86ISD::TLSADDR;
10223
10224   if (InFlag) {
10225     SDValue Ops[] = { Chain,  TGA, *InFlag };
10226     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10227   } else {
10228     SDValue Ops[]  = { Chain, TGA };
10229     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10230   }
10231
10232   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10233   MFI->setAdjustsStack(true);
10234
10235   SDValue Flag = Chain.getValue(1);
10236   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10237 }
10238
10239 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10240 static SDValue
10241 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10242                                 const EVT PtrVT) {
10243   SDValue InFlag;
10244   SDLoc dl(GA);  // ? function entry point might be better
10245   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10246                                    DAG.getNode(X86ISD::GlobalBaseReg,
10247                                                SDLoc(), PtrVT), InFlag);
10248   InFlag = Chain.getValue(1);
10249
10250   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10251 }
10252
10253 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10254 static SDValue
10255 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10256                                 const EVT PtrVT) {
10257   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10258                     X86::RAX, X86II::MO_TLSGD);
10259 }
10260
10261 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10262                                            SelectionDAG &DAG,
10263                                            const EVT PtrVT,
10264                                            bool is64Bit) {
10265   SDLoc dl(GA);
10266
10267   // Get the start address of the TLS block for this module.
10268   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10269       .getInfo<X86MachineFunctionInfo>();
10270   MFI->incNumLocalDynamicTLSAccesses();
10271
10272   SDValue Base;
10273   if (is64Bit) {
10274     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10275                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10276   } else {
10277     SDValue InFlag;
10278     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10279         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10280     InFlag = Chain.getValue(1);
10281     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10282                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10283   }
10284
10285   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10286   // of Base.
10287
10288   // Build x@dtpoff.
10289   unsigned char OperandFlags = X86II::MO_DTPOFF;
10290   unsigned WrapperKind = X86ISD::Wrapper;
10291   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10292                                            GA->getValueType(0),
10293                                            GA->getOffset(), OperandFlags);
10294   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10295
10296   // Add x@dtpoff with the base.
10297   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10298 }
10299
10300 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10301 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10302                                    const EVT PtrVT, TLSModel::Model model,
10303                                    bool is64Bit, bool isPIC) {
10304   SDLoc dl(GA);
10305
10306   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10307   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10308                                                          is64Bit ? 257 : 256));
10309
10310   SDValue ThreadPointer =
10311       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10312                   MachinePointerInfo(Ptr), false, false, false, 0);
10313
10314   unsigned char OperandFlags = 0;
10315   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10316   // initialexec.
10317   unsigned WrapperKind = X86ISD::Wrapper;
10318   if (model == TLSModel::LocalExec) {
10319     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10320   } else if (model == TLSModel::InitialExec) {
10321     if (is64Bit) {
10322       OperandFlags = X86II::MO_GOTTPOFF;
10323       WrapperKind = X86ISD::WrapperRIP;
10324     } else {
10325       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10326     }
10327   } else {
10328     llvm_unreachable("Unexpected model");
10329   }
10330
10331   // emit "addl x@ntpoff,%eax" (local exec)
10332   // or "addl x@indntpoff,%eax" (initial exec)
10333   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10334   SDValue TGA =
10335       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10336                                  GA->getOffset(), OperandFlags);
10337   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10338
10339   if (model == TLSModel::InitialExec) {
10340     if (isPIC && !is64Bit) {
10341       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10342                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10343                            Offset);
10344     }
10345
10346     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10347                          MachinePointerInfo::getGOT(), false, false, false, 0);
10348   }
10349
10350   // The address of the thread local variable is the add of the thread
10351   // pointer with the offset of the variable.
10352   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10353 }
10354
10355 SDValue
10356 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10357
10358   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10359   const GlobalValue *GV = GA->getGlobal();
10360
10361   if (Subtarget->isTargetELF()) {
10362     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10363
10364     switch (model) {
10365       case TLSModel::GeneralDynamic:
10366         if (Subtarget->is64Bit())
10367           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10368         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10369       case TLSModel::LocalDynamic:
10370         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10371                                            Subtarget->is64Bit());
10372       case TLSModel::InitialExec:
10373       case TLSModel::LocalExec:
10374         return LowerToTLSExecModel(
10375             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10376             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10377     }
10378     llvm_unreachable("Unknown TLS model.");
10379   }
10380
10381   if (Subtarget->isTargetDarwin()) {
10382     // Darwin only has one model of TLS.  Lower to that.
10383     unsigned char OpFlag = 0;
10384     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10385                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10386
10387     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10388     // global base reg.
10389     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10390                  !Subtarget->is64Bit();
10391     if (PIC32)
10392       OpFlag = X86II::MO_TLVP_PIC_BASE;
10393     else
10394       OpFlag = X86II::MO_TLVP;
10395     SDLoc DL(Op);
10396     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10397                                                 GA->getValueType(0),
10398                                                 GA->getOffset(), OpFlag);
10399     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10400
10401     // With PIC32, the address is actually $g + Offset.
10402     if (PIC32)
10403       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10404                            DAG.getNode(X86ISD::GlobalBaseReg,
10405                                        SDLoc(), getPointerTy()),
10406                            Offset);
10407
10408     // Lowering the machine isd will make sure everything is in the right
10409     // location.
10410     SDValue Chain = DAG.getEntryNode();
10411     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10412     SDValue Args[] = { Chain, Offset };
10413     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10414
10415     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10416     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10417     MFI->setAdjustsStack(true);
10418
10419     // And our return value (tls address) is in the standard call return value
10420     // location.
10421     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10422     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10423                               Chain.getValue(1));
10424   }
10425
10426   if (Subtarget->isTargetKnownWindowsMSVC() ||
10427       Subtarget->isTargetWindowsGNU()) {
10428     // Just use the implicit TLS architecture
10429     // Need to generate someting similar to:
10430     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10431     //                                  ; from TEB
10432     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10433     //   mov     rcx, qword [rdx+rcx*8]
10434     //   mov     eax, .tls$:tlsvar
10435     //   [rax+rcx] contains the address
10436     // Windows 64bit: gs:0x58
10437     // Windows 32bit: fs:__tls_array
10438
10439     SDLoc dl(GA);
10440     SDValue Chain = DAG.getEntryNode();
10441
10442     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10443     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10444     // use its literal value of 0x2C.
10445     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10446                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10447                                                              256)
10448                                         : Type::getInt32PtrTy(*DAG.getContext(),
10449                                                               257));
10450
10451     SDValue TlsArray =
10452         Subtarget->is64Bit()
10453             ? DAG.getIntPtrConstant(0x58)
10454             : (Subtarget->isTargetWindowsGNU()
10455                    ? DAG.getIntPtrConstant(0x2C)
10456                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10457
10458     SDValue ThreadPointer =
10459         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10460                     MachinePointerInfo(Ptr), false, false, false, 0);
10461
10462     // Load the _tls_index variable
10463     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10464     if (Subtarget->is64Bit())
10465       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10466                            IDX, MachinePointerInfo(), MVT::i32,
10467                            false, false, 0);
10468     else
10469       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10470                         false, false, false, 0);
10471
10472     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10473                                     getPointerTy());
10474     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10475
10476     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10477     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10478                       false, false, false, 0);
10479
10480     // Get the offset of start of .tls section
10481     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10482                                              GA->getValueType(0),
10483                                              GA->getOffset(), X86II::MO_SECREL);
10484     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10485
10486     // The address of the thread local variable is the add of the thread
10487     // pointer with the offset of the variable.
10488     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10489   }
10490
10491   llvm_unreachable("TLS not implemented for this target.");
10492 }
10493
10494 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10495 /// and take a 2 x i32 value to shift plus a shift amount.
10496 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10497   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10498   MVT VT = Op.getSimpleValueType();
10499   unsigned VTBits = VT.getSizeInBits();
10500   SDLoc dl(Op);
10501   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10502   SDValue ShOpLo = Op.getOperand(0);
10503   SDValue ShOpHi = Op.getOperand(1);
10504   SDValue ShAmt  = Op.getOperand(2);
10505   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10506   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10507   // during isel.
10508   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10509                                   DAG.getConstant(VTBits - 1, MVT::i8));
10510   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10511                                      DAG.getConstant(VTBits - 1, MVT::i8))
10512                        : DAG.getConstant(0, VT);
10513
10514   SDValue Tmp2, Tmp3;
10515   if (Op.getOpcode() == ISD::SHL_PARTS) {
10516     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10517     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10518   } else {
10519     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10520     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10521   }
10522
10523   // If the shift amount is larger or equal than the width of a part we can't
10524   // rely on the results of shld/shrd. Insert a test and select the appropriate
10525   // values for large shift amounts.
10526   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10527                                 DAG.getConstant(VTBits, MVT::i8));
10528   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10529                              AndNode, DAG.getConstant(0, MVT::i8));
10530
10531   SDValue Hi, Lo;
10532   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10533   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10534   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10535
10536   if (Op.getOpcode() == ISD::SHL_PARTS) {
10537     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10538     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10539   } else {
10540     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10541     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10542   }
10543
10544   SDValue Ops[2] = { Lo, Hi };
10545   return DAG.getMergeValues(Ops, dl);
10546 }
10547
10548 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10549                                            SelectionDAG &DAG) const {
10550   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10551
10552   if (SrcVT.isVector())
10553     return SDValue();
10554
10555   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10556          "Unknown SINT_TO_FP to lower!");
10557
10558   // These are really Legal; return the operand so the caller accepts it as
10559   // Legal.
10560   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10561     return Op;
10562   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10563       Subtarget->is64Bit()) {
10564     return Op;
10565   }
10566
10567   SDLoc dl(Op);
10568   unsigned Size = SrcVT.getSizeInBits()/8;
10569   MachineFunction &MF = DAG.getMachineFunction();
10570   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10571   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10572   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10573                                StackSlot,
10574                                MachinePointerInfo::getFixedStack(SSFI),
10575                                false, false, 0);
10576   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10577 }
10578
10579 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10580                                      SDValue StackSlot,
10581                                      SelectionDAG &DAG) const {
10582   // Build the FILD
10583   SDLoc DL(Op);
10584   SDVTList Tys;
10585   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10586   if (useSSE)
10587     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10588   else
10589     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10590
10591   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10592
10593   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10594   MachineMemOperand *MMO;
10595   if (FI) {
10596     int SSFI = FI->getIndex();
10597     MMO =
10598       DAG.getMachineFunction()
10599       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10600                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10601   } else {
10602     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10603     StackSlot = StackSlot.getOperand(1);
10604   }
10605   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10606   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10607                                            X86ISD::FILD, DL,
10608                                            Tys, Ops, SrcVT, MMO);
10609
10610   if (useSSE) {
10611     Chain = Result.getValue(1);
10612     SDValue InFlag = Result.getValue(2);
10613
10614     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10615     // shouldn't be necessary except that RFP cannot be live across
10616     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10617     MachineFunction &MF = DAG.getMachineFunction();
10618     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10619     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10620     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10621     Tys = DAG.getVTList(MVT::Other);
10622     SDValue Ops[] = {
10623       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10624     };
10625     MachineMemOperand *MMO =
10626       DAG.getMachineFunction()
10627       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10628                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10629
10630     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10631                                     Ops, Op.getValueType(), MMO);
10632     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10633                          MachinePointerInfo::getFixedStack(SSFI),
10634                          false, false, false, 0);
10635   }
10636
10637   return Result;
10638 }
10639
10640 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10641 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10642                                                SelectionDAG &DAG) const {
10643   // This algorithm is not obvious. Here it is what we're trying to output:
10644   /*
10645      movq       %rax,  %xmm0
10646      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10647      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10648      #ifdef __SSE3__
10649        haddpd   %xmm0, %xmm0
10650      #else
10651        pshufd   $0x4e, %xmm0, %xmm1
10652        addpd    %xmm1, %xmm0
10653      #endif
10654   */
10655
10656   SDLoc dl(Op);
10657   LLVMContext *Context = DAG.getContext();
10658
10659   // Build some magic constants.
10660   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10661   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10662   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10663
10664   SmallVector<Constant*,2> CV1;
10665   CV1.push_back(
10666     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10667                                       APInt(64, 0x4330000000000000ULL))));
10668   CV1.push_back(
10669     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10670                                       APInt(64, 0x4530000000000000ULL))));
10671   Constant *C1 = ConstantVector::get(CV1);
10672   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10673
10674   // Load the 64-bit value into an XMM register.
10675   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10676                             Op.getOperand(0));
10677   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10678                               MachinePointerInfo::getConstantPool(),
10679                               false, false, false, 16);
10680   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10681                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10682                               CLod0);
10683
10684   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10685                               MachinePointerInfo::getConstantPool(),
10686                               false, false, false, 16);
10687   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10688   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10689   SDValue Result;
10690
10691   if (Subtarget->hasSSE3()) {
10692     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10693     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10694   } else {
10695     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10696     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10697                                            S2F, 0x4E, DAG);
10698     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10699                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10700                          Sub);
10701   }
10702
10703   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10704                      DAG.getIntPtrConstant(0));
10705 }
10706
10707 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10708 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10709                                                SelectionDAG &DAG) const {
10710   SDLoc dl(Op);
10711   // FP constant to bias correct the final result.
10712   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10713                                    MVT::f64);
10714
10715   // Load the 32-bit value into an XMM register.
10716   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10717                              Op.getOperand(0));
10718
10719   // Zero out the upper parts of the register.
10720   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10721
10722   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10723                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10724                      DAG.getIntPtrConstant(0));
10725
10726   // Or the load with the bias.
10727   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10728                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10729                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10730                                                    MVT::v2f64, Load)),
10731                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10732                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10733                                                    MVT::v2f64, Bias)));
10734   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10735                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10736                    DAG.getIntPtrConstant(0));
10737
10738   // Subtract the bias.
10739   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10740
10741   // Handle final rounding.
10742   EVT DestVT = Op.getValueType();
10743
10744   if (DestVT.bitsLT(MVT::f64))
10745     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10746                        DAG.getIntPtrConstant(0));
10747   if (DestVT.bitsGT(MVT::f64))
10748     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10749
10750   // Handle final rounding.
10751   return Sub;
10752 }
10753
10754 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10755                                                SelectionDAG &DAG) const {
10756   SDValue N0 = Op.getOperand(0);
10757   MVT SVT = N0.getSimpleValueType();
10758   SDLoc dl(Op);
10759
10760   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10761           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10762          "Custom UINT_TO_FP is not supported!");
10763
10764   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10765   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10766                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10767 }
10768
10769 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10770                                            SelectionDAG &DAG) const {
10771   SDValue N0 = Op.getOperand(0);
10772   SDLoc dl(Op);
10773
10774   if (Op.getValueType().isVector())
10775     return lowerUINT_TO_FP_vec(Op, DAG);
10776
10777   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10778   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10779   // the optimization here.
10780   if (DAG.SignBitIsZero(N0))
10781     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10782
10783   MVT SrcVT = N0.getSimpleValueType();
10784   MVT DstVT = Op.getSimpleValueType();
10785   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10786     return LowerUINT_TO_FP_i64(Op, DAG);
10787   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10788     return LowerUINT_TO_FP_i32(Op, DAG);
10789   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10790     return SDValue();
10791
10792   // Make a 64-bit buffer, and use it to build an FILD.
10793   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10794   if (SrcVT == MVT::i32) {
10795     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10796     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10797                                      getPointerTy(), StackSlot, WordOff);
10798     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10799                                   StackSlot, MachinePointerInfo(),
10800                                   false, false, 0);
10801     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10802                                   OffsetSlot, MachinePointerInfo(),
10803                                   false, false, 0);
10804     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10805     return Fild;
10806   }
10807
10808   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10809   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10810                                StackSlot, MachinePointerInfo(),
10811                                false, false, 0);
10812   // For i64 source, we need to add the appropriate power of 2 if the input
10813   // was negative.  This is the same as the optimization in
10814   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10815   // we must be careful to do the computation in x87 extended precision, not
10816   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10817   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10818   MachineMemOperand *MMO =
10819     DAG.getMachineFunction()
10820     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10821                           MachineMemOperand::MOLoad, 8, 8);
10822
10823   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10824   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10825   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10826                                          MVT::i64, MMO);
10827
10828   APInt FF(32, 0x5F800000ULL);
10829
10830   // Check whether the sign bit is set.
10831   SDValue SignSet = DAG.getSetCC(dl,
10832                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10833                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10834                                  ISD::SETLT);
10835
10836   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10837   SDValue FudgePtr = DAG.getConstantPool(
10838                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10839                                          getPointerTy());
10840
10841   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10842   SDValue Zero = DAG.getIntPtrConstant(0);
10843   SDValue Four = DAG.getIntPtrConstant(4);
10844   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10845                                Zero, Four);
10846   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10847
10848   // Load the value out, extending it from f32 to f80.
10849   // FIXME: Avoid the extend by constructing the right constant pool?
10850   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10851                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10852                                  MVT::f32, false, false, 4);
10853   // Extend everything to 80 bits to force it to be done on x87.
10854   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10855   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10856 }
10857
10858 std::pair<SDValue,SDValue>
10859 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10860                                     bool IsSigned, bool IsReplace) const {
10861   SDLoc DL(Op);
10862
10863   EVT DstTy = Op.getValueType();
10864
10865   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10866     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10867     DstTy = MVT::i64;
10868   }
10869
10870   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10871          DstTy.getSimpleVT() >= MVT::i16 &&
10872          "Unknown FP_TO_INT to lower!");
10873
10874   // These are really Legal.
10875   if (DstTy == MVT::i32 &&
10876       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10877     return std::make_pair(SDValue(), SDValue());
10878   if (Subtarget->is64Bit() &&
10879       DstTy == MVT::i64 &&
10880       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10881     return std::make_pair(SDValue(), SDValue());
10882
10883   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10884   // stack slot, or into the FTOL runtime function.
10885   MachineFunction &MF = DAG.getMachineFunction();
10886   unsigned MemSize = DstTy.getSizeInBits()/8;
10887   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10888   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10889
10890   unsigned Opc;
10891   if (!IsSigned && isIntegerTypeFTOL(DstTy))
10892     Opc = X86ISD::WIN_FTOL;
10893   else
10894     switch (DstTy.getSimpleVT().SimpleTy) {
10895     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10896     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10897     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10898     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10899     }
10900
10901   SDValue Chain = DAG.getEntryNode();
10902   SDValue Value = Op.getOperand(0);
10903   EVT TheVT = Op.getOperand(0).getValueType();
10904   // FIXME This causes a redundant load/store if the SSE-class value is already
10905   // in memory, such as if it is on the callstack.
10906   if (isScalarFPTypeInSSEReg(TheVT)) {
10907     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10908     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10909                          MachinePointerInfo::getFixedStack(SSFI),
10910                          false, false, 0);
10911     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10912     SDValue Ops[] = {
10913       Chain, StackSlot, DAG.getValueType(TheVT)
10914     };
10915
10916     MachineMemOperand *MMO =
10917       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10918                               MachineMemOperand::MOLoad, MemSize, MemSize);
10919     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
10920     Chain = Value.getValue(1);
10921     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10922     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10923   }
10924
10925   MachineMemOperand *MMO =
10926     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10927                             MachineMemOperand::MOStore, MemSize, MemSize);
10928
10929   if (Opc != X86ISD::WIN_FTOL) {
10930     // Build the FP_TO_INT*_IN_MEM
10931     SDValue Ops[] = { Chain, Value, StackSlot };
10932     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
10933                                            Ops, DstTy, MMO);
10934     return std::make_pair(FIST, StackSlot);
10935   } else {
10936     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
10937       DAG.getVTList(MVT::Other, MVT::Glue),
10938       Chain, Value);
10939     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
10940       MVT::i32, ftol.getValue(1));
10941     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
10942       MVT::i32, eax.getValue(2));
10943     SDValue Ops[] = { eax, edx };
10944     SDValue pair = IsReplace
10945       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
10946       : DAG.getMergeValues(Ops, DL);
10947     return std::make_pair(pair, SDValue());
10948   }
10949 }
10950
10951 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
10952                               const X86Subtarget *Subtarget) {
10953   MVT VT = Op->getSimpleValueType(0);
10954   SDValue In = Op->getOperand(0);
10955   MVT InVT = In.getSimpleValueType();
10956   SDLoc dl(Op);
10957
10958   // Optimize vectors in AVX mode:
10959   //
10960   //   v8i16 -> v8i32
10961   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
10962   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
10963   //   Concat upper and lower parts.
10964   //
10965   //   v4i32 -> v4i64
10966   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
10967   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
10968   //   Concat upper and lower parts.
10969   //
10970
10971   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
10972       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
10973       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
10974     return SDValue();
10975
10976   if (Subtarget->hasInt256())
10977     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
10978
10979   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
10980   SDValue Undef = DAG.getUNDEF(InVT);
10981   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
10982   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
10983   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
10984
10985   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
10986                              VT.getVectorNumElements()/2);
10987
10988   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
10989   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
10990
10991   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10992 }
10993
10994 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
10995                                         SelectionDAG &DAG) {
10996   MVT VT = Op->getSimpleValueType(0);
10997   SDValue In = Op->getOperand(0);
10998   MVT InVT = In.getSimpleValueType();
10999   SDLoc DL(Op);
11000   unsigned int NumElts = VT.getVectorNumElements();
11001   if (NumElts != 8 && NumElts != 16)
11002     return SDValue();
11003
11004   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11005     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11006
11007   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11009   // Now we have only mask extension
11010   assert(InVT.getVectorElementType() == MVT::i1);
11011   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11012   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11013   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11014   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11015   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11016                            MachinePointerInfo::getConstantPool(),
11017                            false, false, false, Alignment);
11018
11019   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11020   if (VT.is512BitVector())
11021     return Brcst;
11022   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11023 }
11024
11025 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11026                                SelectionDAG &DAG) {
11027   if (Subtarget->hasFp256()) {
11028     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11029     if (Res.getNode())
11030       return Res;
11031   }
11032
11033   return SDValue();
11034 }
11035
11036 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11037                                 SelectionDAG &DAG) {
11038   SDLoc DL(Op);
11039   MVT VT = Op.getSimpleValueType();
11040   SDValue In = Op.getOperand(0);
11041   MVT SVT = In.getSimpleValueType();
11042
11043   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11044     return LowerZERO_EXTEND_AVX512(Op, DAG);
11045
11046   if (Subtarget->hasFp256()) {
11047     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11048     if (Res.getNode())
11049       return Res;
11050   }
11051
11052   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11053          VT.getVectorNumElements() != SVT.getVectorNumElements());
11054   return SDValue();
11055 }
11056
11057 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11058   SDLoc DL(Op);
11059   MVT VT = Op.getSimpleValueType();
11060   SDValue In = Op.getOperand(0);
11061   MVT InVT = In.getSimpleValueType();
11062
11063   if (VT == MVT::i1) {
11064     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11065            "Invalid scalar TRUNCATE operation");
11066     if (InVT == MVT::i32)
11067       return SDValue();
11068     if (InVT.getSizeInBits() == 64)
11069       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11070     else if (InVT.getSizeInBits() < 32)
11071       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11072     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11073   }
11074   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11075          "Invalid TRUNCATE operation");
11076
11077   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11078     if (VT.getVectorElementType().getSizeInBits() >=8)
11079       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11080
11081     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11082     unsigned NumElts = InVT.getVectorNumElements();
11083     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11084     if (InVT.getSizeInBits() < 512) {
11085       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11086       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11087       InVT = ExtVT;
11088     }
11089     
11090     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11091     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11092     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11093     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11094     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11095                            MachinePointerInfo::getConstantPool(),
11096                            false, false, false, Alignment);
11097     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11098     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11099     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11100   }
11101
11102   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11103     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11104     if (Subtarget->hasInt256()) {
11105       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11106       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11107       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11108                                 ShufMask);
11109       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11110                          DAG.getIntPtrConstant(0));
11111     }
11112
11113     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11114                                DAG.getIntPtrConstant(0));
11115     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11116                                DAG.getIntPtrConstant(2));
11117     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11118     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11119     static const int ShufMask[] = {0, 2, 4, 6};
11120     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11121   }
11122
11123   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11124     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11125     if (Subtarget->hasInt256()) {
11126       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11127
11128       SmallVector<SDValue,32> pshufbMask;
11129       for (unsigned i = 0; i < 2; ++i) {
11130         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11131         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11132         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11133         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11134         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11135         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11136         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11137         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11138         for (unsigned j = 0; j < 8; ++j)
11139           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11140       }
11141       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11142       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11143       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11144
11145       static const int ShufMask[] = {0,  2,  -1,  -1};
11146       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11147                                 &ShufMask[0]);
11148       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11149                        DAG.getIntPtrConstant(0));
11150       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11151     }
11152
11153     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11154                                DAG.getIntPtrConstant(0));
11155
11156     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11157                                DAG.getIntPtrConstant(4));
11158
11159     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11160     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11161
11162     // The PSHUFB mask:
11163     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11164                                    -1, -1, -1, -1, -1, -1, -1, -1};
11165
11166     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11167     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11168     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11169
11170     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11171     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11172
11173     // The MOVLHPS Mask:
11174     static const int ShufMask2[] = {0, 1, 4, 5};
11175     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11176     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11177   }
11178
11179   // Handle truncation of V256 to V128 using shuffles.
11180   if (!VT.is128BitVector() || !InVT.is256BitVector())
11181     return SDValue();
11182
11183   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11184
11185   unsigned NumElems = VT.getVectorNumElements();
11186   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11187
11188   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11189   // Prepare truncation shuffle mask
11190   for (unsigned i = 0; i != NumElems; ++i)
11191     MaskVec[i] = i * 2;
11192   SDValue V = DAG.getVectorShuffle(NVT, DL,
11193                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11194                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11195   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11196                      DAG.getIntPtrConstant(0));
11197 }
11198
11199 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11200                                            SelectionDAG &DAG) const {
11201   assert(!Op.getSimpleValueType().isVector());
11202
11203   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11204     /*IsSigned=*/ true, /*IsReplace=*/ false);
11205   SDValue FIST = Vals.first, StackSlot = Vals.second;
11206   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11207   if (!FIST.getNode()) return Op;
11208
11209   if (StackSlot.getNode())
11210     // Load the result.
11211     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11212                        FIST, StackSlot, MachinePointerInfo(),
11213                        false, false, false, 0);
11214
11215   // The node is the result.
11216   return FIST;
11217 }
11218
11219 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11220                                            SelectionDAG &DAG) const {
11221   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11222     /*IsSigned=*/ false, /*IsReplace=*/ false);
11223   SDValue FIST = Vals.first, StackSlot = Vals.second;
11224   assert(FIST.getNode() && "Unexpected failure");
11225
11226   if (StackSlot.getNode())
11227     // Load the result.
11228     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11229                        FIST, StackSlot, MachinePointerInfo(),
11230                        false, false, false, 0);
11231
11232   // The node is the result.
11233   return FIST;
11234 }
11235
11236 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11237   SDLoc DL(Op);
11238   MVT VT = Op.getSimpleValueType();
11239   SDValue In = Op.getOperand(0);
11240   MVT SVT = In.getSimpleValueType();
11241
11242   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11243
11244   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11245                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11246                                  In, DAG.getUNDEF(SVT)));
11247 }
11248
11249 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11250   LLVMContext *Context = DAG.getContext();
11251   SDLoc dl(Op);
11252   MVT VT = Op.getSimpleValueType();
11253   MVT EltVT = VT;
11254   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11255   if (VT.isVector()) {
11256     EltVT = VT.getVectorElementType();
11257     NumElts = VT.getVectorNumElements();
11258   }
11259   Constant *C;
11260   if (EltVT == MVT::f64)
11261     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11262                                           APInt(64, ~(1ULL << 63))));
11263   else
11264     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11265                                           APInt(32, ~(1U << 31))));
11266   C = ConstantVector::getSplat(NumElts, C);
11267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11268   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11269   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11270   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11271                              MachinePointerInfo::getConstantPool(),
11272                              false, false, false, Alignment);
11273   if (VT.isVector()) {
11274     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11275     return DAG.getNode(ISD::BITCAST, dl, VT,
11276                        DAG.getNode(ISD::AND, dl, ANDVT,
11277                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11278                                                Op.getOperand(0)),
11279                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11280   }
11281   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11282 }
11283
11284 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11285   LLVMContext *Context = DAG.getContext();
11286   SDLoc dl(Op);
11287   MVT VT = Op.getSimpleValueType();
11288   MVT EltVT = VT;
11289   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11290   if (VT.isVector()) {
11291     EltVT = VT.getVectorElementType();
11292     NumElts = VT.getVectorNumElements();
11293   }
11294   Constant *C;
11295   if (EltVT == MVT::f64)
11296     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11297                                           APInt(64, 1ULL << 63)));
11298   else
11299     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11300                                           APInt(32, 1U << 31)));
11301   C = ConstantVector::getSplat(NumElts, C);
11302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11303   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11304   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11305   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11306                              MachinePointerInfo::getConstantPool(),
11307                              false, false, false, Alignment);
11308   if (VT.isVector()) {
11309     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11310     return DAG.getNode(ISD::BITCAST, dl, VT,
11311                        DAG.getNode(ISD::XOR, dl, XORVT,
11312                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11313                                                Op.getOperand(0)),
11314                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11315   }
11316
11317   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11318 }
11319
11320 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11322   LLVMContext *Context = DAG.getContext();
11323   SDValue Op0 = Op.getOperand(0);
11324   SDValue Op1 = Op.getOperand(1);
11325   SDLoc dl(Op);
11326   MVT VT = Op.getSimpleValueType();
11327   MVT SrcVT = Op1.getSimpleValueType();
11328
11329   // If second operand is smaller, extend it first.
11330   if (SrcVT.bitsLT(VT)) {
11331     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11332     SrcVT = VT;
11333   }
11334   // And if it is bigger, shrink it first.
11335   if (SrcVT.bitsGT(VT)) {
11336     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11337     SrcVT = VT;
11338   }
11339
11340   // At this point the operands and the result should have the same
11341   // type, and that won't be f80 since that is not custom lowered.
11342
11343   // First get the sign bit of second operand.
11344   SmallVector<Constant*,4> CV;
11345   if (SrcVT == MVT::f64) {
11346     const fltSemantics &Sem = APFloat::IEEEdouble;
11347     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11348     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11349   } else {
11350     const fltSemantics &Sem = APFloat::IEEEsingle;
11351     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11352     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11353     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11354     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11355   }
11356   Constant *C = ConstantVector::get(CV);
11357   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11358   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11359                               MachinePointerInfo::getConstantPool(),
11360                               false, false, false, 16);
11361   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11362
11363   // Shift sign bit right or left if the two operands have different types.
11364   if (SrcVT.bitsGT(VT)) {
11365     // Op0 is MVT::f32, Op1 is MVT::f64.
11366     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11367     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11368                           DAG.getConstant(32, MVT::i32));
11369     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11370     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11371                           DAG.getIntPtrConstant(0));
11372   }
11373
11374   // Clear first operand sign bit.
11375   CV.clear();
11376   if (VT == MVT::f64) {
11377     const fltSemantics &Sem = APFloat::IEEEdouble;
11378     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11379                                                    APInt(64, ~(1ULL << 63)))));
11380     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11381   } else {
11382     const fltSemantics &Sem = APFloat::IEEEsingle;
11383     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11384                                                    APInt(32, ~(1U << 31)))));
11385     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11386     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11387     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11388   }
11389   C = ConstantVector::get(CV);
11390   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11391   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11392                               MachinePointerInfo::getConstantPool(),
11393                               false, false, false, 16);
11394   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11395
11396   // Or the value with the sign bit.
11397   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11398 }
11399
11400 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11401   SDValue N0 = Op.getOperand(0);
11402   SDLoc dl(Op);
11403   MVT VT = Op.getSimpleValueType();
11404
11405   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11406   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11407                                   DAG.getConstant(1, VT));
11408   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11409 }
11410
11411 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11412 //
11413 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11414                                       SelectionDAG &DAG) {
11415   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11416
11417   if (!Subtarget->hasSSE41())
11418     return SDValue();
11419
11420   if (!Op->hasOneUse())
11421     return SDValue();
11422
11423   SDNode *N = Op.getNode();
11424   SDLoc DL(N);
11425
11426   SmallVector<SDValue, 8> Opnds;
11427   DenseMap<SDValue, unsigned> VecInMap;
11428   SmallVector<SDValue, 8> VecIns;
11429   EVT VT = MVT::Other;
11430
11431   // Recognize a special case where a vector is casted into wide integer to
11432   // test all 0s.
11433   Opnds.push_back(N->getOperand(0));
11434   Opnds.push_back(N->getOperand(1));
11435
11436   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11437     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11438     // BFS traverse all OR'd operands.
11439     if (I->getOpcode() == ISD::OR) {
11440       Opnds.push_back(I->getOperand(0));
11441       Opnds.push_back(I->getOperand(1));
11442       // Re-evaluate the number of nodes to be traversed.
11443       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11444       continue;
11445     }
11446
11447     // Quit if a non-EXTRACT_VECTOR_ELT
11448     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11449       return SDValue();
11450
11451     // Quit if without a constant index.
11452     SDValue Idx = I->getOperand(1);
11453     if (!isa<ConstantSDNode>(Idx))
11454       return SDValue();
11455
11456     SDValue ExtractedFromVec = I->getOperand(0);
11457     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11458     if (M == VecInMap.end()) {
11459       VT = ExtractedFromVec.getValueType();
11460       // Quit if not 128/256-bit vector.
11461       if (!VT.is128BitVector() && !VT.is256BitVector())
11462         return SDValue();
11463       // Quit if not the same type.
11464       if (VecInMap.begin() != VecInMap.end() &&
11465           VT != VecInMap.begin()->first.getValueType())
11466         return SDValue();
11467       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11468       VecIns.push_back(ExtractedFromVec);
11469     }
11470     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11471   }
11472
11473   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11474          "Not extracted from 128-/256-bit vector.");
11475
11476   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11477
11478   for (DenseMap<SDValue, unsigned>::const_iterator
11479         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11480     // Quit if not all elements are used.
11481     if (I->second != FullMask)
11482       return SDValue();
11483   }
11484
11485   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11486
11487   // Cast all vectors into TestVT for PTEST.
11488   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11489     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11490
11491   // If more than one full vectors are evaluated, OR them first before PTEST.
11492   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11493     // Each iteration will OR 2 nodes and append the result until there is only
11494     // 1 node left, i.e. the final OR'd value of all vectors.
11495     SDValue LHS = VecIns[Slot];
11496     SDValue RHS = VecIns[Slot + 1];
11497     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11498   }
11499
11500   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11501                      VecIns.back(), VecIns.back());
11502 }
11503
11504 /// \brief return true if \c Op has a use that doesn't just read flags.
11505 static bool hasNonFlagsUse(SDValue Op) {
11506   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11507        ++UI) {
11508     SDNode *User = *UI;
11509     unsigned UOpNo = UI.getOperandNo();
11510     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11511       // Look pass truncate.
11512       UOpNo = User->use_begin().getOperandNo();
11513       User = *User->use_begin();
11514     }
11515
11516     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11517         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11518       return true;
11519   }
11520   return false;
11521 }
11522
11523 /// Emit nodes that will be selected as "test Op0,Op0", or something
11524 /// equivalent.
11525 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11526                                     SelectionDAG &DAG) const {
11527   if (Op.getValueType() == MVT::i1)
11528     // KORTEST instruction should be selected
11529     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11530                        DAG.getConstant(0, Op.getValueType()));
11531
11532   // CF and OF aren't always set the way we want. Determine which
11533   // of these we need.
11534   bool NeedCF = false;
11535   bool NeedOF = false;
11536   switch (X86CC) {
11537   default: break;
11538   case X86::COND_A: case X86::COND_AE:
11539   case X86::COND_B: case X86::COND_BE:
11540     NeedCF = true;
11541     break;
11542   case X86::COND_G: case X86::COND_GE:
11543   case X86::COND_L: case X86::COND_LE:
11544   case X86::COND_O: case X86::COND_NO: {
11545     // Check if we really need to set the
11546     // Overflow flag. If NoSignedWrap is present
11547     // that is not actually needed.
11548     switch (Op->getOpcode()) {
11549     case ISD::ADD:
11550     case ISD::SUB:
11551     case ISD::MUL:
11552     case ISD::SHL: {
11553       const BinaryWithFlagsSDNode *BinNode =
11554           cast<BinaryWithFlagsSDNode>(Op.getNode());
11555       if (BinNode->hasNoSignedWrap())
11556         break;
11557     }
11558     default:
11559       NeedOF = true;
11560       break;
11561     }
11562     break;
11563   }
11564   }
11565   // See if we can use the EFLAGS value from the operand instead of
11566   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11567   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11568   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11569     // Emit a CMP with 0, which is the TEST pattern.
11570     //if (Op.getValueType() == MVT::i1)
11571     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11572     //                     DAG.getConstant(0, MVT::i1));
11573     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11574                        DAG.getConstant(0, Op.getValueType()));
11575   }
11576   unsigned Opcode = 0;
11577   unsigned NumOperands = 0;
11578
11579   // Truncate operations may prevent the merge of the SETCC instruction
11580   // and the arithmetic instruction before it. Attempt to truncate the operands
11581   // of the arithmetic instruction and use a reduced bit-width instruction.
11582   bool NeedTruncation = false;
11583   SDValue ArithOp = Op;
11584   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11585     SDValue Arith = Op->getOperand(0);
11586     // Both the trunc and the arithmetic op need to have one user each.
11587     if (Arith->hasOneUse())
11588       switch (Arith.getOpcode()) {
11589         default: break;
11590         case ISD::ADD:
11591         case ISD::SUB:
11592         case ISD::AND:
11593         case ISD::OR:
11594         case ISD::XOR: {
11595           NeedTruncation = true;
11596           ArithOp = Arith;
11597         }
11598       }
11599   }
11600
11601   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11602   // which may be the result of a CAST.  We use the variable 'Op', which is the
11603   // non-casted variable when we check for possible users.
11604   switch (ArithOp.getOpcode()) {
11605   case ISD::ADD:
11606     // Due to an isel shortcoming, be conservative if this add is likely to be
11607     // selected as part of a load-modify-store instruction. When the root node
11608     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11609     // uses of other nodes in the match, such as the ADD in this case. This
11610     // leads to the ADD being left around and reselected, with the result being
11611     // two adds in the output.  Alas, even if none our users are stores, that
11612     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11613     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11614     // climbing the DAG back to the root, and it doesn't seem to be worth the
11615     // effort.
11616     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11617          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11618       if (UI->getOpcode() != ISD::CopyToReg &&
11619           UI->getOpcode() != ISD::SETCC &&
11620           UI->getOpcode() != ISD::STORE)
11621         goto default_case;
11622
11623     if (ConstantSDNode *C =
11624         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11625       // An add of one will be selected as an INC.
11626       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11627         Opcode = X86ISD::INC;
11628         NumOperands = 1;
11629         break;
11630       }
11631
11632       // An add of negative one (subtract of one) will be selected as a DEC.
11633       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11634         Opcode = X86ISD::DEC;
11635         NumOperands = 1;
11636         break;
11637       }
11638     }
11639
11640     // Otherwise use a regular EFLAGS-setting add.
11641     Opcode = X86ISD::ADD;
11642     NumOperands = 2;
11643     break;
11644   case ISD::SHL:
11645   case ISD::SRL:
11646     // If we have a constant logical shift that's only used in a comparison
11647     // against zero turn it into an equivalent AND. This allows turning it into
11648     // a TEST instruction later.
11649     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11650         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11651       EVT VT = Op.getValueType();
11652       unsigned BitWidth = VT.getSizeInBits();
11653       unsigned ShAmt = Op->getConstantOperandVal(1);
11654       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11655         break;
11656       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11657                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11658                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11659       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11660         break;
11661       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11662                                 DAG.getConstant(Mask, VT));
11663       DAG.ReplaceAllUsesWith(Op, New);
11664       Op = New;
11665     }
11666     break;
11667
11668   case ISD::AND:
11669     // If the primary and result isn't used, don't bother using X86ISD::AND,
11670     // because a TEST instruction will be better.
11671     if (!hasNonFlagsUse(Op))
11672       break;
11673     // FALL THROUGH
11674   case ISD::SUB:
11675   case ISD::OR:
11676   case ISD::XOR:
11677     // Due to the ISEL shortcoming noted above, be conservative if this op is
11678     // likely to be selected as part of a load-modify-store instruction.
11679     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11680            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11681       if (UI->getOpcode() == ISD::STORE)
11682         goto default_case;
11683
11684     // Otherwise use a regular EFLAGS-setting instruction.
11685     switch (ArithOp.getOpcode()) {
11686     default: llvm_unreachable("unexpected operator!");
11687     case ISD::SUB: Opcode = X86ISD::SUB; break;
11688     case ISD::XOR: Opcode = X86ISD::XOR; break;
11689     case ISD::AND: Opcode = X86ISD::AND; break;
11690     case ISD::OR: {
11691       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11692         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11693         if (EFLAGS.getNode())
11694           return EFLAGS;
11695       }
11696       Opcode = X86ISD::OR;
11697       break;
11698     }
11699     }
11700
11701     NumOperands = 2;
11702     break;
11703   case X86ISD::ADD:
11704   case X86ISD::SUB:
11705   case X86ISD::INC:
11706   case X86ISD::DEC:
11707   case X86ISD::OR:
11708   case X86ISD::XOR:
11709   case X86ISD::AND:
11710     return SDValue(Op.getNode(), 1);
11711   default:
11712   default_case:
11713     break;
11714   }
11715
11716   // If we found that truncation is beneficial, perform the truncation and
11717   // update 'Op'.
11718   if (NeedTruncation) {
11719     EVT VT = Op.getValueType();
11720     SDValue WideVal = Op->getOperand(0);
11721     EVT WideVT = WideVal.getValueType();
11722     unsigned ConvertedOp = 0;
11723     // Use a target machine opcode to prevent further DAGCombine
11724     // optimizations that may separate the arithmetic operations
11725     // from the setcc node.
11726     switch (WideVal.getOpcode()) {
11727       default: break;
11728       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11729       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11730       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11731       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11732       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11733     }
11734
11735     if (ConvertedOp) {
11736       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11737       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11738         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11739         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11740         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11741       }
11742     }
11743   }
11744
11745   if (Opcode == 0)
11746     // Emit a CMP with 0, which is the TEST pattern.
11747     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11748                        DAG.getConstant(0, Op.getValueType()));
11749
11750   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11751   SmallVector<SDValue, 4> Ops;
11752   for (unsigned i = 0; i != NumOperands; ++i)
11753     Ops.push_back(Op.getOperand(i));
11754
11755   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11756   DAG.ReplaceAllUsesWith(Op, New);
11757   return SDValue(New.getNode(), 1);
11758 }
11759
11760 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11761 /// equivalent.
11762 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11763                                    SDLoc dl, SelectionDAG &DAG) const {
11764   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11765     if (C->getAPIntValue() == 0)
11766       return EmitTest(Op0, X86CC, dl, DAG);
11767
11768      if (Op0.getValueType() == MVT::i1)
11769        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11770   }
11771  
11772   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11773        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11774     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11775     // This avoids subregister aliasing issues. Keep the smaller reference 
11776     // if we're optimizing for size, however, as that'll allow better folding 
11777     // of memory operations.
11778     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11779         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11780              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11781         !Subtarget->isAtom()) {
11782       unsigned ExtendOp =
11783           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11784       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11785       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11786     }
11787     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11788     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11789     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11790                               Op0, Op1);
11791     return SDValue(Sub.getNode(), 1);
11792   }
11793   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11794 }
11795
11796 /// Convert a comparison if required by the subtarget.
11797 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11798                                                  SelectionDAG &DAG) const {
11799   // If the subtarget does not support the FUCOMI instruction, floating-point
11800   // comparisons have to be converted.
11801   if (Subtarget->hasCMov() ||
11802       Cmp.getOpcode() != X86ISD::CMP ||
11803       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11804       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11805     return Cmp;
11806
11807   // The instruction selector will select an FUCOM instruction instead of
11808   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11809   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11810   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11811   SDLoc dl(Cmp);
11812   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11813   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11814   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11815                             DAG.getConstant(8, MVT::i8));
11816   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11817   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11818 }
11819
11820 static bool isAllOnes(SDValue V) {
11821   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11822   return C && C->isAllOnesValue();
11823 }
11824
11825 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11826 /// if it's possible.
11827 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11828                                      SDLoc dl, SelectionDAG &DAG) const {
11829   SDValue Op0 = And.getOperand(0);
11830   SDValue Op1 = And.getOperand(1);
11831   if (Op0.getOpcode() == ISD::TRUNCATE)
11832     Op0 = Op0.getOperand(0);
11833   if (Op1.getOpcode() == ISD::TRUNCATE)
11834     Op1 = Op1.getOperand(0);
11835
11836   SDValue LHS, RHS;
11837   if (Op1.getOpcode() == ISD::SHL)
11838     std::swap(Op0, Op1);
11839   if (Op0.getOpcode() == ISD::SHL) {
11840     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11841       if (And00C->getZExtValue() == 1) {
11842         // If we looked past a truncate, check that it's only truncating away
11843         // known zeros.
11844         unsigned BitWidth = Op0.getValueSizeInBits();
11845         unsigned AndBitWidth = And.getValueSizeInBits();
11846         if (BitWidth > AndBitWidth) {
11847           APInt Zeros, Ones;
11848           DAG.computeKnownBits(Op0, Zeros, Ones);
11849           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11850             return SDValue();
11851         }
11852         LHS = Op1;
11853         RHS = Op0.getOperand(1);
11854       }
11855   } else if (Op1.getOpcode() == ISD::Constant) {
11856     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11857     uint64_t AndRHSVal = AndRHS->getZExtValue();
11858     SDValue AndLHS = Op0;
11859
11860     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11861       LHS = AndLHS.getOperand(0);
11862       RHS = AndLHS.getOperand(1);
11863     }
11864
11865     // Use BT if the immediate can't be encoded in a TEST instruction.
11866     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11867       LHS = AndLHS;
11868       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11869     }
11870   }
11871
11872   if (LHS.getNode()) {
11873     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11874     // instruction.  Since the shift amount is in-range-or-undefined, we know
11875     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11876     // the encoding for the i16 version is larger than the i32 version.
11877     // Also promote i16 to i32 for performance / code size reason.
11878     if (LHS.getValueType() == MVT::i8 ||
11879         LHS.getValueType() == MVT::i16)
11880       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11881
11882     // If the operand types disagree, extend the shift amount to match.  Since
11883     // BT ignores high bits (like shifts) we can use anyextend.
11884     if (LHS.getValueType() != RHS.getValueType())
11885       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11886
11887     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11888     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11889     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11890                        DAG.getConstant(Cond, MVT::i8), BT);
11891   }
11892
11893   return SDValue();
11894 }
11895
11896 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11897 /// mask CMPs.
11898 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11899                               SDValue &Op1) {
11900   unsigned SSECC;
11901   bool Swap = false;
11902
11903   // SSE Condition code mapping:
11904   //  0 - EQ
11905   //  1 - LT
11906   //  2 - LE
11907   //  3 - UNORD
11908   //  4 - NEQ
11909   //  5 - NLT
11910   //  6 - NLE
11911   //  7 - ORD
11912   switch (SetCCOpcode) {
11913   default: llvm_unreachable("Unexpected SETCC condition");
11914   case ISD::SETOEQ:
11915   case ISD::SETEQ:  SSECC = 0; break;
11916   case ISD::SETOGT:
11917   case ISD::SETGT:  Swap = true; // Fallthrough
11918   case ISD::SETLT:
11919   case ISD::SETOLT: SSECC = 1; break;
11920   case ISD::SETOGE:
11921   case ISD::SETGE:  Swap = true; // Fallthrough
11922   case ISD::SETLE:
11923   case ISD::SETOLE: SSECC = 2; break;
11924   case ISD::SETUO:  SSECC = 3; break;
11925   case ISD::SETUNE:
11926   case ISD::SETNE:  SSECC = 4; break;
11927   case ISD::SETULE: Swap = true; // Fallthrough
11928   case ISD::SETUGE: SSECC = 5; break;
11929   case ISD::SETULT: Swap = true; // Fallthrough
11930   case ISD::SETUGT: SSECC = 6; break;
11931   case ISD::SETO:   SSECC = 7; break;
11932   case ISD::SETUEQ:
11933   case ISD::SETONE: SSECC = 8; break;
11934   }
11935   if (Swap)
11936     std::swap(Op0, Op1);
11937
11938   return SSECC;
11939 }
11940
11941 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
11942 // ones, and then concatenate the result back.
11943 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
11944   MVT VT = Op.getSimpleValueType();
11945
11946   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
11947          "Unsupported value type for operation");
11948
11949   unsigned NumElems = VT.getVectorNumElements();
11950   SDLoc dl(Op);
11951   SDValue CC = Op.getOperand(2);
11952
11953   // Extract the LHS vectors
11954   SDValue LHS = Op.getOperand(0);
11955   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11956   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11957
11958   // Extract the RHS vectors
11959   SDValue RHS = Op.getOperand(1);
11960   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11961   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11962
11963   // Issue the operation on the smaller types and concatenate the result back
11964   MVT EltVT = VT.getVectorElementType();
11965   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11966   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11967                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
11968                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
11969 }
11970
11971 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
11972                                      const X86Subtarget *Subtarget) {
11973   SDValue Op0 = Op.getOperand(0);
11974   SDValue Op1 = Op.getOperand(1);
11975   SDValue CC = Op.getOperand(2);
11976   MVT VT = Op.getSimpleValueType();
11977   SDLoc dl(Op);
11978
11979   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
11980          Op.getValueType().getScalarType() == MVT::i1 &&
11981          "Cannot set masked compare for this operation");
11982
11983   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
11984   unsigned  Opc = 0;
11985   bool Unsigned = false;
11986   bool Swap = false;
11987   unsigned SSECC;
11988   switch (SetCCOpcode) {
11989   default: llvm_unreachable("Unexpected SETCC condition");
11990   case ISD::SETNE:  SSECC = 4; break;
11991   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
11992   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
11993   case ISD::SETLT:  Swap = true; //fall-through
11994   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
11995   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
11996   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
11997   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
11998   case ISD::SETULE: Unsigned = true; //fall-through
11999   case ISD::SETLE:  SSECC = 2; break;
12000   }
12001
12002   if (Swap)
12003     std::swap(Op0, Op1);
12004   if (Opc)
12005     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12006   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12007   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12008                      DAG.getConstant(SSECC, MVT::i8));
12009 }
12010
12011 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12012 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12013 /// return an empty value.
12014 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12015 {
12016   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12017   if (!BV)
12018     return SDValue();
12019
12020   MVT VT = Op1.getSimpleValueType();
12021   MVT EVT = VT.getVectorElementType();
12022   unsigned n = VT.getVectorNumElements();
12023   SmallVector<SDValue, 8> ULTOp1;
12024
12025   for (unsigned i = 0; i < n; ++i) {
12026     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12027     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12028       return SDValue();
12029
12030     // Avoid underflow.
12031     APInt Val = Elt->getAPIntValue();
12032     if (Val == 0)
12033       return SDValue();
12034
12035     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12036   }
12037
12038   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12039 }
12040
12041 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12042                            SelectionDAG &DAG) {
12043   SDValue Op0 = Op.getOperand(0);
12044   SDValue Op1 = Op.getOperand(1);
12045   SDValue CC = Op.getOperand(2);
12046   MVT VT = Op.getSimpleValueType();
12047   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12048   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12049   SDLoc dl(Op);
12050
12051   if (isFP) {
12052 #ifndef NDEBUG
12053     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12054     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12055 #endif
12056
12057     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12058     unsigned Opc = X86ISD::CMPP;
12059     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12060       assert(VT.getVectorNumElements() <= 16);
12061       Opc = X86ISD::CMPM;
12062     }
12063     // In the two special cases we can't handle, emit two comparisons.
12064     if (SSECC == 8) {
12065       unsigned CC0, CC1;
12066       unsigned CombineOpc;
12067       if (SetCCOpcode == ISD::SETUEQ) {
12068         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12069       } else {
12070         assert(SetCCOpcode == ISD::SETONE);
12071         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12072       }
12073
12074       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12075                                  DAG.getConstant(CC0, MVT::i8));
12076       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12077                                  DAG.getConstant(CC1, MVT::i8));
12078       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12079     }
12080     // Handle all other FP comparisons here.
12081     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12082                        DAG.getConstant(SSECC, MVT::i8));
12083   }
12084
12085   // Break 256-bit integer vector compare into smaller ones.
12086   if (VT.is256BitVector() && !Subtarget->hasInt256())
12087     return Lower256IntVSETCC(Op, DAG);
12088
12089   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12090   EVT OpVT = Op1.getValueType();
12091   if (Subtarget->hasAVX512()) {
12092     if (Op1.getValueType().is512BitVector() ||
12093         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12094       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12095
12096     // In AVX-512 architecture setcc returns mask with i1 elements,
12097     // But there is no compare instruction for i8 and i16 elements.
12098     // We are not talking about 512-bit operands in this case, these
12099     // types are illegal.
12100     if (MaskResult &&
12101         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12102          OpVT.getVectorElementType().getSizeInBits() >= 8))
12103       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12104                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12105   }
12106
12107   // We are handling one of the integer comparisons here.  Since SSE only has
12108   // GT and EQ comparisons for integer, swapping operands and multiple
12109   // operations may be required for some comparisons.
12110   unsigned Opc;
12111   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12112   bool Subus = false;
12113
12114   switch (SetCCOpcode) {
12115   default: llvm_unreachable("Unexpected SETCC condition");
12116   case ISD::SETNE:  Invert = true;
12117   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12118   case ISD::SETLT:  Swap = true;
12119   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12120   case ISD::SETGE:  Swap = true;
12121   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12122                     Invert = true; break;
12123   case ISD::SETULT: Swap = true;
12124   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12125                     FlipSigns = true; break;
12126   case ISD::SETUGE: Swap = true;
12127   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12128                     FlipSigns = true; Invert = true; break;
12129   }
12130
12131   // Special case: Use min/max operations for SETULE/SETUGE
12132   MVT VET = VT.getVectorElementType();
12133   bool hasMinMax =
12134        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12135     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12136
12137   if (hasMinMax) {
12138     switch (SetCCOpcode) {
12139     default: break;
12140     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12141     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12142     }
12143
12144     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12145   }
12146
12147   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12148   if (!MinMax && hasSubus) {
12149     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12150     // Op0 u<= Op1:
12151     //   t = psubus Op0, Op1
12152     //   pcmpeq t, <0..0>
12153     switch (SetCCOpcode) {
12154     default: break;
12155     case ISD::SETULT: {
12156       // If the comparison is against a constant we can turn this into a
12157       // setule.  With psubus, setule does not require a swap.  This is
12158       // beneficial because the constant in the register is no longer
12159       // destructed as the destination so it can be hoisted out of a loop.
12160       // Only do this pre-AVX since vpcmp* is no longer destructive.
12161       if (Subtarget->hasAVX())
12162         break;
12163       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12164       if (ULEOp1.getNode()) {
12165         Op1 = ULEOp1;
12166         Subus = true; Invert = false; Swap = false;
12167       }
12168       break;
12169     }
12170     // Psubus is better than flip-sign because it requires no inversion.
12171     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12172     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12173     }
12174
12175     if (Subus) {
12176       Opc = X86ISD::SUBUS;
12177       FlipSigns = false;
12178     }
12179   }
12180
12181   if (Swap)
12182     std::swap(Op0, Op1);
12183
12184   // Check that the operation in question is available (most are plain SSE2,
12185   // but PCMPGTQ and PCMPEQQ have different requirements).
12186   if (VT == MVT::v2i64) {
12187     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12188       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12189
12190       // First cast everything to the right type.
12191       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12192       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12193
12194       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12195       // bits of the inputs before performing those operations. The lower
12196       // compare is always unsigned.
12197       SDValue SB;
12198       if (FlipSigns) {
12199         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12200       } else {
12201         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12202         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12203         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12204                          Sign, Zero, Sign, Zero);
12205       }
12206       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12207       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12208
12209       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12210       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12211       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12212
12213       // Create masks for only the low parts/high parts of the 64 bit integers.
12214       static const int MaskHi[] = { 1, 1, 3, 3 };
12215       static const int MaskLo[] = { 0, 0, 2, 2 };
12216       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12217       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12218       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12219
12220       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12221       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12222
12223       if (Invert)
12224         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12225
12226       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12227     }
12228
12229     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12230       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12231       // pcmpeqd + pshufd + pand.
12232       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12233
12234       // First cast everything to the right type.
12235       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12236       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12237
12238       // Do the compare.
12239       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12240
12241       // Make sure the lower and upper halves are both all-ones.
12242       static const int Mask[] = { 1, 0, 3, 2 };
12243       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12244       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12245
12246       if (Invert)
12247         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12248
12249       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12250     }
12251   }
12252
12253   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12254   // bits of the inputs before performing those operations.
12255   if (FlipSigns) {
12256     EVT EltVT = VT.getVectorElementType();
12257     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12258     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12259     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12260   }
12261
12262   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12263
12264   // If the logical-not of the result is required, perform that now.
12265   if (Invert)
12266     Result = DAG.getNOT(dl, Result, VT);
12267
12268   if (MinMax)
12269     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12270
12271   if (Subus)
12272     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12273                          getZeroVector(VT, Subtarget, DAG, dl));
12274
12275   return Result;
12276 }
12277
12278 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12279
12280   MVT VT = Op.getSimpleValueType();
12281
12282   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12283
12284   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12285          && "SetCC type must be 8-bit or 1-bit integer");
12286   SDValue Op0 = Op.getOperand(0);
12287   SDValue Op1 = Op.getOperand(1);
12288   SDLoc dl(Op);
12289   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12290
12291   // Optimize to BT if possible.
12292   // Lower (X & (1 << N)) == 0 to BT(X, N).
12293   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12294   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12295   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12296       Op1.getOpcode() == ISD::Constant &&
12297       cast<ConstantSDNode>(Op1)->isNullValue() &&
12298       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12299     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12300     if (NewSetCC.getNode())
12301       return NewSetCC;
12302   }
12303
12304   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12305   // these.
12306   if (Op1.getOpcode() == ISD::Constant &&
12307       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12308        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12309       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12310
12311     // If the input is a setcc, then reuse the input setcc or use a new one with
12312     // the inverted condition.
12313     if (Op0.getOpcode() == X86ISD::SETCC) {
12314       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12315       bool Invert = (CC == ISD::SETNE) ^
12316         cast<ConstantSDNode>(Op1)->isNullValue();
12317       if (!Invert)
12318         return Op0;
12319
12320       CCode = X86::GetOppositeBranchCondition(CCode);
12321       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12322                                   DAG.getConstant(CCode, MVT::i8),
12323                                   Op0.getOperand(1));
12324       if (VT == MVT::i1)
12325         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12326       return SetCC;
12327     }
12328   }
12329   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12330       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12331       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12332
12333     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12334     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12335   }
12336
12337   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12338   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12339   if (X86CC == X86::COND_INVALID)
12340     return SDValue();
12341
12342   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12343   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12344   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12345                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12346   if (VT == MVT::i1)
12347     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12348   return SetCC;
12349 }
12350
12351 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12352 static bool isX86LogicalCmp(SDValue Op) {
12353   unsigned Opc = Op.getNode()->getOpcode();
12354   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12355       Opc == X86ISD::SAHF)
12356     return true;
12357   if (Op.getResNo() == 1 &&
12358       (Opc == X86ISD::ADD ||
12359        Opc == X86ISD::SUB ||
12360        Opc == X86ISD::ADC ||
12361        Opc == X86ISD::SBB ||
12362        Opc == X86ISD::SMUL ||
12363        Opc == X86ISD::UMUL ||
12364        Opc == X86ISD::INC ||
12365        Opc == X86ISD::DEC ||
12366        Opc == X86ISD::OR ||
12367        Opc == X86ISD::XOR ||
12368        Opc == X86ISD::AND))
12369     return true;
12370
12371   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12372     return true;
12373
12374   return false;
12375 }
12376
12377 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12378   if (V.getOpcode() != ISD::TRUNCATE)
12379     return false;
12380
12381   SDValue VOp0 = V.getOperand(0);
12382   unsigned InBits = VOp0.getValueSizeInBits();
12383   unsigned Bits = V.getValueSizeInBits();
12384   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12385 }
12386
12387 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12388   bool addTest = true;
12389   SDValue Cond  = Op.getOperand(0);
12390   SDValue Op1 = Op.getOperand(1);
12391   SDValue Op2 = Op.getOperand(2);
12392   SDLoc DL(Op);
12393   EVT VT = Op1.getValueType();
12394   SDValue CC;
12395
12396   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12397   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12398   // sequence later on.
12399   if (Cond.getOpcode() == ISD::SETCC &&
12400       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12401        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12402       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12403     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12404     int SSECC = translateX86FSETCC(
12405         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12406
12407     if (SSECC != 8) {
12408       if (Subtarget->hasAVX512()) {
12409         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12410                                   DAG.getConstant(SSECC, MVT::i8));
12411         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12412       }
12413       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12414                                 DAG.getConstant(SSECC, MVT::i8));
12415       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12416       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12417       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12418     }
12419   }
12420
12421   if (Cond.getOpcode() == ISD::SETCC) {
12422     SDValue NewCond = LowerSETCC(Cond, DAG);
12423     if (NewCond.getNode())
12424       Cond = NewCond;
12425   }
12426
12427   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12428   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12429   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12430   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12431   if (Cond.getOpcode() == X86ISD::SETCC &&
12432       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12433       isZero(Cond.getOperand(1).getOperand(1))) {
12434     SDValue Cmp = Cond.getOperand(1);
12435
12436     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12437
12438     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12439         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12440       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12441
12442       SDValue CmpOp0 = Cmp.getOperand(0);
12443       // Apply further optimizations for special cases
12444       // (select (x != 0), -1, 0) -> neg & sbb
12445       // (select (x == 0), 0, -1) -> neg & sbb
12446       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12447         if (YC->isNullValue() &&
12448             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12449           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12450           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12451                                     DAG.getConstant(0, CmpOp0.getValueType()),
12452                                     CmpOp0);
12453           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12454                                     DAG.getConstant(X86::COND_B, MVT::i8),
12455                                     SDValue(Neg.getNode(), 1));
12456           return Res;
12457         }
12458
12459       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12460                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12461       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12462
12463       SDValue Res =   // Res = 0 or -1.
12464         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12465                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12466
12467       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12468         Res = DAG.getNOT(DL, Res, Res.getValueType());
12469
12470       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12471       if (!N2C || !N2C->isNullValue())
12472         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12473       return Res;
12474     }
12475   }
12476
12477   // Look past (and (setcc_carry (cmp ...)), 1).
12478   if (Cond.getOpcode() == ISD::AND &&
12479       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12480     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12481     if (C && C->getAPIntValue() == 1)
12482       Cond = Cond.getOperand(0);
12483   }
12484
12485   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12486   // setting operand in place of the X86ISD::SETCC.
12487   unsigned CondOpcode = Cond.getOpcode();
12488   if (CondOpcode == X86ISD::SETCC ||
12489       CondOpcode == X86ISD::SETCC_CARRY) {
12490     CC = Cond.getOperand(0);
12491
12492     SDValue Cmp = Cond.getOperand(1);
12493     unsigned Opc = Cmp.getOpcode();
12494     MVT VT = Op.getSimpleValueType();
12495
12496     bool IllegalFPCMov = false;
12497     if (VT.isFloatingPoint() && !VT.isVector() &&
12498         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12499       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12500
12501     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12502         Opc == X86ISD::BT) { // FIXME
12503       Cond = Cmp;
12504       addTest = false;
12505     }
12506   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12507              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12508              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12509               Cond.getOperand(0).getValueType() != MVT::i8)) {
12510     SDValue LHS = Cond.getOperand(0);
12511     SDValue RHS = Cond.getOperand(1);
12512     unsigned X86Opcode;
12513     unsigned X86Cond;
12514     SDVTList VTs;
12515     switch (CondOpcode) {
12516     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12517     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12518     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12519     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12520     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12521     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12522     default: llvm_unreachable("unexpected overflowing operator");
12523     }
12524     if (CondOpcode == ISD::UMULO)
12525       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12526                           MVT::i32);
12527     else
12528       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12529
12530     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12531
12532     if (CondOpcode == ISD::UMULO)
12533       Cond = X86Op.getValue(2);
12534     else
12535       Cond = X86Op.getValue(1);
12536
12537     CC = DAG.getConstant(X86Cond, MVT::i8);
12538     addTest = false;
12539   }
12540
12541   if (addTest) {
12542     // Look pass the truncate if the high bits are known zero.
12543     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12544         Cond = Cond.getOperand(0);
12545
12546     // We know the result of AND is compared against zero. Try to match
12547     // it to BT.
12548     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12549       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12550       if (NewSetCC.getNode()) {
12551         CC = NewSetCC.getOperand(0);
12552         Cond = NewSetCC.getOperand(1);
12553         addTest = false;
12554       }
12555     }
12556   }
12557
12558   if (addTest) {
12559     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12560     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12561   }
12562
12563   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12564   // a <  b ?  0 : -1 -> RES = setcc_carry
12565   // a >= b ? -1 :  0 -> RES = setcc_carry
12566   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12567   if (Cond.getOpcode() == X86ISD::SUB) {
12568     Cond = ConvertCmpIfNecessary(Cond, DAG);
12569     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12570
12571     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12572         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12573       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12574                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12575       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12576         return DAG.getNOT(DL, Res, Res.getValueType());
12577       return Res;
12578     }
12579   }
12580
12581   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12582   // widen the cmov and push the truncate through. This avoids introducing a new
12583   // branch during isel and doesn't add any extensions.
12584   if (Op.getValueType() == MVT::i8 &&
12585       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12586     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12587     if (T1.getValueType() == T2.getValueType() &&
12588         // Blacklist CopyFromReg to avoid partial register stalls.
12589         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12590       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12591       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12592       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12593     }
12594   }
12595
12596   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12597   // condition is true.
12598   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12599   SDValue Ops[] = { Op2, Op1, CC, Cond };
12600   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12601 }
12602
12603 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12604   MVT VT = Op->getSimpleValueType(0);
12605   SDValue In = Op->getOperand(0);
12606   MVT InVT = In.getSimpleValueType();
12607   SDLoc dl(Op);
12608
12609   unsigned int NumElts = VT.getVectorNumElements();
12610   if (NumElts != 8 && NumElts != 16)
12611     return SDValue();
12612
12613   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12614     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12615
12616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12617   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12618
12619   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12620   Constant *C = ConstantInt::get(*DAG.getContext(),
12621     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12622
12623   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12624   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12625   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12626                           MachinePointerInfo::getConstantPool(),
12627                           false, false, false, Alignment);
12628   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12629   if (VT.is512BitVector())
12630     return Brcst;
12631   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12632 }
12633
12634 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12635                                 SelectionDAG &DAG) {
12636   MVT VT = Op->getSimpleValueType(0);
12637   SDValue In = Op->getOperand(0);
12638   MVT InVT = In.getSimpleValueType();
12639   SDLoc dl(Op);
12640
12641   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12642     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12643
12644   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12645       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12646       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12647     return SDValue();
12648
12649   if (Subtarget->hasInt256())
12650     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12651
12652   // Optimize vectors in AVX mode
12653   // Sign extend  v8i16 to v8i32 and
12654   //              v4i32 to v4i64
12655   //
12656   // Divide input vector into two parts
12657   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12658   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12659   // concat the vectors to original VT
12660
12661   unsigned NumElems = InVT.getVectorNumElements();
12662   SDValue Undef = DAG.getUNDEF(InVT);
12663
12664   SmallVector<int,8> ShufMask1(NumElems, -1);
12665   for (unsigned i = 0; i != NumElems/2; ++i)
12666     ShufMask1[i] = i;
12667
12668   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12669
12670   SmallVector<int,8> ShufMask2(NumElems, -1);
12671   for (unsigned i = 0; i != NumElems/2; ++i)
12672     ShufMask2[i] = i + NumElems/2;
12673
12674   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12675
12676   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12677                                 VT.getVectorNumElements()/2);
12678
12679   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12680   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12681
12682   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12683 }
12684
12685 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12686 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12687 // from the AND / OR.
12688 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12689   Opc = Op.getOpcode();
12690   if (Opc != ISD::OR && Opc != ISD::AND)
12691     return false;
12692   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12693           Op.getOperand(0).hasOneUse() &&
12694           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12695           Op.getOperand(1).hasOneUse());
12696 }
12697
12698 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12699 // 1 and that the SETCC node has a single use.
12700 static bool isXor1OfSetCC(SDValue Op) {
12701   if (Op.getOpcode() != ISD::XOR)
12702     return false;
12703   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12704   if (N1C && N1C->getAPIntValue() == 1) {
12705     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12706       Op.getOperand(0).hasOneUse();
12707   }
12708   return false;
12709 }
12710
12711 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12712   bool addTest = true;
12713   SDValue Chain = Op.getOperand(0);
12714   SDValue Cond  = Op.getOperand(1);
12715   SDValue Dest  = Op.getOperand(2);
12716   SDLoc dl(Op);
12717   SDValue CC;
12718   bool Inverted = false;
12719
12720   if (Cond.getOpcode() == ISD::SETCC) {
12721     // Check for setcc([su]{add,sub,mul}o == 0).
12722     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12723         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12724         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12725         Cond.getOperand(0).getResNo() == 1 &&
12726         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12727          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12728          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12729          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12730          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12731          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12732       Inverted = true;
12733       Cond = Cond.getOperand(0);
12734     } else {
12735       SDValue NewCond = LowerSETCC(Cond, DAG);
12736       if (NewCond.getNode())
12737         Cond = NewCond;
12738     }
12739   }
12740 #if 0
12741   // FIXME: LowerXALUO doesn't handle these!!
12742   else if (Cond.getOpcode() == X86ISD::ADD  ||
12743            Cond.getOpcode() == X86ISD::SUB  ||
12744            Cond.getOpcode() == X86ISD::SMUL ||
12745            Cond.getOpcode() == X86ISD::UMUL)
12746     Cond = LowerXALUO(Cond, DAG);
12747 #endif
12748
12749   // Look pass (and (setcc_carry (cmp ...)), 1).
12750   if (Cond.getOpcode() == ISD::AND &&
12751       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12752     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12753     if (C && C->getAPIntValue() == 1)
12754       Cond = Cond.getOperand(0);
12755   }
12756
12757   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12758   // setting operand in place of the X86ISD::SETCC.
12759   unsigned CondOpcode = Cond.getOpcode();
12760   if (CondOpcode == X86ISD::SETCC ||
12761       CondOpcode == X86ISD::SETCC_CARRY) {
12762     CC = Cond.getOperand(0);
12763
12764     SDValue Cmp = Cond.getOperand(1);
12765     unsigned Opc = Cmp.getOpcode();
12766     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12767     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12768       Cond = Cmp;
12769       addTest = false;
12770     } else {
12771       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12772       default: break;
12773       case X86::COND_O:
12774       case X86::COND_B:
12775         // These can only come from an arithmetic instruction with overflow,
12776         // e.g. SADDO, UADDO.
12777         Cond = Cond.getNode()->getOperand(1);
12778         addTest = false;
12779         break;
12780       }
12781     }
12782   }
12783   CondOpcode = Cond.getOpcode();
12784   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12785       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12786       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12787        Cond.getOperand(0).getValueType() != MVT::i8)) {
12788     SDValue LHS = Cond.getOperand(0);
12789     SDValue RHS = Cond.getOperand(1);
12790     unsigned X86Opcode;
12791     unsigned X86Cond;
12792     SDVTList VTs;
12793     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12794     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12795     // X86ISD::INC).
12796     switch (CondOpcode) {
12797     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12798     case ISD::SADDO:
12799       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12800         if (C->isOne()) {
12801           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12802           break;
12803         }
12804       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12805     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12806     case ISD::SSUBO:
12807       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12808         if (C->isOne()) {
12809           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12810           break;
12811         }
12812       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12813     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12814     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12815     default: llvm_unreachable("unexpected overflowing operator");
12816     }
12817     if (Inverted)
12818       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12819     if (CondOpcode == ISD::UMULO)
12820       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12821                           MVT::i32);
12822     else
12823       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12824
12825     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12826
12827     if (CondOpcode == ISD::UMULO)
12828       Cond = X86Op.getValue(2);
12829     else
12830       Cond = X86Op.getValue(1);
12831
12832     CC = DAG.getConstant(X86Cond, MVT::i8);
12833     addTest = false;
12834   } else {
12835     unsigned CondOpc;
12836     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12837       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12838       if (CondOpc == ISD::OR) {
12839         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12840         // two branches instead of an explicit OR instruction with a
12841         // separate test.
12842         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12843             isX86LogicalCmp(Cmp)) {
12844           CC = Cond.getOperand(0).getOperand(0);
12845           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12846                               Chain, Dest, CC, Cmp);
12847           CC = Cond.getOperand(1).getOperand(0);
12848           Cond = Cmp;
12849           addTest = false;
12850         }
12851       } else { // ISD::AND
12852         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12853         // two branches instead of an explicit AND instruction with a
12854         // separate test. However, we only do this if this block doesn't
12855         // have a fall-through edge, because this requires an explicit
12856         // jmp when the condition is false.
12857         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12858             isX86LogicalCmp(Cmp) &&
12859             Op.getNode()->hasOneUse()) {
12860           X86::CondCode CCode =
12861             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12862           CCode = X86::GetOppositeBranchCondition(CCode);
12863           CC = DAG.getConstant(CCode, MVT::i8);
12864           SDNode *User = *Op.getNode()->use_begin();
12865           // Look for an unconditional branch following this conditional branch.
12866           // We need this because we need to reverse the successors in order
12867           // to implement FCMP_OEQ.
12868           if (User->getOpcode() == ISD::BR) {
12869             SDValue FalseBB = User->getOperand(1);
12870             SDNode *NewBR =
12871               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12872             assert(NewBR == User);
12873             (void)NewBR;
12874             Dest = FalseBB;
12875
12876             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12877                                 Chain, Dest, CC, Cmp);
12878             X86::CondCode CCode =
12879               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12880             CCode = X86::GetOppositeBranchCondition(CCode);
12881             CC = DAG.getConstant(CCode, MVT::i8);
12882             Cond = Cmp;
12883             addTest = false;
12884           }
12885         }
12886       }
12887     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12888       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12889       // It should be transformed during dag combiner except when the condition
12890       // is set by a arithmetics with overflow node.
12891       X86::CondCode CCode =
12892         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12893       CCode = X86::GetOppositeBranchCondition(CCode);
12894       CC = DAG.getConstant(CCode, MVT::i8);
12895       Cond = Cond.getOperand(0).getOperand(1);
12896       addTest = false;
12897     } else if (Cond.getOpcode() == ISD::SETCC &&
12898                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12899       // For FCMP_OEQ, we can emit
12900       // two branches instead of an explicit AND instruction with a
12901       // separate test. However, we only do this if this block doesn't
12902       // have a fall-through edge, because this requires an explicit
12903       // jmp when the condition is false.
12904       if (Op.getNode()->hasOneUse()) {
12905         SDNode *User = *Op.getNode()->use_begin();
12906         // Look for an unconditional branch following this conditional branch.
12907         // We need this because we need to reverse the successors in order
12908         // to implement FCMP_OEQ.
12909         if (User->getOpcode() == ISD::BR) {
12910           SDValue FalseBB = User->getOperand(1);
12911           SDNode *NewBR =
12912             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12913           assert(NewBR == User);
12914           (void)NewBR;
12915           Dest = FalseBB;
12916
12917           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12918                                     Cond.getOperand(0), Cond.getOperand(1));
12919           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12920           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12921           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12922                               Chain, Dest, CC, Cmp);
12923           CC = DAG.getConstant(X86::COND_P, MVT::i8);
12924           Cond = Cmp;
12925           addTest = false;
12926         }
12927       }
12928     } else if (Cond.getOpcode() == ISD::SETCC &&
12929                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
12930       // For FCMP_UNE, we can emit
12931       // two branches instead of an explicit AND instruction with a
12932       // separate test. However, we only do this if this block doesn't
12933       // have a fall-through edge, because this requires an explicit
12934       // jmp when the condition is false.
12935       if (Op.getNode()->hasOneUse()) {
12936         SDNode *User = *Op.getNode()->use_begin();
12937         // Look for an unconditional branch following this conditional branch.
12938         // We need this because we need to reverse the successors in order
12939         // to implement FCMP_UNE.
12940         if (User->getOpcode() == ISD::BR) {
12941           SDValue FalseBB = User->getOperand(1);
12942           SDNode *NewBR =
12943             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12944           assert(NewBR == User);
12945           (void)NewBR;
12946
12947           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12948                                     Cond.getOperand(0), Cond.getOperand(1));
12949           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12950           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12951           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12952                               Chain, Dest, CC, Cmp);
12953           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
12954           Cond = Cmp;
12955           addTest = false;
12956           Dest = FalseBB;
12957         }
12958       }
12959     }
12960   }
12961
12962   if (addTest) {
12963     // Look pass the truncate if the high bits are known zero.
12964     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12965         Cond = Cond.getOperand(0);
12966
12967     // We know the result of AND is compared against zero. Try to match
12968     // it to BT.
12969     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12970       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
12971       if (NewSetCC.getNode()) {
12972         CC = NewSetCC.getOperand(0);
12973         Cond = NewSetCC.getOperand(1);
12974         addTest = false;
12975       }
12976     }
12977   }
12978
12979   if (addTest) {
12980     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
12981     CC = DAG.getConstant(X86Cond, MVT::i8);
12982     Cond = EmitTest(Cond, X86Cond, dl, DAG);
12983   }
12984   Cond = ConvertCmpIfNecessary(Cond, DAG);
12985   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12986                      Chain, Dest, CC, Cond);
12987 }
12988
12989 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
12990 // Calls to _alloca is needed to probe the stack when allocating more than 4k
12991 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
12992 // that the guard pages used by the OS virtual memory manager are allocated in
12993 // correct sequence.
12994 SDValue
12995 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
12996                                            SelectionDAG &DAG) const {
12997   MachineFunction &MF = DAG.getMachineFunction();
12998   bool SplitStack = MF.shouldSplitStack();
12999   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13000                SplitStack;
13001   SDLoc dl(Op);
13002
13003   if (!Lower) {
13004     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13005     SDNode* Node = Op.getNode();
13006
13007     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13008     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13009         " not tell us which reg is the stack pointer!");
13010     EVT VT = Node->getValueType(0);
13011     SDValue Tmp1 = SDValue(Node, 0);
13012     SDValue Tmp2 = SDValue(Node, 1);
13013     SDValue Tmp3 = Node->getOperand(2);
13014     SDValue Chain = Tmp1.getOperand(0);
13015
13016     // Chain the dynamic stack allocation so that it doesn't modify the stack
13017     // pointer when other instructions are using the stack.
13018     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13019         SDLoc(Node));
13020
13021     SDValue Size = Tmp2.getOperand(1);
13022     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13023     Chain = SP.getValue(1);
13024     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13025     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13026     unsigned StackAlign = TFI.getStackAlignment();
13027     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13028     if (Align > StackAlign)
13029       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13030           DAG.getConstant(-(uint64_t)Align, VT));
13031     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13032
13033     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13034         DAG.getIntPtrConstant(0, true), SDValue(),
13035         SDLoc(Node));
13036
13037     SDValue Ops[2] = { Tmp1, Tmp2 };
13038     return DAG.getMergeValues(Ops, dl);
13039   }
13040
13041   // Get the inputs.
13042   SDValue Chain = Op.getOperand(0);
13043   SDValue Size  = Op.getOperand(1);
13044   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13045   EVT VT = Op.getNode()->getValueType(0);
13046
13047   bool Is64Bit = Subtarget->is64Bit();
13048   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13049
13050   if (SplitStack) {
13051     MachineRegisterInfo &MRI = MF.getRegInfo();
13052
13053     if (Is64Bit) {
13054       // The 64 bit implementation of segmented stacks needs to clobber both r10
13055       // r11. This makes it impossible to use it along with nested parameters.
13056       const Function *F = MF.getFunction();
13057
13058       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13059            I != E; ++I)
13060         if (I->hasNestAttr())
13061           report_fatal_error("Cannot use segmented stacks with functions that "
13062                              "have nested arguments.");
13063     }
13064
13065     const TargetRegisterClass *AddrRegClass =
13066       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13067     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13068     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13069     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13070                                 DAG.getRegister(Vreg, SPTy));
13071     SDValue Ops1[2] = { Value, Chain };
13072     return DAG.getMergeValues(Ops1, dl);
13073   } else {
13074     SDValue Flag;
13075     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13076
13077     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13078     Flag = Chain.getValue(1);
13079     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13080
13081     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13082
13083     const X86RegisterInfo *RegInfo =
13084       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13085     unsigned SPReg = RegInfo->getStackRegister();
13086     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13087     Chain = SP.getValue(1);
13088
13089     if (Align) {
13090       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13091                        DAG.getConstant(-(uint64_t)Align, VT));
13092       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13093     }
13094
13095     SDValue Ops1[2] = { SP, Chain };
13096     return DAG.getMergeValues(Ops1, dl);
13097   }
13098 }
13099
13100 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13101   MachineFunction &MF = DAG.getMachineFunction();
13102   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13103
13104   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13105   SDLoc DL(Op);
13106
13107   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13108     // vastart just stores the address of the VarArgsFrameIndex slot into the
13109     // memory location argument.
13110     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13111                                    getPointerTy());
13112     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13113                         MachinePointerInfo(SV), false, false, 0);
13114   }
13115
13116   // __va_list_tag:
13117   //   gp_offset         (0 - 6 * 8)
13118   //   fp_offset         (48 - 48 + 8 * 16)
13119   //   overflow_arg_area (point to parameters coming in memory).
13120   //   reg_save_area
13121   SmallVector<SDValue, 8> MemOps;
13122   SDValue FIN = Op.getOperand(1);
13123   // Store gp_offset
13124   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13125                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13126                                                MVT::i32),
13127                                FIN, MachinePointerInfo(SV), false, false, 0);
13128   MemOps.push_back(Store);
13129
13130   // Store fp_offset
13131   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13132                     FIN, DAG.getIntPtrConstant(4));
13133   Store = DAG.getStore(Op.getOperand(0), DL,
13134                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13135                                        MVT::i32),
13136                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13137   MemOps.push_back(Store);
13138
13139   // Store ptr to overflow_arg_area
13140   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13141                     FIN, DAG.getIntPtrConstant(4));
13142   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13143                                     getPointerTy());
13144   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13145                        MachinePointerInfo(SV, 8),
13146                        false, false, 0);
13147   MemOps.push_back(Store);
13148
13149   // Store ptr to reg_save_area.
13150   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13151                     FIN, DAG.getIntPtrConstant(8));
13152   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13153                                     getPointerTy());
13154   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13155                        MachinePointerInfo(SV, 16), false, false, 0);
13156   MemOps.push_back(Store);
13157   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13158 }
13159
13160 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13161   assert(Subtarget->is64Bit() &&
13162          "LowerVAARG only handles 64-bit va_arg!");
13163   assert((Subtarget->isTargetLinux() ||
13164           Subtarget->isTargetDarwin()) &&
13165           "Unhandled target in LowerVAARG");
13166   assert(Op.getNode()->getNumOperands() == 4);
13167   SDValue Chain = Op.getOperand(0);
13168   SDValue SrcPtr = Op.getOperand(1);
13169   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13170   unsigned Align = Op.getConstantOperandVal(3);
13171   SDLoc dl(Op);
13172
13173   EVT ArgVT = Op.getNode()->getValueType(0);
13174   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13175   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13176   uint8_t ArgMode;
13177
13178   // Decide which area this value should be read from.
13179   // TODO: Implement the AMD64 ABI in its entirety. This simple
13180   // selection mechanism works only for the basic types.
13181   if (ArgVT == MVT::f80) {
13182     llvm_unreachable("va_arg for f80 not yet implemented");
13183   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13184     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13185   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13186     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13187   } else {
13188     llvm_unreachable("Unhandled argument type in LowerVAARG");
13189   }
13190
13191   if (ArgMode == 2) {
13192     // Sanity Check: Make sure using fp_offset makes sense.
13193     assert(!DAG.getTarget().Options.UseSoftFloat &&
13194            !(DAG.getMachineFunction()
13195                 .getFunction()->getAttributes()
13196                 .hasAttribute(AttributeSet::FunctionIndex,
13197                               Attribute::NoImplicitFloat)) &&
13198            Subtarget->hasSSE1());
13199   }
13200
13201   // Insert VAARG_64 node into the DAG
13202   // VAARG_64 returns two values: Variable Argument Address, Chain
13203   SmallVector<SDValue, 11> InstOps;
13204   InstOps.push_back(Chain);
13205   InstOps.push_back(SrcPtr);
13206   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13207   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13208   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13209   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13210   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13211                                           VTs, InstOps, MVT::i64,
13212                                           MachinePointerInfo(SV),
13213                                           /*Align=*/0,
13214                                           /*Volatile=*/false,
13215                                           /*ReadMem=*/true,
13216                                           /*WriteMem=*/true);
13217   Chain = VAARG.getValue(1);
13218
13219   // Load the next argument and return it
13220   return DAG.getLoad(ArgVT, dl,
13221                      Chain,
13222                      VAARG,
13223                      MachinePointerInfo(),
13224                      false, false, false, 0);
13225 }
13226
13227 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13228                            SelectionDAG &DAG) {
13229   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13230   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13231   SDValue Chain = Op.getOperand(0);
13232   SDValue DstPtr = Op.getOperand(1);
13233   SDValue SrcPtr = Op.getOperand(2);
13234   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13235   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13236   SDLoc DL(Op);
13237
13238   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13239                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13240                        false,
13241                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13242 }
13243
13244 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13245 // amount is a constant. Takes immediate version of shift as input.
13246 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13247                                           SDValue SrcOp, uint64_t ShiftAmt,
13248                                           SelectionDAG &DAG) {
13249   MVT ElementType = VT.getVectorElementType();
13250
13251   // Fold this packed shift into its first operand if ShiftAmt is 0.
13252   if (ShiftAmt == 0)
13253     return SrcOp;
13254
13255   // Check for ShiftAmt >= element width
13256   if (ShiftAmt >= ElementType.getSizeInBits()) {
13257     if (Opc == X86ISD::VSRAI)
13258       ShiftAmt = ElementType.getSizeInBits() - 1;
13259     else
13260       return DAG.getConstant(0, VT);
13261   }
13262
13263   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13264          && "Unknown target vector shift-by-constant node");
13265
13266   // Fold this packed vector shift into a build vector if SrcOp is a
13267   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13268   if (VT == SrcOp.getSimpleValueType() &&
13269       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13270     SmallVector<SDValue, 8> Elts;
13271     unsigned NumElts = SrcOp->getNumOperands();
13272     ConstantSDNode *ND;
13273
13274     switch(Opc) {
13275     default: llvm_unreachable(nullptr);
13276     case X86ISD::VSHLI:
13277       for (unsigned i=0; i!=NumElts; ++i) {
13278         SDValue CurrentOp = SrcOp->getOperand(i);
13279         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13280           Elts.push_back(CurrentOp);
13281           continue;
13282         }
13283         ND = cast<ConstantSDNode>(CurrentOp);
13284         const APInt &C = ND->getAPIntValue();
13285         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13286       }
13287       break;
13288     case X86ISD::VSRLI:
13289       for (unsigned i=0; i!=NumElts; ++i) {
13290         SDValue CurrentOp = SrcOp->getOperand(i);
13291         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13292           Elts.push_back(CurrentOp);
13293           continue;
13294         }
13295         ND = cast<ConstantSDNode>(CurrentOp);
13296         const APInt &C = ND->getAPIntValue();
13297         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13298       }
13299       break;
13300     case X86ISD::VSRAI:
13301       for (unsigned i=0; i!=NumElts; ++i) {
13302         SDValue CurrentOp = SrcOp->getOperand(i);
13303         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13304           Elts.push_back(CurrentOp);
13305           continue;
13306         }
13307         ND = cast<ConstantSDNode>(CurrentOp);
13308         const APInt &C = ND->getAPIntValue();
13309         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13310       }
13311       break;
13312     }
13313
13314     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13315   }
13316
13317   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13318 }
13319
13320 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13321 // may or may not be a constant. Takes immediate version of shift as input.
13322 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13323                                    SDValue SrcOp, SDValue ShAmt,
13324                                    SelectionDAG &DAG) {
13325   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13326
13327   // Catch shift-by-constant.
13328   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13329     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13330                                       CShAmt->getZExtValue(), DAG);
13331
13332   // Change opcode to non-immediate version
13333   switch (Opc) {
13334     default: llvm_unreachable("Unknown target vector shift node");
13335     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13336     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13337     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13338   }
13339
13340   // Need to build a vector containing shift amount
13341   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13342   SDValue ShOps[4];
13343   ShOps[0] = ShAmt;
13344   ShOps[1] = DAG.getConstant(0, MVT::i32);
13345   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13346   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13347
13348   // The return type has to be a 128-bit type with the same element
13349   // type as the input type.
13350   MVT EltVT = VT.getVectorElementType();
13351   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13352
13353   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13354   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13355 }
13356
13357 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13358   SDLoc dl(Op);
13359   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13360   switch (IntNo) {
13361   default: return SDValue();    // Don't custom lower most intrinsics.
13362   // Comparison intrinsics.
13363   case Intrinsic::x86_sse_comieq_ss:
13364   case Intrinsic::x86_sse_comilt_ss:
13365   case Intrinsic::x86_sse_comile_ss:
13366   case Intrinsic::x86_sse_comigt_ss:
13367   case Intrinsic::x86_sse_comige_ss:
13368   case Intrinsic::x86_sse_comineq_ss:
13369   case Intrinsic::x86_sse_ucomieq_ss:
13370   case Intrinsic::x86_sse_ucomilt_ss:
13371   case Intrinsic::x86_sse_ucomile_ss:
13372   case Intrinsic::x86_sse_ucomigt_ss:
13373   case Intrinsic::x86_sse_ucomige_ss:
13374   case Intrinsic::x86_sse_ucomineq_ss:
13375   case Intrinsic::x86_sse2_comieq_sd:
13376   case Intrinsic::x86_sse2_comilt_sd:
13377   case Intrinsic::x86_sse2_comile_sd:
13378   case Intrinsic::x86_sse2_comigt_sd:
13379   case Intrinsic::x86_sse2_comige_sd:
13380   case Intrinsic::x86_sse2_comineq_sd:
13381   case Intrinsic::x86_sse2_ucomieq_sd:
13382   case Intrinsic::x86_sse2_ucomilt_sd:
13383   case Intrinsic::x86_sse2_ucomile_sd:
13384   case Intrinsic::x86_sse2_ucomigt_sd:
13385   case Intrinsic::x86_sse2_ucomige_sd:
13386   case Intrinsic::x86_sse2_ucomineq_sd: {
13387     unsigned Opc;
13388     ISD::CondCode CC;
13389     switch (IntNo) {
13390     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13391     case Intrinsic::x86_sse_comieq_ss:
13392     case Intrinsic::x86_sse2_comieq_sd:
13393       Opc = X86ISD::COMI;
13394       CC = ISD::SETEQ;
13395       break;
13396     case Intrinsic::x86_sse_comilt_ss:
13397     case Intrinsic::x86_sse2_comilt_sd:
13398       Opc = X86ISD::COMI;
13399       CC = ISD::SETLT;
13400       break;
13401     case Intrinsic::x86_sse_comile_ss:
13402     case Intrinsic::x86_sse2_comile_sd:
13403       Opc = X86ISD::COMI;
13404       CC = ISD::SETLE;
13405       break;
13406     case Intrinsic::x86_sse_comigt_ss:
13407     case Intrinsic::x86_sse2_comigt_sd:
13408       Opc = X86ISD::COMI;
13409       CC = ISD::SETGT;
13410       break;
13411     case Intrinsic::x86_sse_comige_ss:
13412     case Intrinsic::x86_sse2_comige_sd:
13413       Opc = X86ISD::COMI;
13414       CC = ISD::SETGE;
13415       break;
13416     case Intrinsic::x86_sse_comineq_ss:
13417     case Intrinsic::x86_sse2_comineq_sd:
13418       Opc = X86ISD::COMI;
13419       CC = ISD::SETNE;
13420       break;
13421     case Intrinsic::x86_sse_ucomieq_ss:
13422     case Intrinsic::x86_sse2_ucomieq_sd:
13423       Opc = X86ISD::UCOMI;
13424       CC = ISD::SETEQ;
13425       break;
13426     case Intrinsic::x86_sse_ucomilt_ss:
13427     case Intrinsic::x86_sse2_ucomilt_sd:
13428       Opc = X86ISD::UCOMI;
13429       CC = ISD::SETLT;
13430       break;
13431     case Intrinsic::x86_sse_ucomile_ss:
13432     case Intrinsic::x86_sse2_ucomile_sd:
13433       Opc = X86ISD::UCOMI;
13434       CC = ISD::SETLE;
13435       break;
13436     case Intrinsic::x86_sse_ucomigt_ss:
13437     case Intrinsic::x86_sse2_ucomigt_sd:
13438       Opc = X86ISD::UCOMI;
13439       CC = ISD::SETGT;
13440       break;
13441     case Intrinsic::x86_sse_ucomige_ss:
13442     case Intrinsic::x86_sse2_ucomige_sd:
13443       Opc = X86ISD::UCOMI;
13444       CC = ISD::SETGE;
13445       break;
13446     case Intrinsic::x86_sse_ucomineq_ss:
13447     case Intrinsic::x86_sse2_ucomineq_sd:
13448       Opc = X86ISD::UCOMI;
13449       CC = ISD::SETNE;
13450       break;
13451     }
13452
13453     SDValue LHS = Op.getOperand(1);
13454     SDValue RHS = Op.getOperand(2);
13455     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13456     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13457     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13458     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13459                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13460     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13461   }
13462
13463   // Arithmetic intrinsics.
13464   case Intrinsic::x86_sse2_pmulu_dq:
13465   case Intrinsic::x86_avx2_pmulu_dq:
13466     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13467                        Op.getOperand(1), Op.getOperand(2));
13468
13469   case Intrinsic::x86_sse41_pmuldq:
13470   case Intrinsic::x86_avx2_pmul_dq:
13471     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13472                        Op.getOperand(1), Op.getOperand(2));
13473
13474   case Intrinsic::x86_sse2_pmulhu_w:
13475   case Intrinsic::x86_avx2_pmulhu_w:
13476     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13477                        Op.getOperand(1), Op.getOperand(2));
13478
13479   case Intrinsic::x86_sse2_pmulh_w:
13480   case Intrinsic::x86_avx2_pmulh_w:
13481     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13482                        Op.getOperand(1), Op.getOperand(2));
13483
13484   // SSE2/AVX2 sub with unsigned saturation intrinsics
13485   case Intrinsic::x86_sse2_psubus_b:
13486   case Intrinsic::x86_sse2_psubus_w:
13487   case Intrinsic::x86_avx2_psubus_b:
13488   case Intrinsic::x86_avx2_psubus_w:
13489     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13490                        Op.getOperand(1), Op.getOperand(2));
13491
13492   // SSE3/AVX horizontal add/sub intrinsics
13493   case Intrinsic::x86_sse3_hadd_ps:
13494   case Intrinsic::x86_sse3_hadd_pd:
13495   case Intrinsic::x86_avx_hadd_ps_256:
13496   case Intrinsic::x86_avx_hadd_pd_256:
13497   case Intrinsic::x86_sse3_hsub_ps:
13498   case Intrinsic::x86_sse3_hsub_pd:
13499   case Intrinsic::x86_avx_hsub_ps_256:
13500   case Intrinsic::x86_avx_hsub_pd_256:
13501   case Intrinsic::x86_ssse3_phadd_w_128:
13502   case Intrinsic::x86_ssse3_phadd_d_128:
13503   case Intrinsic::x86_avx2_phadd_w:
13504   case Intrinsic::x86_avx2_phadd_d:
13505   case Intrinsic::x86_ssse3_phsub_w_128:
13506   case Intrinsic::x86_ssse3_phsub_d_128:
13507   case Intrinsic::x86_avx2_phsub_w:
13508   case Intrinsic::x86_avx2_phsub_d: {
13509     unsigned Opcode;
13510     switch (IntNo) {
13511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13512     case Intrinsic::x86_sse3_hadd_ps:
13513     case Intrinsic::x86_sse3_hadd_pd:
13514     case Intrinsic::x86_avx_hadd_ps_256:
13515     case Intrinsic::x86_avx_hadd_pd_256:
13516       Opcode = X86ISD::FHADD;
13517       break;
13518     case Intrinsic::x86_sse3_hsub_ps:
13519     case Intrinsic::x86_sse3_hsub_pd:
13520     case Intrinsic::x86_avx_hsub_ps_256:
13521     case Intrinsic::x86_avx_hsub_pd_256:
13522       Opcode = X86ISD::FHSUB;
13523       break;
13524     case Intrinsic::x86_ssse3_phadd_w_128:
13525     case Intrinsic::x86_ssse3_phadd_d_128:
13526     case Intrinsic::x86_avx2_phadd_w:
13527     case Intrinsic::x86_avx2_phadd_d:
13528       Opcode = X86ISD::HADD;
13529       break;
13530     case Intrinsic::x86_ssse3_phsub_w_128:
13531     case Intrinsic::x86_ssse3_phsub_d_128:
13532     case Intrinsic::x86_avx2_phsub_w:
13533     case Intrinsic::x86_avx2_phsub_d:
13534       Opcode = X86ISD::HSUB;
13535       break;
13536     }
13537     return DAG.getNode(Opcode, dl, Op.getValueType(),
13538                        Op.getOperand(1), Op.getOperand(2));
13539   }
13540
13541   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13542   case Intrinsic::x86_sse2_pmaxu_b:
13543   case Intrinsic::x86_sse41_pmaxuw:
13544   case Intrinsic::x86_sse41_pmaxud:
13545   case Intrinsic::x86_avx2_pmaxu_b:
13546   case Intrinsic::x86_avx2_pmaxu_w:
13547   case Intrinsic::x86_avx2_pmaxu_d:
13548   case Intrinsic::x86_sse2_pminu_b:
13549   case Intrinsic::x86_sse41_pminuw:
13550   case Intrinsic::x86_sse41_pminud:
13551   case Intrinsic::x86_avx2_pminu_b:
13552   case Intrinsic::x86_avx2_pminu_w:
13553   case Intrinsic::x86_avx2_pminu_d:
13554   case Intrinsic::x86_sse41_pmaxsb:
13555   case Intrinsic::x86_sse2_pmaxs_w:
13556   case Intrinsic::x86_sse41_pmaxsd:
13557   case Intrinsic::x86_avx2_pmaxs_b:
13558   case Intrinsic::x86_avx2_pmaxs_w:
13559   case Intrinsic::x86_avx2_pmaxs_d:
13560   case Intrinsic::x86_sse41_pminsb:
13561   case Intrinsic::x86_sse2_pmins_w:
13562   case Intrinsic::x86_sse41_pminsd:
13563   case Intrinsic::x86_avx2_pmins_b:
13564   case Intrinsic::x86_avx2_pmins_w:
13565   case Intrinsic::x86_avx2_pmins_d: {
13566     unsigned Opcode;
13567     switch (IntNo) {
13568     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13569     case Intrinsic::x86_sse2_pmaxu_b:
13570     case Intrinsic::x86_sse41_pmaxuw:
13571     case Intrinsic::x86_sse41_pmaxud:
13572     case Intrinsic::x86_avx2_pmaxu_b:
13573     case Intrinsic::x86_avx2_pmaxu_w:
13574     case Intrinsic::x86_avx2_pmaxu_d:
13575       Opcode = X86ISD::UMAX;
13576       break;
13577     case Intrinsic::x86_sse2_pminu_b:
13578     case Intrinsic::x86_sse41_pminuw:
13579     case Intrinsic::x86_sse41_pminud:
13580     case Intrinsic::x86_avx2_pminu_b:
13581     case Intrinsic::x86_avx2_pminu_w:
13582     case Intrinsic::x86_avx2_pminu_d:
13583       Opcode = X86ISD::UMIN;
13584       break;
13585     case Intrinsic::x86_sse41_pmaxsb:
13586     case Intrinsic::x86_sse2_pmaxs_w:
13587     case Intrinsic::x86_sse41_pmaxsd:
13588     case Intrinsic::x86_avx2_pmaxs_b:
13589     case Intrinsic::x86_avx2_pmaxs_w:
13590     case Intrinsic::x86_avx2_pmaxs_d:
13591       Opcode = X86ISD::SMAX;
13592       break;
13593     case Intrinsic::x86_sse41_pminsb:
13594     case Intrinsic::x86_sse2_pmins_w:
13595     case Intrinsic::x86_sse41_pminsd:
13596     case Intrinsic::x86_avx2_pmins_b:
13597     case Intrinsic::x86_avx2_pmins_w:
13598     case Intrinsic::x86_avx2_pmins_d:
13599       Opcode = X86ISD::SMIN;
13600       break;
13601     }
13602     return DAG.getNode(Opcode, dl, Op.getValueType(),
13603                        Op.getOperand(1), Op.getOperand(2));
13604   }
13605
13606   // SSE/SSE2/AVX floating point max/min intrinsics.
13607   case Intrinsic::x86_sse_max_ps:
13608   case Intrinsic::x86_sse2_max_pd:
13609   case Intrinsic::x86_avx_max_ps_256:
13610   case Intrinsic::x86_avx_max_pd_256:
13611   case Intrinsic::x86_sse_min_ps:
13612   case Intrinsic::x86_sse2_min_pd:
13613   case Intrinsic::x86_avx_min_ps_256:
13614   case Intrinsic::x86_avx_min_pd_256: {
13615     unsigned Opcode;
13616     switch (IntNo) {
13617     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13618     case Intrinsic::x86_sse_max_ps:
13619     case Intrinsic::x86_sse2_max_pd:
13620     case Intrinsic::x86_avx_max_ps_256:
13621     case Intrinsic::x86_avx_max_pd_256:
13622       Opcode = X86ISD::FMAX;
13623       break;
13624     case Intrinsic::x86_sse_min_ps:
13625     case Intrinsic::x86_sse2_min_pd:
13626     case Intrinsic::x86_avx_min_ps_256:
13627     case Intrinsic::x86_avx_min_pd_256:
13628       Opcode = X86ISD::FMIN;
13629       break;
13630     }
13631     return DAG.getNode(Opcode, dl, Op.getValueType(),
13632                        Op.getOperand(1), Op.getOperand(2));
13633   }
13634
13635   // AVX2 variable shift intrinsics
13636   case Intrinsic::x86_avx2_psllv_d:
13637   case Intrinsic::x86_avx2_psllv_q:
13638   case Intrinsic::x86_avx2_psllv_d_256:
13639   case Intrinsic::x86_avx2_psllv_q_256:
13640   case Intrinsic::x86_avx2_psrlv_d:
13641   case Intrinsic::x86_avx2_psrlv_q:
13642   case Intrinsic::x86_avx2_psrlv_d_256:
13643   case Intrinsic::x86_avx2_psrlv_q_256:
13644   case Intrinsic::x86_avx2_psrav_d:
13645   case Intrinsic::x86_avx2_psrav_d_256: {
13646     unsigned Opcode;
13647     switch (IntNo) {
13648     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13649     case Intrinsic::x86_avx2_psllv_d:
13650     case Intrinsic::x86_avx2_psllv_q:
13651     case Intrinsic::x86_avx2_psllv_d_256:
13652     case Intrinsic::x86_avx2_psllv_q_256:
13653       Opcode = ISD::SHL;
13654       break;
13655     case Intrinsic::x86_avx2_psrlv_d:
13656     case Intrinsic::x86_avx2_psrlv_q:
13657     case Intrinsic::x86_avx2_psrlv_d_256:
13658     case Intrinsic::x86_avx2_psrlv_q_256:
13659       Opcode = ISD::SRL;
13660       break;
13661     case Intrinsic::x86_avx2_psrav_d:
13662     case Intrinsic::x86_avx2_psrav_d_256:
13663       Opcode = ISD::SRA;
13664       break;
13665     }
13666     return DAG.getNode(Opcode, dl, Op.getValueType(),
13667                        Op.getOperand(1), Op.getOperand(2));
13668   }
13669
13670   case Intrinsic::x86_sse2_packssdw_128:
13671   case Intrinsic::x86_sse2_packsswb_128:
13672   case Intrinsic::x86_avx2_packssdw:
13673   case Intrinsic::x86_avx2_packsswb:
13674     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13675                        Op.getOperand(1), Op.getOperand(2));
13676
13677   case Intrinsic::x86_sse2_packuswb_128:
13678   case Intrinsic::x86_sse41_packusdw:
13679   case Intrinsic::x86_avx2_packuswb:
13680   case Intrinsic::x86_avx2_packusdw:
13681     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13682                        Op.getOperand(1), Op.getOperand(2));
13683
13684   case Intrinsic::x86_ssse3_pshuf_b_128:
13685   case Intrinsic::x86_avx2_pshuf_b:
13686     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13687                        Op.getOperand(1), Op.getOperand(2));
13688
13689   case Intrinsic::x86_sse2_pshuf_d:
13690     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13691                        Op.getOperand(1), Op.getOperand(2));
13692
13693   case Intrinsic::x86_sse2_pshufl_w:
13694     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13695                        Op.getOperand(1), Op.getOperand(2));
13696
13697   case Intrinsic::x86_sse2_pshufh_w:
13698     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13699                        Op.getOperand(1), Op.getOperand(2));
13700
13701   case Intrinsic::x86_ssse3_psign_b_128:
13702   case Intrinsic::x86_ssse3_psign_w_128:
13703   case Intrinsic::x86_ssse3_psign_d_128:
13704   case Intrinsic::x86_avx2_psign_b:
13705   case Intrinsic::x86_avx2_psign_w:
13706   case Intrinsic::x86_avx2_psign_d:
13707     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13708                        Op.getOperand(1), Op.getOperand(2));
13709
13710   case Intrinsic::x86_sse41_insertps:
13711     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13712                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13713
13714   case Intrinsic::x86_avx_vperm2f128_ps_256:
13715   case Intrinsic::x86_avx_vperm2f128_pd_256:
13716   case Intrinsic::x86_avx_vperm2f128_si_256:
13717   case Intrinsic::x86_avx2_vperm2i128:
13718     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13719                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13720
13721   case Intrinsic::x86_avx2_permd:
13722   case Intrinsic::x86_avx2_permps:
13723     // Operands intentionally swapped. Mask is last operand to intrinsic,
13724     // but second operand for node/instruction.
13725     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13726                        Op.getOperand(2), Op.getOperand(1));
13727
13728   case Intrinsic::x86_sse_sqrt_ps:
13729   case Intrinsic::x86_sse2_sqrt_pd:
13730   case Intrinsic::x86_avx_sqrt_ps_256:
13731   case Intrinsic::x86_avx_sqrt_pd_256:
13732     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13733
13734   // ptest and testp intrinsics. The intrinsic these come from are designed to
13735   // return an integer value, not just an instruction so lower it to the ptest
13736   // or testp pattern and a setcc for the result.
13737   case Intrinsic::x86_sse41_ptestz:
13738   case Intrinsic::x86_sse41_ptestc:
13739   case Intrinsic::x86_sse41_ptestnzc:
13740   case Intrinsic::x86_avx_ptestz_256:
13741   case Intrinsic::x86_avx_ptestc_256:
13742   case Intrinsic::x86_avx_ptestnzc_256:
13743   case Intrinsic::x86_avx_vtestz_ps:
13744   case Intrinsic::x86_avx_vtestc_ps:
13745   case Intrinsic::x86_avx_vtestnzc_ps:
13746   case Intrinsic::x86_avx_vtestz_pd:
13747   case Intrinsic::x86_avx_vtestc_pd:
13748   case Intrinsic::x86_avx_vtestnzc_pd:
13749   case Intrinsic::x86_avx_vtestz_ps_256:
13750   case Intrinsic::x86_avx_vtestc_ps_256:
13751   case Intrinsic::x86_avx_vtestnzc_ps_256:
13752   case Intrinsic::x86_avx_vtestz_pd_256:
13753   case Intrinsic::x86_avx_vtestc_pd_256:
13754   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13755     bool IsTestPacked = false;
13756     unsigned X86CC;
13757     switch (IntNo) {
13758     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13759     case Intrinsic::x86_avx_vtestz_ps:
13760     case Intrinsic::x86_avx_vtestz_pd:
13761     case Intrinsic::x86_avx_vtestz_ps_256:
13762     case Intrinsic::x86_avx_vtestz_pd_256:
13763       IsTestPacked = true; // Fallthrough
13764     case Intrinsic::x86_sse41_ptestz:
13765     case Intrinsic::x86_avx_ptestz_256:
13766       // ZF = 1
13767       X86CC = X86::COND_E;
13768       break;
13769     case Intrinsic::x86_avx_vtestc_ps:
13770     case Intrinsic::x86_avx_vtestc_pd:
13771     case Intrinsic::x86_avx_vtestc_ps_256:
13772     case Intrinsic::x86_avx_vtestc_pd_256:
13773       IsTestPacked = true; // Fallthrough
13774     case Intrinsic::x86_sse41_ptestc:
13775     case Intrinsic::x86_avx_ptestc_256:
13776       // CF = 1
13777       X86CC = X86::COND_B;
13778       break;
13779     case Intrinsic::x86_avx_vtestnzc_ps:
13780     case Intrinsic::x86_avx_vtestnzc_pd:
13781     case Intrinsic::x86_avx_vtestnzc_ps_256:
13782     case Intrinsic::x86_avx_vtestnzc_pd_256:
13783       IsTestPacked = true; // Fallthrough
13784     case Intrinsic::x86_sse41_ptestnzc:
13785     case Intrinsic::x86_avx_ptestnzc_256:
13786       // ZF and CF = 0
13787       X86CC = X86::COND_A;
13788       break;
13789     }
13790
13791     SDValue LHS = Op.getOperand(1);
13792     SDValue RHS = Op.getOperand(2);
13793     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13794     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13795     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13796     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13797     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13798   }
13799   case Intrinsic::x86_avx512_kortestz_w:
13800   case Intrinsic::x86_avx512_kortestc_w: {
13801     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13802     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13803     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13804     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13805     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13806     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13807     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13808   }
13809
13810   // SSE/AVX shift intrinsics
13811   case Intrinsic::x86_sse2_psll_w:
13812   case Intrinsic::x86_sse2_psll_d:
13813   case Intrinsic::x86_sse2_psll_q:
13814   case Intrinsic::x86_avx2_psll_w:
13815   case Intrinsic::x86_avx2_psll_d:
13816   case Intrinsic::x86_avx2_psll_q:
13817   case Intrinsic::x86_sse2_psrl_w:
13818   case Intrinsic::x86_sse2_psrl_d:
13819   case Intrinsic::x86_sse2_psrl_q:
13820   case Intrinsic::x86_avx2_psrl_w:
13821   case Intrinsic::x86_avx2_psrl_d:
13822   case Intrinsic::x86_avx2_psrl_q:
13823   case Intrinsic::x86_sse2_psra_w:
13824   case Intrinsic::x86_sse2_psra_d:
13825   case Intrinsic::x86_avx2_psra_w:
13826   case Intrinsic::x86_avx2_psra_d: {
13827     unsigned Opcode;
13828     switch (IntNo) {
13829     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13830     case Intrinsic::x86_sse2_psll_w:
13831     case Intrinsic::x86_sse2_psll_d:
13832     case Intrinsic::x86_sse2_psll_q:
13833     case Intrinsic::x86_avx2_psll_w:
13834     case Intrinsic::x86_avx2_psll_d:
13835     case Intrinsic::x86_avx2_psll_q:
13836       Opcode = X86ISD::VSHL;
13837       break;
13838     case Intrinsic::x86_sse2_psrl_w:
13839     case Intrinsic::x86_sse2_psrl_d:
13840     case Intrinsic::x86_sse2_psrl_q:
13841     case Intrinsic::x86_avx2_psrl_w:
13842     case Intrinsic::x86_avx2_psrl_d:
13843     case Intrinsic::x86_avx2_psrl_q:
13844       Opcode = X86ISD::VSRL;
13845       break;
13846     case Intrinsic::x86_sse2_psra_w:
13847     case Intrinsic::x86_sse2_psra_d:
13848     case Intrinsic::x86_avx2_psra_w:
13849     case Intrinsic::x86_avx2_psra_d:
13850       Opcode = X86ISD::VSRA;
13851       break;
13852     }
13853     return DAG.getNode(Opcode, dl, Op.getValueType(),
13854                        Op.getOperand(1), Op.getOperand(2));
13855   }
13856
13857   // SSE/AVX immediate shift intrinsics
13858   case Intrinsic::x86_sse2_pslli_w:
13859   case Intrinsic::x86_sse2_pslli_d:
13860   case Intrinsic::x86_sse2_pslli_q:
13861   case Intrinsic::x86_avx2_pslli_w:
13862   case Intrinsic::x86_avx2_pslli_d:
13863   case Intrinsic::x86_avx2_pslli_q:
13864   case Intrinsic::x86_sse2_psrli_w:
13865   case Intrinsic::x86_sse2_psrli_d:
13866   case Intrinsic::x86_sse2_psrli_q:
13867   case Intrinsic::x86_avx2_psrli_w:
13868   case Intrinsic::x86_avx2_psrli_d:
13869   case Intrinsic::x86_avx2_psrli_q:
13870   case Intrinsic::x86_sse2_psrai_w:
13871   case Intrinsic::x86_sse2_psrai_d:
13872   case Intrinsic::x86_avx2_psrai_w:
13873   case Intrinsic::x86_avx2_psrai_d: {
13874     unsigned Opcode;
13875     switch (IntNo) {
13876     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13877     case Intrinsic::x86_sse2_pslli_w:
13878     case Intrinsic::x86_sse2_pslli_d:
13879     case Intrinsic::x86_sse2_pslli_q:
13880     case Intrinsic::x86_avx2_pslli_w:
13881     case Intrinsic::x86_avx2_pslli_d:
13882     case Intrinsic::x86_avx2_pslli_q:
13883       Opcode = X86ISD::VSHLI;
13884       break;
13885     case Intrinsic::x86_sse2_psrli_w:
13886     case Intrinsic::x86_sse2_psrli_d:
13887     case Intrinsic::x86_sse2_psrli_q:
13888     case Intrinsic::x86_avx2_psrli_w:
13889     case Intrinsic::x86_avx2_psrli_d:
13890     case Intrinsic::x86_avx2_psrli_q:
13891       Opcode = X86ISD::VSRLI;
13892       break;
13893     case Intrinsic::x86_sse2_psrai_w:
13894     case Intrinsic::x86_sse2_psrai_d:
13895     case Intrinsic::x86_avx2_psrai_w:
13896     case Intrinsic::x86_avx2_psrai_d:
13897       Opcode = X86ISD::VSRAI;
13898       break;
13899     }
13900     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13901                                Op.getOperand(1), Op.getOperand(2), DAG);
13902   }
13903
13904   case Intrinsic::x86_sse42_pcmpistria128:
13905   case Intrinsic::x86_sse42_pcmpestria128:
13906   case Intrinsic::x86_sse42_pcmpistric128:
13907   case Intrinsic::x86_sse42_pcmpestric128:
13908   case Intrinsic::x86_sse42_pcmpistrio128:
13909   case Intrinsic::x86_sse42_pcmpestrio128:
13910   case Intrinsic::x86_sse42_pcmpistris128:
13911   case Intrinsic::x86_sse42_pcmpestris128:
13912   case Intrinsic::x86_sse42_pcmpistriz128:
13913   case Intrinsic::x86_sse42_pcmpestriz128: {
13914     unsigned Opcode;
13915     unsigned X86CC;
13916     switch (IntNo) {
13917     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13918     case Intrinsic::x86_sse42_pcmpistria128:
13919       Opcode = X86ISD::PCMPISTRI;
13920       X86CC = X86::COND_A;
13921       break;
13922     case Intrinsic::x86_sse42_pcmpestria128:
13923       Opcode = X86ISD::PCMPESTRI;
13924       X86CC = X86::COND_A;
13925       break;
13926     case Intrinsic::x86_sse42_pcmpistric128:
13927       Opcode = X86ISD::PCMPISTRI;
13928       X86CC = X86::COND_B;
13929       break;
13930     case Intrinsic::x86_sse42_pcmpestric128:
13931       Opcode = X86ISD::PCMPESTRI;
13932       X86CC = X86::COND_B;
13933       break;
13934     case Intrinsic::x86_sse42_pcmpistrio128:
13935       Opcode = X86ISD::PCMPISTRI;
13936       X86CC = X86::COND_O;
13937       break;
13938     case Intrinsic::x86_sse42_pcmpestrio128:
13939       Opcode = X86ISD::PCMPESTRI;
13940       X86CC = X86::COND_O;
13941       break;
13942     case Intrinsic::x86_sse42_pcmpistris128:
13943       Opcode = X86ISD::PCMPISTRI;
13944       X86CC = X86::COND_S;
13945       break;
13946     case Intrinsic::x86_sse42_pcmpestris128:
13947       Opcode = X86ISD::PCMPESTRI;
13948       X86CC = X86::COND_S;
13949       break;
13950     case Intrinsic::x86_sse42_pcmpistriz128:
13951       Opcode = X86ISD::PCMPISTRI;
13952       X86CC = X86::COND_E;
13953       break;
13954     case Intrinsic::x86_sse42_pcmpestriz128:
13955       Opcode = X86ISD::PCMPESTRI;
13956       X86CC = X86::COND_E;
13957       break;
13958     }
13959     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
13960     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13961     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
13962     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13963                                 DAG.getConstant(X86CC, MVT::i8),
13964                                 SDValue(PCMP.getNode(), 1));
13965     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13966   }
13967
13968   case Intrinsic::x86_sse42_pcmpistri128:
13969   case Intrinsic::x86_sse42_pcmpestri128: {
13970     unsigned Opcode;
13971     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
13972       Opcode = X86ISD::PCMPISTRI;
13973     else
13974       Opcode = X86ISD::PCMPESTRI;
13975
13976     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
13977     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13978     return DAG.getNode(Opcode, dl, VTs, NewOps);
13979   }
13980   case Intrinsic::x86_fma_vfmadd_ps:
13981   case Intrinsic::x86_fma_vfmadd_pd:
13982   case Intrinsic::x86_fma_vfmsub_ps:
13983   case Intrinsic::x86_fma_vfmsub_pd:
13984   case Intrinsic::x86_fma_vfnmadd_ps:
13985   case Intrinsic::x86_fma_vfnmadd_pd:
13986   case Intrinsic::x86_fma_vfnmsub_ps:
13987   case Intrinsic::x86_fma_vfnmsub_pd:
13988   case Intrinsic::x86_fma_vfmaddsub_ps:
13989   case Intrinsic::x86_fma_vfmaddsub_pd:
13990   case Intrinsic::x86_fma_vfmsubadd_ps:
13991   case Intrinsic::x86_fma_vfmsubadd_pd:
13992   case Intrinsic::x86_fma_vfmadd_ps_256:
13993   case Intrinsic::x86_fma_vfmadd_pd_256:
13994   case Intrinsic::x86_fma_vfmsub_ps_256:
13995   case Intrinsic::x86_fma_vfmsub_pd_256:
13996   case Intrinsic::x86_fma_vfnmadd_ps_256:
13997   case Intrinsic::x86_fma_vfnmadd_pd_256:
13998   case Intrinsic::x86_fma_vfnmsub_ps_256:
13999   case Intrinsic::x86_fma_vfnmsub_pd_256:
14000   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14001   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14002   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14003   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14004   case Intrinsic::x86_fma_vfmadd_ps_512:
14005   case Intrinsic::x86_fma_vfmadd_pd_512:
14006   case Intrinsic::x86_fma_vfmsub_ps_512:
14007   case Intrinsic::x86_fma_vfmsub_pd_512:
14008   case Intrinsic::x86_fma_vfnmadd_ps_512:
14009   case Intrinsic::x86_fma_vfnmadd_pd_512:
14010   case Intrinsic::x86_fma_vfnmsub_ps_512:
14011   case Intrinsic::x86_fma_vfnmsub_pd_512:
14012   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14013   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14014   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14015   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14016     unsigned Opc;
14017     switch (IntNo) {
14018     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14019     case Intrinsic::x86_fma_vfmadd_ps:
14020     case Intrinsic::x86_fma_vfmadd_pd:
14021     case Intrinsic::x86_fma_vfmadd_ps_256:
14022     case Intrinsic::x86_fma_vfmadd_pd_256:
14023     case Intrinsic::x86_fma_vfmadd_ps_512:
14024     case Intrinsic::x86_fma_vfmadd_pd_512:
14025       Opc = X86ISD::FMADD;
14026       break;
14027     case Intrinsic::x86_fma_vfmsub_ps:
14028     case Intrinsic::x86_fma_vfmsub_pd:
14029     case Intrinsic::x86_fma_vfmsub_ps_256:
14030     case Intrinsic::x86_fma_vfmsub_pd_256:
14031     case Intrinsic::x86_fma_vfmsub_ps_512:
14032     case Intrinsic::x86_fma_vfmsub_pd_512:
14033       Opc = X86ISD::FMSUB;
14034       break;
14035     case Intrinsic::x86_fma_vfnmadd_ps:
14036     case Intrinsic::x86_fma_vfnmadd_pd:
14037     case Intrinsic::x86_fma_vfnmadd_ps_256:
14038     case Intrinsic::x86_fma_vfnmadd_pd_256:
14039     case Intrinsic::x86_fma_vfnmadd_ps_512:
14040     case Intrinsic::x86_fma_vfnmadd_pd_512:
14041       Opc = X86ISD::FNMADD;
14042       break;
14043     case Intrinsic::x86_fma_vfnmsub_ps:
14044     case Intrinsic::x86_fma_vfnmsub_pd:
14045     case Intrinsic::x86_fma_vfnmsub_ps_256:
14046     case Intrinsic::x86_fma_vfnmsub_pd_256:
14047     case Intrinsic::x86_fma_vfnmsub_ps_512:
14048     case Intrinsic::x86_fma_vfnmsub_pd_512:
14049       Opc = X86ISD::FNMSUB;
14050       break;
14051     case Intrinsic::x86_fma_vfmaddsub_ps:
14052     case Intrinsic::x86_fma_vfmaddsub_pd:
14053     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14054     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14055     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14056     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14057       Opc = X86ISD::FMADDSUB;
14058       break;
14059     case Intrinsic::x86_fma_vfmsubadd_ps:
14060     case Intrinsic::x86_fma_vfmsubadd_pd:
14061     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14062     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14063     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14064     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14065       Opc = X86ISD::FMSUBADD;
14066       break;
14067     }
14068
14069     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14070                        Op.getOperand(2), Op.getOperand(3));
14071   }
14072   }
14073 }
14074
14075 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14076                               SDValue Src, SDValue Mask, SDValue Base,
14077                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14078                               const X86Subtarget * Subtarget) {
14079   SDLoc dl(Op);
14080   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14081   assert(C && "Invalid scale type");
14082   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14083   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14084                              Index.getSimpleValueType().getVectorNumElements());
14085   SDValue MaskInReg;
14086   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14087   if (MaskC)
14088     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14089   else
14090     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14091   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14092   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14093   SDValue Segment = DAG.getRegister(0, MVT::i32);
14094   if (Src.getOpcode() == ISD::UNDEF)
14095     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14096   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14097   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14098   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14099   return DAG.getMergeValues(RetOps, dl);
14100 }
14101
14102 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14103                                SDValue Src, SDValue Mask, SDValue Base,
14104                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14105   SDLoc dl(Op);
14106   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14107   assert(C && "Invalid scale type");
14108   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14109   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14110   SDValue Segment = DAG.getRegister(0, MVT::i32);
14111   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14112                              Index.getSimpleValueType().getVectorNumElements());
14113   SDValue MaskInReg;
14114   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14115   if (MaskC)
14116     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14117   else
14118     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14119   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14120   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14121   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14122   return SDValue(Res, 1);
14123 }
14124
14125 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14126                                SDValue Mask, SDValue Base, SDValue Index,
14127                                SDValue ScaleOp, SDValue Chain) {
14128   SDLoc dl(Op);
14129   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14130   assert(C && "Invalid scale type");
14131   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14132   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14133   SDValue Segment = DAG.getRegister(0, MVT::i32);
14134   EVT MaskVT =
14135     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14136   SDValue MaskInReg;
14137   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14138   if (MaskC)
14139     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14140   else
14141     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14142   //SDVTList VTs = DAG.getVTList(MVT::Other);
14143   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14144   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14145   return SDValue(Res, 0);
14146 }
14147
14148 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14149 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14150 // also used to custom lower READCYCLECOUNTER nodes.
14151 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14152                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14153                               SmallVectorImpl<SDValue> &Results) {
14154   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14155   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14156   SDValue LO, HI;
14157
14158   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14159   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14160   // and the EAX register is loaded with the low-order 32 bits.
14161   if (Subtarget->is64Bit()) {
14162     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14163     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14164                             LO.getValue(2));
14165   } else {
14166     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14167     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14168                             LO.getValue(2));
14169   }
14170   SDValue Chain = HI.getValue(1);
14171
14172   if (Opcode == X86ISD::RDTSCP_DAG) {
14173     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14174
14175     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14176     // the ECX register. Add 'ecx' explicitly to the chain.
14177     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14178                                      HI.getValue(2));
14179     // Explicitly store the content of ECX at the location passed in input
14180     // to the 'rdtscp' intrinsic.
14181     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14182                          MachinePointerInfo(), false, false, 0);
14183   }
14184
14185   if (Subtarget->is64Bit()) {
14186     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14187     // the EAX register is loaded with the low-order 32 bits.
14188     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14189                               DAG.getConstant(32, MVT::i8));
14190     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14191     Results.push_back(Chain);
14192     return;
14193   }
14194
14195   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14196   SDValue Ops[] = { LO, HI };
14197   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14198   Results.push_back(Pair);
14199   Results.push_back(Chain);
14200 }
14201
14202 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14203                                      SelectionDAG &DAG) {
14204   SmallVector<SDValue, 2> Results;
14205   SDLoc DL(Op);
14206   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14207                           Results);
14208   return DAG.getMergeValues(Results, DL);
14209 }
14210
14211 enum IntrinsicType {
14212   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
14213 };
14214
14215 struct IntrinsicData {
14216   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14217     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14218   IntrinsicType Type;
14219   unsigned      Opc0;
14220   unsigned      Opc1;
14221 };
14222
14223 std::map < unsigned, IntrinsicData> IntrMap;
14224 static void InitIntinsicsMap() {
14225   static bool Initialized = false;
14226   if (Initialized) 
14227     return;
14228   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14229                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14230   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14231                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14232   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14233                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14234   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14235                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14236   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14237                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14238   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14239                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14240   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14241                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14242   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14243                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14244   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14245                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14246
14247   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14248                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14249   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14250                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14251   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14252                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14253   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14254                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14255   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14256                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14257   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14258                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14259   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14260                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14261   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14262                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14263    
14264   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14265                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14266                                                         X86::VGATHERPF1QPSm)));
14267   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14268                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14269                                                         X86::VGATHERPF1QPDm)));
14270   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14271                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14272                                                         X86::VGATHERPF1DPDm)));
14273   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14274                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14275                                                         X86::VGATHERPF1DPSm)));
14276   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14277                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14278                                                         X86::VSCATTERPF1QPSm)));
14279   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14280                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14281                                                         X86::VSCATTERPF1QPDm)));
14282   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14283                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14284                                                         X86::VSCATTERPF1DPDm)));
14285   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14286                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14287                                                         X86::VSCATTERPF1DPSm)));
14288   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14289                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14290   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14291                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14292   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14293                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14294   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14295                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14296   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14297                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14298   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14299                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14300   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14301                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14302   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14303                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14304   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14305                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14306   Initialized = true;
14307 }
14308
14309 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14310                                       SelectionDAG &DAG) {
14311   InitIntinsicsMap();
14312   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14313   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14314   if (itr == IntrMap.end())
14315     return SDValue();
14316
14317   SDLoc dl(Op);
14318   IntrinsicData Intr = itr->second;
14319   switch(Intr.Type) {
14320   case RDSEED:
14321   case RDRAND: {
14322     // Emit the node with the right value type.
14323     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14324     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14325
14326     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14327     // Otherwise return the value from Rand, which is always 0, casted to i32.
14328     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14329                       DAG.getConstant(1, Op->getValueType(1)),
14330                       DAG.getConstant(X86::COND_B, MVT::i32),
14331                       SDValue(Result.getNode(), 1) };
14332     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14333                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14334                                   Ops);
14335
14336     // Return { result, isValid, chain }.
14337     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14338                        SDValue(Result.getNode(), 2));
14339   }
14340   case GATHER: {
14341   //gather(v1, mask, index, base, scale);
14342     SDValue Chain = Op.getOperand(0);
14343     SDValue Src   = Op.getOperand(2);
14344     SDValue Base  = Op.getOperand(3);
14345     SDValue Index = Op.getOperand(4);
14346     SDValue Mask  = Op.getOperand(5);
14347     SDValue Scale = Op.getOperand(6);
14348     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14349                           Subtarget);
14350   }
14351   case SCATTER: {
14352   //scatter(base, mask, index, v1, scale);
14353     SDValue Chain = Op.getOperand(0);
14354     SDValue Base  = Op.getOperand(2);
14355     SDValue Mask  = Op.getOperand(3);
14356     SDValue Index = Op.getOperand(4);
14357     SDValue Src   = Op.getOperand(5);
14358     SDValue Scale = Op.getOperand(6);
14359     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14360   }
14361   case PREFETCH: {
14362     SDValue Hint = Op.getOperand(6);
14363     unsigned HintVal;
14364     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14365         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14366       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14367     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14368     SDValue Chain = Op.getOperand(0);
14369     SDValue Mask  = Op.getOperand(2);
14370     SDValue Index = Op.getOperand(3);
14371     SDValue Base  = Op.getOperand(4);
14372     SDValue Scale = Op.getOperand(5);
14373     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14374   }
14375   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14376   case RDTSC: {
14377     SmallVector<SDValue, 2> Results;
14378     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14379     return DAG.getMergeValues(Results, dl);
14380   }
14381   // XTEST intrinsics.
14382   case XTEST: {
14383     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14384     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14385     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14386                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14387                                 InTrans);
14388     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14389     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14390                        Ret, SDValue(InTrans.getNode(), 1));
14391   }
14392   }
14393   llvm_unreachable("Unknown Intrinsic Type");
14394 }
14395
14396 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14397                                            SelectionDAG &DAG) const {
14398   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14399   MFI->setReturnAddressIsTaken(true);
14400
14401   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14402     return SDValue();
14403
14404   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14405   SDLoc dl(Op);
14406   EVT PtrVT = getPointerTy();
14407
14408   if (Depth > 0) {
14409     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14410     const X86RegisterInfo *RegInfo =
14411       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14412     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14413     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14414                        DAG.getNode(ISD::ADD, dl, PtrVT,
14415                                    FrameAddr, Offset),
14416                        MachinePointerInfo(), false, false, false, 0);
14417   }
14418
14419   // Just load the return address.
14420   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14421   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14422                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14423 }
14424
14425 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14426   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14427   MFI->setFrameAddressIsTaken(true);
14428
14429   EVT VT = Op.getValueType();
14430   SDLoc dl(Op);  // FIXME probably not meaningful
14431   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14432   const X86RegisterInfo *RegInfo =
14433     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14434   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14435   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14436           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14437          "Invalid Frame Register!");
14438   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14439   while (Depth--)
14440     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14441                             MachinePointerInfo(),
14442                             false, false, false, 0);
14443   return FrameAddr;
14444 }
14445
14446 // FIXME? Maybe this could be a TableGen attribute on some registers and
14447 // this table could be generated automatically from RegInfo.
14448 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14449                                               EVT VT) const {
14450   unsigned Reg = StringSwitch<unsigned>(RegName)
14451                        .Case("esp", X86::ESP)
14452                        .Case("rsp", X86::RSP)
14453                        .Default(0);
14454   if (Reg)
14455     return Reg;
14456   report_fatal_error("Invalid register name global variable");
14457 }
14458
14459 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14460                                                      SelectionDAG &DAG) const {
14461   const X86RegisterInfo *RegInfo =
14462     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14463   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14464 }
14465
14466 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14467   SDValue Chain     = Op.getOperand(0);
14468   SDValue Offset    = Op.getOperand(1);
14469   SDValue Handler   = Op.getOperand(2);
14470   SDLoc dl      (Op);
14471
14472   EVT PtrVT = getPointerTy();
14473   const X86RegisterInfo *RegInfo =
14474     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14475   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14476   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14477           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14478          "Invalid Frame Register!");
14479   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14480   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14481
14482   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14483                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14484   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14485   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14486                        false, false, 0);
14487   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14488
14489   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14490                      DAG.getRegister(StoreAddrReg, PtrVT));
14491 }
14492
14493 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14494                                                SelectionDAG &DAG) const {
14495   SDLoc DL(Op);
14496   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14497                      DAG.getVTList(MVT::i32, MVT::Other),
14498                      Op.getOperand(0), Op.getOperand(1));
14499 }
14500
14501 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14502                                                 SelectionDAG &DAG) const {
14503   SDLoc DL(Op);
14504   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14505                      Op.getOperand(0), Op.getOperand(1));
14506 }
14507
14508 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14509   return Op.getOperand(0);
14510 }
14511
14512 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14513                                                 SelectionDAG &DAG) const {
14514   SDValue Root = Op.getOperand(0);
14515   SDValue Trmp = Op.getOperand(1); // trampoline
14516   SDValue FPtr = Op.getOperand(2); // nested function
14517   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14518   SDLoc dl (Op);
14519
14520   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14521   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14522
14523   if (Subtarget->is64Bit()) {
14524     SDValue OutChains[6];
14525
14526     // Large code-model.
14527     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14528     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14529
14530     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14531     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14532
14533     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14534
14535     // Load the pointer to the nested function into R11.
14536     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14537     SDValue Addr = Trmp;
14538     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14539                                 Addr, MachinePointerInfo(TrmpAddr),
14540                                 false, false, 0);
14541
14542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14543                        DAG.getConstant(2, MVT::i64));
14544     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14545                                 MachinePointerInfo(TrmpAddr, 2),
14546                                 false, false, 2);
14547
14548     // Load the 'nest' parameter value into R10.
14549     // R10 is specified in X86CallingConv.td
14550     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14551     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14552                        DAG.getConstant(10, MVT::i64));
14553     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14554                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14555                                 false, false, 0);
14556
14557     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14558                        DAG.getConstant(12, MVT::i64));
14559     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14560                                 MachinePointerInfo(TrmpAddr, 12),
14561                                 false, false, 2);
14562
14563     // Jump to the nested function.
14564     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14566                        DAG.getConstant(20, MVT::i64));
14567     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14568                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14569                                 false, false, 0);
14570
14571     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14572     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14573                        DAG.getConstant(22, MVT::i64));
14574     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14575                                 MachinePointerInfo(TrmpAddr, 22),
14576                                 false, false, 0);
14577
14578     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14579   } else {
14580     const Function *Func =
14581       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14582     CallingConv::ID CC = Func->getCallingConv();
14583     unsigned NestReg;
14584
14585     switch (CC) {
14586     default:
14587       llvm_unreachable("Unsupported calling convention");
14588     case CallingConv::C:
14589     case CallingConv::X86_StdCall: {
14590       // Pass 'nest' parameter in ECX.
14591       // Must be kept in sync with X86CallingConv.td
14592       NestReg = X86::ECX;
14593
14594       // Check that ECX wasn't needed by an 'inreg' parameter.
14595       FunctionType *FTy = Func->getFunctionType();
14596       const AttributeSet &Attrs = Func->getAttributes();
14597
14598       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14599         unsigned InRegCount = 0;
14600         unsigned Idx = 1;
14601
14602         for (FunctionType::param_iterator I = FTy->param_begin(),
14603              E = FTy->param_end(); I != E; ++I, ++Idx)
14604           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14605             // FIXME: should only count parameters that are lowered to integers.
14606             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14607
14608         if (InRegCount > 2) {
14609           report_fatal_error("Nest register in use - reduce number of inreg"
14610                              " parameters!");
14611         }
14612       }
14613       break;
14614     }
14615     case CallingConv::X86_FastCall:
14616     case CallingConv::X86_ThisCall:
14617     case CallingConv::Fast:
14618       // Pass 'nest' parameter in EAX.
14619       // Must be kept in sync with X86CallingConv.td
14620       NestReg = X86::EAX;
14621       break;
14622     }
14623
14624     SDValue OutChains[4];
14625     SDValue Addr, Disp;
14626
14627     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14628                        DAG.getConstant(10, MVT::i32));
14629     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14630
14631     // This is storing the opcode for MOV32ri.
14632     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14633     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14634     OutChains[0] = DAG.getStore(Root, dl,
14635                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14636                                 Trmp, MachinePointerInfo(TrmpAddr),
14637                                 false, false, 0);
14638
14639     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14640                        DAG.getConstant(1, MVT::i32));
14641     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14642                                 MachinePointerInfo(TrmpAddr, 1),
14643                                 false, false, 1);
14644
14645     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14646     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14647                        DAG.getConstant(5, MVT::i32));
14648     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14649                                 MachinePointerInfo(TrmpAddr, 5),
14650                                 false, false, 1);
14651
14652     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14653                        DAG.getConstant(6, MVT::i32));
14654     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14655                                 MachinePointerInfo(TrmpAddr, 6),
14656                                 false, false, 1);
14657
14658     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14659   }
14660 }
14661
14662 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14663                                             SelectionDAG &DAG) const {
14664   /*
14665    The rounding mode is in bits 11:10 of FPSR, and has the following
14666    settings:
14667      00 Round to nearest
14668      01 Round to -inf
14669      10 Round to +inf
14670      11 Round to 0
14671
14672   FLT_ROUNDS, on the other hand, expects the following:
14673     -1 Undefined
14674      0 Round to 0
14675      1 Round to nearest
14676      2 Round to +inf
14677      3 Round to -inf
14678
14679   To perform the conversion, we do:
14680     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14681   */
14682
14683   MachineFunction &MF = DAG.getMachineFunction();
14684   const TargetMachine &TM = MF.getTarget();
14685   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14686   unsigned StackAlignment = TFI.getStackAlignment();
14687   MVT VT = Op.getSimpleValueType();
14688   SDLoc DL(Op);
14689
14690   // Save FP Control Word to stack slot
14691   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14692   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14693
14694   MachineMemOperand *MMO =
14695    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14696                            MachineMemOperand::MOStore, 2, 2);
14697
14698   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14699   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14700                                           DAG.getVTList(MVT::Other),
14701                                           Ops, MVT::i16, MMO);
14702
14703   // Load FP Control Word from stack slot
14704   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14705                             MachinePointerInfo(), false, false, false, 0);
14706
14707   // Transform as necessary
14708   SDValue CWD1 =
14709     DAG.getNode(ISD::SRL, DL, MVT::i16,
14710                 DAG.getNode(ISD::AND, DL, MVT::i16,
14711                             CWD, DAG.getConstant(0x800, MVT::i16)),
14712                 DAG.getConstant(11, MVT::i8));
14713   SDValue CWD2 =
14714     DAG.getNode(ISD::SRL, DL, MVT::i16,
14715                 DAG.getNode(ISD::AND, DL, MVT::i16,
14716                             CWD, DAG.getConstant(0x400, MVT::i16)),
14717                 DAG.getConstant(9, MVT::i8));
14718
14719   SDValue RetVal =
14720     DAG.getNode(ISD::AND, DL, MVT::i16,
14721                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14722                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14723                             DAG.getConstant(1, MVT::i16)),
14724                 DAG.getConstant(3, MVT::i16));
14725
14726   return DAG.getNode((VT.getSizeInBits() < 16 ?
14727                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14728 }
14729
14730 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14731   MVT VT = Op.getSimpleValueType();
14732   EVT OpVT = VT;
14733   unsigned NumBits = VT.getSizeInBits();
14734   SDLoc dl(Op);
14735
14736   Op = Op.getOperand(0);
14737   if (VT == MVT::i8) {
14738     // Zero extend to i32 since there is not an i8 bsr.
14739     OpVT = MVT::i32;
14740     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14741   }
14742
14743   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14744   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14745   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14746
14747   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14748   SDValue Ops[] = {
14749     Op,
14750     DAG.getConstant(NumBits+NumBits-1, OpVT),
14751     DAG.getConstant(X86::COND_E, MVT::i8),
14752     Op.getValue(1)
14753   };
14754   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14755
14756   // Finally xor with NumBits-1.
14757   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14758
14759   if (VT == MVT::i8)
14760     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14761   return Op;
14762 }
14763
14764 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14765   MVT VT = Op.getSimpleValueType();
14766   EVT OpVT = VT;
14767   unsigned NumBits = VT.getSizeInBits();
14768   SDLoc dl(Op);
14769
14770   Op = Op.getOperand(0);
14771   if (VT == MVT::i8) {
14772     // Zero extend to i32 since there is not an i8 bsr.
14773     OpVT = MVT::i32;
14774     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14775   }
14776
14777   // Issue a bsr (scan bits in reverse).
14778   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14779   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14780
14781   // And xor with NumBits-1.
14782   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14783
14784   if (VT == MVT::i8)
14785     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14786   return Op;
14787 }
14788
14789 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14790   MVT VT = Op.getSimpleValueType();
14791   unsigned NumBits = VT.getSizeInBits();
14792   SDLoc dl(Op);
14793   Op = Op.getOperand(0);
14794
14795   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14796   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14797   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14798
14799   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14800   SDValue Ops[] = {
14801     Op,
14802     DAG.getConstant(NumBits, VT),
14803     DAG.getConstant(X86::COND_E, MVT::i8),
14804     Op.getValue(1)
14805   };
14806   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14807 }
14808
14809 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14810 // ones, and then concatenate the result back.
14811 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14812   MVT VT = Op.getSimpleValueType();
14813
14814   assert(VT.is256BitVector() && VT.isInteger() &&
14815          "Unsupported value type for operation");
14816
14817   unsigned NumElems = VT.getVectorNumElements();
14818   SDLoc dl(Op);
14819
14820   // Extract the LHS vectors
14821   SDValue LHS = Op.getOperand(0);
14822   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14823   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14824
14825   // Extract the RHS vectors
14826   SDValue RHS = Op.getOperand(1);
14827   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14828   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14829
14830   MVT EltVT = VT.getVectorElementType();
14831   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14832
14833   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14834                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14835                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14836 }
14837
14838 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14839   assert(Op.getSimpleValueType().is256BitVector() &&
14840          Op.getSimpleValueType().isInteger() &&
14841          "Only handle AVX 256-bit vector integer operation");
14842   return Lower256IntArith(Op, DAG);
14843 }
14844
14845 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14846   assert(Op.getSimpleValueType().is256BitVector() &&
14847          Op.getSimpleValueType().isInteger() &&
14848          "Only handle AVX 256-bit vector integer operation");
14849   return Lower256IntArith(Op, DAG);
14850 }
14851
14852 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14853                         SelectionDAG &DAG) {
14854   SDLoc dl(Op);
14855   MVT VT = Op.getSimpleValueType();
14856
14857   // Decompose 256-bit ops into smaller 128-bit ops.
14858   if (VT.is256BitVector() && !Subtarget->hasInt256())
14859     return Lower256IntArith(Op, DAG);
14860
14861   SDValue A = Op.getOperand(0);
14862   SDValue B = Op.getOperand(1);
14863
14864   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14865   if (VT == MVT::v4i32) {
14866     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
14867            "Should not custom lower when pmuldq is available!");
14868
14869     // Extract the odd parts.
14870     static const int UnpackMask[] = { 1, -1, 3, -1 };
14871     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
14872     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
14873
14874     // Multiply the even parts.
14875     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
14876     // Now multiply odd parts.
14877     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
14878
14879     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
14880     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
14881
14882     // Merge the two vectors back together with a shuffle. This expands into 2
14883     // shuffles.
14884     static const int ShufMask[] = { 0, 4, 2, 6 };
14885     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
14886   }
14887
14888   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
14889          "Only know how to lower V2I64/V4I64/V8I64 multiply");
14890
14891   //  Ahi = psrlqi(a, 32);
14892   //  Bhi = psrlqi(b, 32);
14893   //
14894   //  AloBlo = pmuludq(a, b);
14895   //  AloBhi = pmuludq(a, Bhi);
14896   //  AhiBlo = pmuludq(Ahi, b);
14897
14898   //  AloBhi = psllqi(AloBhi, 32);
14899   //  AhiBlo = psllqi(AhiBlo, 32);
14900   //  return AloBlo + AloBhi + AhiBlo;
14901
14902   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
14903   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
14904
14905   // Bit cast to 32-bit vectors for MULUDQ
14906   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
14907                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
14908   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
14909   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
14910   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
14911   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
14912
14913   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
14914   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
14915   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
14916
14917   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
14918   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
14919
14920   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
14921   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
14922 }
14923
14924 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
14925   assert(Subtarget->isTargetWin64() && "Unexpected target");
14926   EVT VT = Op.getValueType();
14927   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
14928          "Unexpected return type for lowering");
14929
14930   RTLIB::Libcall LC;
14931   bool isSigned;
14932   switch (Op->getOpcode()) {
14933   default: llvm_unreachable("Unexpected request for libcall!");
14934   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
14935   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
14936   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
14937   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
14938   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
14939   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
14940   }
14941
14942   SDLoc dl(Op);
14943   SDValue InChain = DAG.getEntryNode();
14944
14945   TargetLowering::ArgListTy Args;
14946   TargetLowering::ArgListEntry Entry;
14947   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
14948     EVT ArgVT = Op->getOperand(i).getValueType();
14949     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
14950            "Unexpected argument type for lowering");
14951     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
14952     Entry.Node = StackPtr;
14953     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
14954                            false, false, 16);
14955     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14956     Entry.Ty = PointerType::get(ArgTy,0);
14957     Entry.isSExt = false;
14958     Entry.isZExt = false;
14959     Args.push_back(Entry);
14960   }
14961
14962   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14963                                          getPointerTy());
14964
14965   TargetLowering::CallLoweringInfo CLI(DAG);
14966   CLI.setDebugLoc(dl).setChain(InChain)
14967     .setCallee(getLibcallCallingConv(LC),
14968                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
14969                Callee, &Args, 0)
14970     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14971
14972   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14973   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
14974 }
14975
14976 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
14977                              SelectionDAG &DAG) {
14978   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
14979   EVT VT = Op0.getValueType();
14980   SDLoc dl(Op);
14981
14982   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
14983          (VT == MVT::v8i32 && Subtarget->hasInt256()));
14984
14985   // Get the high parts.
14986   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
14987   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
14988   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
14989
14990   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
14991   // ints.
14992   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
14993   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
14994   unsigned Opcode =
14995       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
14996   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
14997                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
14998   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
14999                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15000
15001   // Shuffle it back into the right order.
15002   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15003   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15004   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15005   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15006
15007   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15008   // unsigned multiply.
15009   if (IsSigned && !Subtarget->hasSSE41()) {
15010     SDValue ShAmt =
15011         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15012     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15013                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15014     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15015                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15016
15017     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15018     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15019   }
15020
15021   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15022 }
15023
15024 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15025                                          const X86Subtarget *Subtarget) {
15026   MVT VT = Op.getSimpleValueType();
15027   SDLoc dl(Op);
15028   SDValue R = Op.getOperand(0);
15029   SDValue Amt = Op.getOperand(1);
15030
15031   // Optimize shl/srl/sra with constant shift amount.
15032   if (isSplatVector(Amt.getNode())) {
15033     SDValue SclrAmt = Amt->getOperand(0);
15034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15035       uint64_t ShiftAmt = C->getZExtValue();
15036
15037       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15038           (Subtarget->hasInt256() &&
15039            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15040           (Subtarget->hasAVX512() &&
15041            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15042         if (Op.getOpcode() == ISD::SHL)
15043           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15044                                             DAG);
15045         if (Op.getOpcode() == ISD::SRL)
15046           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15047                                             DAG);
15048         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15049           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15050                                             DAG);
15051       }
15052
15053       if (VT == MVT::v16i8) {
15054         if (Op.getOpcode() == ISD::SHL) {
15055           // Make a large shift.
15056           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15057                                                    MVT::v8i16, R, ShiftAmt,
15058                                                    DAG);
15059           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15060           // Zero out the rightmost bits.
15061           SmallVector<SDValue, 16> V(16,
15062                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15063                                                      MVT::i8));
15064           return DAG.getNode(ISD::AND, dl, VT, SHL,
15065                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15066         }
15067         if (Op.getOpcode() == ISD::SRL) {
15068           // Make a large shift.
15069           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15070                                                    MVT::v8i16, R, ShiftAmt,
15071                                                    DAG);
15072           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15073           // Zero out the leftmost bits.
15074           SmallVector<SDValue, 16> V(16,
15075                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15076                                                      MVT::i8));
15077           return DAG.getNode(ISD::AND, dl, VT, SRL,
15078                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15079         }
15080         if (Op.getOpcode() == ISD::SRA) {
15081           if (ShiftAmt == 7) {
15082             // R s>> 7  ===  R s< 0
15083             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15084             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15085           }
15086
15087           // R s>> a === ((R u>> a) ^ m) - m
15088           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15089           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15090                                                          MVT::i8));
15091           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15092           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15093           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15094           return Res;
15095         }
15096         llvm_unreachable("Unknown shift opcode.");
15097       }
15098
15099       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15100         if (Op.getOpcode() == ISD::SHL) {
15101           // Make a large shift.
15102           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15103                                                    MVT::v16i16, R, ShiftAmt,
15104                                                    DAG);
15105           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15106           // Zero out the rightmost bits.
15107           SmallVector<SDValue, 32> V(32,
15108                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15109                                                      MVT::i8));
15110           return DAG.getNode(ISD::AND, dl, VT, SHL,
15111                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15112         }
15113         if (Op.getOpcode() == ISD::SRL) {
15114           // Make a large shift.
15115           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15116                                                    MVT::v16i16, R, ShiftAmt,
15117                                                    DAG);
15118           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15119           // Zero out the leftmost bits.
15120           SmallVector<SDValue, 32> V(32,
15121                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15122                                                      MVT::i8));
15123           return DAG.getNode(ISD::AND, dl, VT, SRL,
15124                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15125         }
15126         if (Op.getOpcode() == ISD::SRA) {
15127           if (ShiftAmt == 7) {
15128             // R s>> 7  ===  R s< 0
15129             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15130             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15131           }
15132
15133           // R s>> a === ((R u>> a) ^ m) - m
15134           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15135           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15136                                                          MVT::i8));
15137           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15138           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15139           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15140           return Res;
15141         }
15142         llvm_unreachable("Unknown shift opcode.");
15143       }
15144     }
15145   }
15146
15147   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15148   if (!Subtarget->is64Bit() &&
15149       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15150       Amt.getOpcode() == ISD::BITCAST &&
15151       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15152     Amt = Amt.getOperand(0);
15153     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15154                      VT.getVectorNumElements();
15155     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15156     uint64_t ShiftAmt = 0;
15157     for (unsigned i = 0; i != Ratio; ++i) {
15158       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15159       if (!C)
15160         return SDValue();
15161       // 6 == Log2(64)
15162       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15163     }
15164     // Check remaining shift amounts.
15165     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15166       uint64_t ShAmt = 0;
15167       for (unsigned j = 0; j != Ratio; ++j) {
15168         ConstantSDNode *C =
15169           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15170         if (!C)
15171           return SDValue();
15172         // 6 == Log2(64)
15173         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15174       }
15175       if (ShAmt != ShiftAmt)
15176         return SDValue();
15177     }
15178     switch (Op.getOpcode()) {
15179     default:
15180       llvm_unreachable("Unknown shift opcode!");
15181     case ISD::SHL:
15182       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15183                                         DAG);
15184     case ISD::SRL:
15185       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15186                                         DAG);
15187     case ISD::SRA:
15188       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15189                                         DAG);
15190     }
15191   }
15192
15193   return SDValue();
15194 }
15195
15196 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15197                                         const X86Subtarget* Subtarget) {
15198   MVT VT = Op.getSimpleValueType();
15199   SDLoc dl(Op);
15200   SDValue R = Op.getOperand(0);
15201   SDValue Amt = Op.getOperand(1);
15202
15203   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15204       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15205       (Subtarget->hasInt256() &&
15206        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15207         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15208        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15209     SDValue BaseShAmt;
15210     EVT EltVT = VT.getVectorElementType();
15211
15212     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15213       unsigned NumElts = VT.getVectorNumElements();
15214       unsigned i, j;
15215       for (i = 0; i != NumElts; ++i) {
15216         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15217           continue;
15218         break;
15219       }
15220       for (j = i; j != NumElts; ++j) {
15221         SDValue Arg = Amt.getOperand(j);
15222         if (Arg.getOpcode() == ISD::UNDEF) continue;
15223         if (Arg != Amt.getOperand(i))
15224           break;
15225       }
15226       if (i != NumElts && j == NumElts)
15227         BaseShAmt = Amt.getOperand(i);
15228     } else {
15229       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15230         Amt = Amt.getOperand(0);
15231       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15232                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15233         SDValue InVec = Amt.getOperand(0);
15234         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15235           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15236           unsigned i = 0;
15237           for (; i != NumElts; ++i) {
15238             SDValue Arg = InVec.getOperand(i);
15239             if (Arg.getOpcode() == ISD::UNDEF) continue;
15240             BaseShAmt = Arg;
15241             break;
15242           }
15243         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15244            if (ConstantSDNode *C =
15245                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15246              unsigned SplatIdx =
15247                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15248              if (C->getZExtValue() == SplatIdx)
15249                BaseShAmt = InVec.getOperand(1);
15250            }
15251         }
15252         if (!BaseShAmt.getNode())
15253           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15254                                   DAG.getIntPtrConstant(0));
15255       }
15256     }
15257
15258     if (BaseShAmt.getNode()) {
15259       if (EltVT.bitsGT(MVT::i32))
15260         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15261       else if (EltVT.bitsLT(MVT::i32))
15262         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15263
15264       switch (Op.getOpcode()) {
15265       default:
15266         llvm_unreachable("Unknown shift opcode!");
15267       case ISD::SHL:
15268         switch (VT.SimpleTy) {
15269         default: return SDValue();
15270         case MVT::v2i64:
15271         case MVT::v4i32:
15272         case MVT::v8i16:
15273         case MVT::v4i64:
15274         case MVT::v8i32:
15275         case MVT::v16i16:
15276         case MVT::v16i32:
15277         case MVT::v8i64:
15278           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15279         }
15280       case ISD::SRA:
15281         switch (VT.SimpleTy) {
15282         default: return SDValue();
15283         case MVT::v4i32:
15284         case MVT::v8i16:
15285         case MVT::v8i32:
15286         case MVT::v16i16:
15287         case MVT::v16i32:
15288         case MVT::v8i64:
15289           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15290         }
15291       case ISD::SRL:
15292         switch (VT.SimpleTy) {
15293         default: return SDValue();
15294         case MVT::v2i64:
15295         case MVT::v4i32:
15296         case MVT::v8i16:
15297         case MVT::v4i64:
15298         case MVT::v8i32:
15299         case MVT::v16i16:
15300         case MVT::v16i32:
15301         case MVT::v8i64:
15302           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15303         }
15304       }
15305     }
15306   }
15307
15308   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15309   if (!Subtarget->is64Bit() &&
15310       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15311       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15312       Amt.getOpcode() == ISD::BITCAST &&
15313       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15314     Amt = Amt.getOperand(0);
15315     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15316                      VT.getVectorNumElements();
15317     std::vector<SDValue> Vals(Ratio);
15318     for (unsigned i = 0; i != Ratio; ++i)
15319       Vals[i] = Amt.getOperand(i);
15320     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15321       for (unsigned j = 0; j != Ratio; ++j)
15322         if (Vals[j] != Amt.getOperand(i + j))
15323           return SDValue();
15324     }
15325     switch (Op.getOpcode()) {
15326     default:
15327       llvm_unreachable("Unknown shift opcode!");
15328     case ISD::SHL:
15329       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15330     case ISD::SRL:
15331       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15332     case ISD::SRA:
15333       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15334     }
15335   }
15336
15337   return SDValue();
15338 }
15339
15340 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15341                           SelectionDAG &DAG) {
15342
15343   MVT VT = Op.getSimpleValueType();
15344   SDLoc dl(Op);
15345   SDValue R = Op.getOperand(0);
15346   SDValue Amt = Op.getOperand(1);
15347   SDValue V;
15348
15349   if (!Subtarget->hasSSE2())
15350     return SDValue();
15351
15352   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15353   if (V.getNode())
15354     return V;
15355
15356   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15357   if (V.getNode())
15358       return V;
15359
15360   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15361     return Op;
15362   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15363   if (Subtarget->hasInt256()) {
15364     if (Op.getOpcode() == ISD::SRL &&
15365         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15366          VT == MVT::v4i64 || VT == MVT::v8i32))
15367       return Op;
15368     if (Op.getOpcode() == ISD::SHL &&
15369         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15370          VT == MVT::v4i64 || VT == MVT::v8i32))
15371       return Op;
15372     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15373       return Op;
15374   }
15375
15376   // If possible, lower this packed shift into a vector multiply instead of
15377   // expanding it into a sequence of scalar shifts.
15378   // Do this only if the vector shift count is a constant build_vector.
15379   if (Op.getOpcode() == ISD::SHL && 
15380       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15381        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15382       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15383     SmallVector<SDValue, 8> Elts;
15384     EVT SVT = VT.getScalarType();
15385     unsigned SVTBits = SVT.getSizeInBits();
15386     const APInt &One = APInt(SVTBits, 1);
15387     unsigned NumElems = VT.getVectorNumElements();
15388
15389     for (unsigned i=0; i !=NumElems; ++i) {
15390       SDValue Op = Amt->getOperand(i);
15391       if (Op->getOpcode() == ISD::UNDEF) {
15392         Elts.push_back(Op);
15393         continue;
15394       }
15395
15396       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15397       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15398       uint64_t ShAmt = C.getZExtValue();
15399       if (ShAmt >= SVTBits) {
15400         Elts.push_back(DAG.getUNDEF(SVT));
15401         continue;
15402       }
15403       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15404     }
15405     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15406     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15407   }
15408
15409   // Lower SHL with variable shift amount.
15410   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15411     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15412
15413     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15414     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15415     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15416     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15417   }
15418
15419   // If possible, lower this shift as a sequence of two shifts by
15420   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15421   // Example:
15422   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15423   //
15424   // Could be rewritten as:
15425   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15426   //
15427   // The advantage is that the two shifts from the example would be
15428   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15429   // the vector shift into four scalar shifts plus four pairs of vector
15430   // insert/extract.
15431   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15432       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15433     unsigned TargetOpcode = X86ISD::MOVSS;
15434     bool CanBeSimplified;
15435     // The splat value for the first packed shift (the 'X' from the example).
15436     SDValue Amt1 = Amt->getOperand(0);
15437     // The splat value for the second packed shift (the 'Y' from the example).
15438     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15439                                         Amt->getOperand(2);
15440
15441     // See if it is possible to replace this node with a sequence of
15442     // two shifts followed by a MOVSS/MOVSD
15443     if (VT == MVT::v4i32) {
15444       // Check if it is legal to use a MOVSS.
15445       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15446                         Amt2 == Amt->getOperand(3);
15447       if (!CanBeSimplified) {
15448         // Otherwise, check if we can still simplify this node using a MOVSD.
15449         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15450                           Amt->getOperand(2) == Amt->getOperand(3);
15451         TargetOpcode = X86ISD::MOVSD;
15452         Amt2 = Amt->getOperand(2);
15453       }
15454     } else {
15455       // Do similar checks for the case where the machine value type
15456       // is MVT::v8i16.
15457       CanBeSimplified = Amt1 == Amt->getOperand(1);
15458       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15459         CanBeSimplified = Amt2 == Amt->getOperand(i);
15460
15461       if (!CanBeSimplified) {
15462         TargetOpcode = X86ISD::MOVSD;
15463         CanBeSimplified = true;
15464         Amt2 = Amt->getOperand(4);
15465         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15466           CanBeSimplified = Amt1 == Amt->getOperand(i);
15467         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15468           CanBeSimplified = Amt2 == Amt->getOperand(j);
15469       }
15470     }
15471     
15472     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15473         isa<ConstantSDNode>(Amt2)) {
15474       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15475       EVT CastVT = MVT::v4i32;
15476       SDValue Splat1 = 
15477         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15478       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15479       SDValue Splat2 = 
15480         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15481       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15482       if (TargetOpcode == X86ISD::MOVSD)
15483         CastVT = MVT::v2i64;
15484       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15485       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15486       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15487                                             BitCast1, DAG);
15488       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15489     }
15490   }
15491
15492   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15493     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15494
15495     // a = a << 5;
15496     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15497     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15498
15499     // Turn 'a' into a mask suitable for VSELECT
15500     SDValue VSelM = DAG.getConstant(0x80, VT);
15501     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15502     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15503
15504     SDValue CM1 = DAG.getConstant(0x0f, VT);
15505     SDValue CM2 = DAG.getConstant(0x3f, VT);
15506
15507     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15508     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15509     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15510     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15511     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15512
15513     // a += a
15514     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15515     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15516     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15517
15518     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15519     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15520     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15521     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15522     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15523
15524     // a += a
15525     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15526     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15527     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15528
15529     // return VSELECT(r, r+r, a);
15530     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15531                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15532     return R;
15533   }
15534
15535   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15536   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15537   // solution better.
15538   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15539     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15540     unsigned ExtOpc =
15541         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15542     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15543     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15544     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15545                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15546     }
15547
15548   // Decompose 256-bit shifts into smaller 128-bit shifts.
15549   if (VT.is256BitVector()) {
15550     unsigned NumElems = VT.getVectorNumElements();
15551     MVT EltVT = VT.getVectorElementType();
15552     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15553
15554     // Extract the two vectors
15555     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15556     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15557
15558     // Recreate the shift amount vectors
15559     SDValue Amt1, Amt2;
15560     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15561       // Constant shift amount
15562       SmallVector<SDValue, 4> Amt1Csts;
15563       SmallVector<SDValue, 4> Amt2Csts;
15564       for (unsigned i = 0; i != NumElems/2; ++i)
15565         Amt1Csts.push_back(Amt->getOperand(i));
15566       for (unsigned i = NumElems/2; i != NumElems; ++i)
15567         Amt2Csts.push_back(Amt->getOperand(i));
15568
15569       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15570       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15571     } else {
15572       // Variable shift amount
15573       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15574       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15575     }
15576
15577     // Issue new vector shifts for the smaller types
15578     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15579     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15580
15581     // Concatenate the result back
15582     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15583   }
15584
15585   return SDValue();
15586 }
15587
15588 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15589   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15590   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15591   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15592   // has only one use.
15593   SDNode *N = Op.getNode();
15594   SDValue LHS = N->getOperand(0);
15595   SDValue RHS = N->getOperand(1);
15596   unsigned BaseOp = 0;
15597   unsigned Cond = 0;
15598   SDLoc DL(Op);
15599   switch (Op.getOpcode()) {
15600   default: llvm_unreachable("Unknown ovf instruction!");
15601   case ISD::SADDO:
15602     // A subtract of one will be selected as a INC. Note that INC doesn't
15603     // set CF, so we can't do this for UADDO.
15604     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15605       if (C->isOne()) {
15606         BaseOp = X86ISD::INC;
15607         Cond = X86::COND_O;
15608         break;
15609       }
15610     BaseOp = X86ISD::ADD;
15611     Cond = X86::COND_O;
15612     break;
15613   case ISD::UADDO:
15614     BaseOp = X86ISD::ADD;
15615     Cond = X86::COND_B;
15616     break;
15617   case ISD::SSUBO:
15618     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15619     // set CF, so we can't do this for USUBO.
15620     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15621       if (C->isOne()) {
15622         BaseOp = X86ISD::DEC;
15623         Cond = X86::COND_O;
15624         break;
15625       }
15626     BaseOp = X86ISD::SUB;
15627     Cond = X86::COND_O;
15628     break;
15629   case ISD::USUBO:
15630     BaseOp = X86ISD::SUB;
15631     Cond = X86::COND_B;
15632     break;
15633   case ISD::SMULO:
15634     BaseOp = X86ISD::SMUL;
15635     Cond = X86::COND_O;
15636     break;
15637   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15638     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15639                                  MVT::i32);
15640     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15641
15642     SDValue SetCC =
15643       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15644                   DAG.getConstant(X86::COND_O, MVT::i32),
15645                   SDValue(Sum.getNode(), 2));
15646
15647     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15648   }
15649   }
15650
15651   // Also sets EFLAGS.
15652   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15653   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15654
15655   SDValue SetCC =
15656     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15657                 DAG.getConstant(Cond, MVT::i32),
15658                 SDValue(Sum.getNode(), 1));
15659
15660   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15661 }
15662
15663 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15664                                                   SelectionDAG &DAG) const {
15665   SDLoc dl(Op);
15666   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15667   MVT VT = Op.getSimpleValueType();
15668
15669   if (!Subtarget->hasSSE2() || !VT.isVector())
15670     return SDValue();
15671
15672   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15673                       ExtraVT.getScalarType().getSizeInBits();
15674
15675   switch (VT.SimpleTy) {
15676     default: return SDValue();
15677     case MVT::v8i32:
15678     case MVT::v16i16:
15679       if (!Subtarget->hasFp256())
15680         return SDValue();
15681       if (!Subtarget->hasInt256()) {
15682         // needs to be split
15683         unsigned NumElems = VT.getVectorNumElements();
15684
15685         // Extract the LHS vectors
15686         SDValue LHS = Op.getOperand(0);
15687         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15688         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15689
15690         MVT EltVT = VT.getVectorElementType();
15691         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15692
15693         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15694         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15695         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15696                                    ExtraNumElems/2);
15697         SDValue Extra = DAG.getValueType(ExtraVT);
15698
15699         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15700         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15701
15702         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15703       }
15704       // fall through
15705     case MVT::v4i32:
15706     case MVT::v8i16: {
15707       SDValue Op0 = Op.getOperand(0);
15708       SDValue Op00 = Op0.getOperand(0);
15709       SDValue Tmp1;
15710       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15711       if (Op0.getOpcode() == ISD::BITCAST &&
15712           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15713         // (sext (vzext x)) -> (vsext x)
15714         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15715         if (Tmp1.getNode()) {
15716           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15717           // This folding is only valid when the in-reg type is a vector of i8,
15718           // i16, or i32.
15719           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15720               ExtraEltVT == MVT::i32) {
15721             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15722             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15723                    "This optimization is invalid without a VZEXT.");
15724             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15725           }
15726           Op0 = Tmp1;
15727         }
15728       }
15729
15730       // If the above didn't work, then just use Shift-Left + Shift-Right.
15731       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15732                                         DAG);
15733       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15734                                         DAG);
15735     }
15736   }
15737 }
15738
15739 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15740                                  SelectionDAG &DAG) {
15741   SDLoc dl(Op);
15742   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15743     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15744   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15745     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15746
15747   // The only fence that needs an instruction is a sequentially-consistent
15748   // cross-thread fence.
15749   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15750     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15751     // no-sse2). There isn't any reason to disable it if the target processor
15752     // supports it.
15753     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15754       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15755
15756     SDValue Chain = Op.getOperand(0);
15757     SDValue Zero = DAG.getConstant(0, MVT::i32);
15758     SDValue Ops[] = {
15759       DAG.getRegister(X86::ESP, MVT::i32), // Base
15760       DAG.getTargetConstant(1, MVT::i8),   // Scale
15761       DAG.getRegister(0, MVT::i32),        // Index
15762       DAG.getTargetConstant(0, MVT::i32),  // Disp
15763       DAG.getRegister(0, MVT::i32),        // Segment.
15764       Zero,
15765       Chain
15766     };
15767     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15768     return SDValue(Res, 0);
15769   }
15770
15771   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15772   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15773 }
15774
15775 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15776                              SelectionDAG &DAG) {
15777   MVT T = Op.getSimpleValueType();
15778   SDLoc DL(Op);
15779   unsigned Reg = 0;
15780   unsigned size = 0;
15781   switch(T.SimpleTy) {
15782   default: llvm_unreachable("Invalid value type!");
15783   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15784   case MVT::i16: Reg = X86::AX;  size = 2; break;
15785   case MVT::i32: Reg = X86::EAX; size = 4; break;
15786   case MVT::i64:
15787     assert(Subtarget->is64Bit() && "Node not type legal!");
15788     Reg = X86::RAX; size = 8;
15789     break;
15790   }
15791   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15792                                   Op.getOperand(2), SDValue());
15793   SDValue Ops[] = { cpIn.getValue(0),
15794                     Op.getOperand(1),
15795                     Op.getOperand(3),
15796                     DAG.getTargetConstant(size, MVT::i8),
15797                     cpIn.getValue(1) };
15798   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15799   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15800   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15801                                            Ops, T, MMO);
15802
15803   SDValue cpOut =
15804     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15805   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15806                                       MVT::i32, cpOut.getValue(2));
15807   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15808                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15809
15810   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15811   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15812   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15813   return SDValue();
15814 }
15815
15816 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15817                             SelectionDAG &DAG) {
15818   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15819   MVT DstVT = Op.getSimpleValueType();
15820
15821   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15822     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15823     if (DstVT != MVT::f64)
15824       // This conversion needs to be expanded.
15825       return SDValue();
15826
15827     SDValue InVec = Op->getOperand(0);
15828     SDLoc dl(Op);
15829     unsigned NumElts = SrcVT.getVectorNumElements();
15830     EVT SVT = SrcVT.getVectorElementType();
15831
15832     // Widen the vector in input in the case of MVT::v2i32.
15833     // Example: from MVT::v2i32 to MVT::v4i32.
15834     SmallVector<SDValue, 16> Elts;
15835     for (unsigned i = 0, e = NumElts; i != e; ++i)
15836       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15837                                  DAG.getIntPtrConstant(i)));
15838
15839     // Explicitly mark the extra elements as Undef.
15840     SDValue Undef = DAG.getUNDEF(SVT);
15841     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15842       Elts.push_back(Undef);
15843
15844     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15845     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15846     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15847     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15848                        DAG.getIntPtrConstant(0));
15849   }
15850
15851   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15852          Subtarget->hasMMX() && "Unexpected custom BITCAST");
15853   assert((DstVT == MVT::i64 ||
15854           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15855          "Unexpected custom BITCAST");
15856   // i64 <=> MMX conversions are Legal.
15857   if (SrcVT==MVT::i64 && DstVT.isVector())
15858     return Op;
15859   if (DstVT==MVT::i64 && SrcVT.isVector())
15860     return Op;
15861   // MMX <=> MMX conversions are Legal.
15862   if (SrcVT.isVector() && DstVT.isVector())
15863     return Op;
15864   // All other conversions need to be expanded.
15865   return SDValue();
15866 }
15867
15868 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
15869   SDNode *Node = Op.getNode();
15870   SDLoc dl(Node);
15871   EVT T = Node->getValueType(0);
15872   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
15873                               DAG.getConstant(0, T), Node->getOperand(2));
15874   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
15875                        cast<AtomicSDNode>(Node)->getMemoryVT(),
15876                        Node->getOperand(0),
15877                        Node->getOperand(1), negOp,
15878                        cast<AtomicSDNode>(Node)->getMemOperand(),
15879                        cast<AtomicSDNode>(Node)->getOrdering(),
15880                        cast<AtomicSDNode>(Node)->getSynchScope());
15881 }
15882
15883 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
15884   SDNode *Node = Op.getNode();
15885   SDLoc dl(Node);
15886   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15887
15888   // Convert seq_cst store -> xchg
15889   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
15890   // FIXME: On 32-bit, store -> fist or movq would be more efficient
15891   //        (The only way to get a 16-byte store is cmpxchg16b)
15892   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
15893   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
15894       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15895     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
15896                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
15897                                  Node->getOperand(0),
15898                                  Node->getOperand(1), Node->getOperand(2),
15899                                  cast<AtomicSDNode>(Node)->getMemOperand(),
15900                                  cast<AtomicSDNode>(Node)->getOrdering(),
15901                                  cast<AtomicSDNode>(Node)->getSynchScope());
15902     return Swap.getValue(1);
15903   }
15904   // Other atomic stores have a simple pattern.
15905   return Op;
15906 }
15907
15908 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
15909   EVT VT = Op.getNode()->getSimpleValueType(0);
15910
15911   // Let legalize expand this if it isn't a legal type yet.
15912   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15913     return SDValue();
15914
15915   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15916
15917   unsigned Opc;
15918   bool ExtraOp = false;
15919   switch (Op.getOpcode()) {
15920   default: llvm_unreachable("Invalid code");
15921   case ISD::ADDC: Opc = X86ISD::ADD; break;
15922   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
15923   case ISD::SUBC: Opc = X86ISD::SUB; break;
15924   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
15925   }
15926
15927   if (!ExtraOp)
15928     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
15929                        Op.getOperand(1));
15930   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
15931                      Op.getOperand(1), Op.getOperand(2));
15932 }
15933
15934 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
15935                             SelectionDAG &DAG) {
15936   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
15937
15938   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
15939   // which returns the values as { float, float } (in XMM0) or
15940   // { double, double } (which is returned in XMM0, XMM1).
15941   SDLoc dl(Op);
15942   SDValue Arg = Op.getOperand(0);
15943   EVT ArgVT = Arg.getValueType();
15944   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15945
15946   TargetLowering::ArgListTy Args;
15947   TargetLowering::ArgListEntry Entry;
15948
15949   Entry.Node = Arg;
15950   Entry.Ty = ArgTy;
15951   Entry.isSExt = false;
15952   Entry.isZExt = false;
15953   Args.push_back(Entry);
15954
15955   bool isF64 = ArgVT == MVT::f64;
15956   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
15957   // the small struct {f32, f32} is returned in (eax, edx). For f64,
15958   // the results are returned via SRet in memory.
15959   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
15960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15961   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
15962
15963   Type *RetTy = isF64
15964     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
15965     : (Type*)VectorType::get(ArgTy, 4);
15966
15967   TargetLowering::CallLoweringInfo CLI(DAG);
15968   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
15969     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
15970
15971   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
15972
15973   if (isF64)
15974     // Returned in xmm0 and xmm1.
15975     return CallResult.first;
15976
15977   // Returned in bits 0:31 and 32:64 xmm0.
15978   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
15979                                CallResult.first, DAG.getIntPtrConstant(0));
15980   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
15981                                CallResult.first, DAG.getIntPtrConstant(1));
15982   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
15983   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
15984 }
15985
15986 /// LowerOperation - Provide custom lowering hooks for some operations.
15987 ///
15988 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
15989   switch (Op.getOpcode()) {
15990   default: llvm_unreachable("Should not custom lower this!");
15991   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
15992   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
15993   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
15994     return LowerCMP_SWAP(Op, Subtarget, DAG);
15995   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
15996   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
15997   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
15998   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
15999   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16000   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16001   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16002   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16003   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16004   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16005   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16006   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16007   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16008   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16009   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16010   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16011   case ISD::SHL_PARTS:
16012   case ISD::SRA_PARTS:
16013   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16014   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16015   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16016   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16017   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16018   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16019   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16020   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16021   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16022   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16023   case ISD::FABS:               return LowerFABS(Op, DAG);
16024   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16025   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16026   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16027   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16028   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16029   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16030   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16031   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16032   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16033   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16034   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16035   case ISD::INTRINSIC_VOID:
16036   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16037   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16038   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16039   case ISD::FRAME_TO_ARGS_OFFSET:
16040                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16041   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16042   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16043   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16044   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16045   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16046   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16047   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16048   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16049   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16050   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16051   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16052   case ISD::UMUL_LOHI:
16053   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16054   case ISD::SRA:
16055   case ISD::SRL:
16056   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16057   case ISD::SADDO:
16058   case ISD::UADDO:
16059   case ISD::SSUBO:
16060   case ISD::USUBO:
16061   case ISD::SMULO:
16062   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16063   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16064   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16065   case ISD::ADDC:
16066   case ISD::ADDE:
16067   case ISD::SUBC:
16068   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16069   case ISD::ADD:                return LowerADD(Op, DAG);
16070   case ISD::SUB:                return LowerSUB(Op, DAG);
16071   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16072   }
16073 }
16074
16075 static void ReplaceATOMIC_LOAD(SDNode *Node,
16076                                SmallVectorImpl<SDValue> &Results,
16077                                SelectionDAG &DAG) {
16078   SDLoc dl(Node);
16079   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16080
16081   // Convert wide load -> cmpxchg8b/cmpxchg16b
16082   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16083   //        (The only way to get a 16-byte load is cmpxchg16b)
16084   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16085   SDValue Zero = DAG.getConstant(0, VT);
16086   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16087   SDValue Swap =
16088       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16089                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16090                            cast<AtomicSDNode>(Node)->getMemOperand(),
16091                            cast<AtomicSDNode>(Node)->getOrdering(),
16092                            cast<AtomicSDNode>(Node)->getOrdering(),
16093                            cast<AtomicSDNode>(Node)->getSynchScope());
16094   Results.push_back(Swap.getValue(0));
16095   Results.push_back(Swap.getValue(2));
16096 }
16097
16098 static void
16099 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
16100                         SelectionDAG &DAG, unsigned NewOp) {
16101   SDLoc dl(Node);
16102   assert (Node->getValueType(0) == MVT::i64 &&
16103           "Only know how to expand i64 atomics");
16104
16105   SDValue Chain = Node->getOperand(0);
16106   SDValue In1 = Node->getOperand(1);
16107   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16108                              Node->getOperand(2), DAG.getIntPtrConstant(0));
16109   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16110                              Node->getOperand(2), DAG.getIntPtrConstant(1));
16111   SDValue Ops[] = { Chain, In1, In2L, In2H };
16112   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
16113   SDValue Result =
16114     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
16115                             cast<MemSDNode>(Node)->getMemOperand());
16116   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
16117   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
16118   Results.push_back(Result.getValue(2));
16119 }
16120
16121 /// ReplaceNodeResults - Replace a node with an illegal result type
16122 /// with a new node built out of custom code.
16123 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16124                                            SmallVectorImpl<SDValue>&Results,
16125                                            SelectionDAG &DAG) const {
16126   SDLoc dl(N);
16127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16128   switch (N->getOpcode()) {
16129   default:
16130     llvm_unreachable("Do not know how to custom type legalize this operation!");
16131   case ISD::SIGN_EXTEND_INREG:
16132   case ISD::ADDC:
16133   case ISD::ADDE:
16134   case ISD::SUBC:
16135   case ISD::SUBE:
16136     // We don't want to expand or promote these.
16137     return;
16138   case ISD::SDIV:
16139   case ISD::UDIV:
16140   case ISD::SREM:
16141   case ISD::UREM:
16142   case ISD::SDIVREM:
16143   case ISD::UDIVREM: {
16144     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16145     Results.push_back(V);
16146     return;
16147   }
16148   case ISD::FP_TO_SINT:
16149   case ISD::FP_TO_UINT: {
16150     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16151
16152     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16153       return;
16154
16155     std::pair<SDValue,SDValue> Vals =
16156         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16157     SDValue FIST = Vals.first, StackSlot = Vals.second;
16158     if (FIST.getNode()) {
16159       EVT VT = N->getValueType(0);
16160       // Return a load from the stack slot.
16161       if (StackSlot.getNode())
16162         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16163                                       MachinePointerInfo(),
16164                                       false, false, false, 0));
16165       else
16166         Results.push_back(FIST);
16167     }
16168     return;
16169   }
16170   case ISD::UINT_TO_FP: {
16171     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16172     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16173         N->getValueType(0) != MVT::v2f32)
16174       return;
16175     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16176                                  N->getOperand(0));
16177     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16178                                      MVT::f64);
16179     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16180     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16181                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16182     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16183     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16184     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16185     return;
16186   }
16187   case ISD::FP_ROUND: {
16188     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16189         return;
16190     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16191     Results.push_back(V);
16192     return;
16193   }
16194   case ISD::INTRINSIC_W_CHAIN: {
16195     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16196     switch (IntNo) {
16197     default : llvm_unreachable("Do not know how to custom type "
16198                                "legalize this intrinsic operation!");
16199     case Intrinsic::x86_rdtsc:
16200       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16201                                      Results);
16202     case Intrinsic::x86_rdtscp:
16203       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16204                                      Results);
16205     }
16206   }
16207   case ISD::READCYCLECOUNTER: {
16208     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16209                                    Results);
16210   }
16211   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16212     EVT T = N->getValueType(0);
16213     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16214     bool Regs64bit = T == MVT::i128;
16215     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16216     SDValue cpInL, cpInH;
16217     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16218                         DAG.getConstant(0, HalfT));
16219     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16220                         DAG.getConstant(1, HalfT));
16221     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16222                              Regs64bit ? X86::RAX : X86::EAX,
16223                              cpInL, SDValue());
16224     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16225                              Regs64bit ? X86::RDX : X86::EDX,
16226                              cpInH, cpInL.getValue(1));
16227     SDValue swapInL, swapInH;
16228     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16229                           DAG.getConstant(0, HalfT));
16230     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16231                           DAG.getConstant(1, HalfT));
16232     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16233                                Regs64bit ? X86::RBX : X86::EBX,
16234                                swapInL, cpInH.getValue(1));
16235     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16236                                Regs64bit ? X86::RCX : X86::ECX,
16237                                swapInH, swapInL.getValue(1));
16238     SDValue Ops[] = { swapInH.getValue(0),
16239                       N->getOperand(1),
16240                       swapInH.getValue(1) };
16241     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16242     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16243     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16244                                   X86ISD::LCMPXCHG8_DAG;
16245     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16246     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16247                                         Regs64bit ? X86::RAX : X86::EAX,
16248                                         HalfT, Result.getValue(1));
16249     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16250                                         Regs64bit ? X86::RDX : X86::EDX,
16251                                         HalfT, cpOutL.getValue(2));
16252     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16253
16254     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16255                                         MVT::i32, cpOutH.getValue(2));
16256     SDValue Success =
16257         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16258                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16259     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16260
16261     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16262     Results.push_back(Success);
16263     Results.push_back(EFLAGS.getValue(1));
16264     return;
16265   }
16266   case ISD::ATOMIC_LOAD_ADD:
16267   case ISD::ATOMIC_LOAD_AND:
16268   case ISD::ATOMIC_LOAD_NAND:
16269   case ISD::ATOMIC_LOAD_OR:
16270   case ISD::ATOMIC_LOAD_SUB:
16271   case ISD::ATOMIC_LOAD_XOR:
16272   case ISD::ATOMIC_LOAD_MAX:
16273   case ISD::ATOMIC_LOAD_MIN:
16274   case ISD::ATOMIC_LOAD_UMAX:
16275   case ISD::ATOMIC_LOAD_UMIN:
16276   case ISD::ATOMIC_SWAP: {
16277     unsigned Opc;
16278     switch (N->getOpcode()) {
16279     default: llvm_unreachable("Unexpected opcode");
16280     case ISD::ATOMIC_LOAD_ADD:
16281       Opc = X86ISD::ATOMADD64_DAG;
16282       break;
16283     case ISD::ATOMIC_LOAD_AND:
16284       Opc = X86ISD::ATOMAND64_DAG;
16285       break;
16286     case ISD::ATOMIC_LOAD_NAND:
16287       Opc = X86ISD::ATOMNAND64_DAG;
16288       break;
16289     case ISD::ATOMIC_LOAD_OR:
16290       Opc = X86ISD::ATOMOR64_DAG;
16291       break;
16292     case ISD::ATOMIC_LOAD_SUB:
16293       Opc = X86ISD::ATOMSUB64_DAG;
16294       break;
16295     case ISD::ATOMIC_LOAD_XOR:
16296       Opc = X86ISD::ATOMXOR64_DAG;
16297       break;
16298     case ISD::ATOMIC_LOAD_MAX:
16299       Opc = X86ISD::ATOMMAX64_DAG;
16300       break;
16301     case ISD::ATOMIC_LOAD_MIN:
16302       Opc = X86ISD::ATOMMIN64_DAG;
16303       break;
16304     case ISD::ATOMIC_LOAD_UMAX:
16305       Opc = X86ISD::ATOMUMAX64_DAG;
16306       break;
16307     case ISD::ATOMIC_LOAD_UMIN:
16308       Opc = X86ISD::ATOMUMIN64_DAG;
16309       break;
16310     case ISD::ATOMIC_SWAP:
16311       Opc = X86ISD::ATOMSWAP64_DAG;
16312       break;
16313     }
16314     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
16315     return;
16316   }
16317   case ISD::ATOMIC_LOAD: {
16318     ReplaceATOMIC_LOAD(N, Results, DAG);
16319     return;
16320   }
16321   case ISD::BITCAST: {
16322     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16323     EVT DstVT = N->getValueType(0);
16324     EVT SrcVT = N->getOperand(0)->getValueType(0);
16325
16326     if (SrcVT != MVT::f64 ||
16327         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16328       return;
16329
16330     unsigned NumElts = DstVT.getVectorNumElements();
16331     EVT SVT = DstVT.getVectorElementType();
16332     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16333     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16334                                    MVT::v2f64, N->getOperand(0));
16335     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16336
16337     SmallVector<SDValue, 8> Elts;
16338     for (unsigned i = 0, e = NumElts; i != e; ++i)
16339       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16340                                    ToVecInt, DAG.getIntPtrConstant(i)));
16341
16342     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16343   }
16344   }
16345 }
16346
16347 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16348   switch (Opcode) {
16349   default: return nullptr;
16350   case X86ISD::BSF:                return "X86ISD::BSF";
16351   case X86ISD::BSR:                return "X86ISD::BSR";
16352   case X86ISD::SHLD:               return "X86ISD::SHLD";
16353   case X86ISD::SHRD:               return "X86ISD::SHRD";
16354   case X86ISD::FAND:               return "X86ISD::FAND";
16355   case X86ISD::FANDN:              return "X86ISD::FANDN";
16356   case X86ISD::FOR:                return "X86ISD::FOR";
16357   case X86ISD::FXOR:               return "X86ISD::FXOR";
16358   case X86ISD::FSRL:               return "X86ISD::FSRL";
16359   case X86ISD::FILD:               return "X86ISD::FILD";
16360   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16361   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16362   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16363   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16364   case X86ISD::FLD:                return "X86ISD::FLD";
16365   case X86ISD::FST:                return "X86ISD::FST";
16366   case X86ISD::CALL:               return "X86ISD::CALL";
16367   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16368   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16369   case X86ISD::BT:                 return "X86ISD::BT";
16370   case X86ISD::CMP:                return "X86ISD::CMP";
16371   case X86ISD::COMI:               return "X86ISD::COMI";
16372   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16373   case X86ISD::CMPM:               return "X86ISD::CMPM";
16374   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16375   case X86ISD::SETCC:              return "X86ISD::SETCC";
16376   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16377   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16378   case X86ISD::CMOV:               return "X86ISD::CMOV";
16379   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16380   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16381   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16382   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16383   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16384   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16385   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16386   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16387   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16388   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16389   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16390   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16391   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16392   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16393   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16394   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16395   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16396   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16397   case X86ISD::HADD:               return "X86ISD::HADD";
16398   case X86ISD::HSUB:               return "X86ISD::HSUB";
16399   case X86ISD::FHADD:              return "X86ISD::FHADD";
16400   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16401   case X86ISD::UMAX:               return "X86ISD::UMAX";
16402   case X86ISD::UMIN:               return "X86ISD::UMIN";
16403   case X86ISD::SMAX:               return "X86ISD::SMAX";
16404   case X86ISD::SMIN:               return "X86ISD::SMIN";
16405   case X86ISD::FMAX:               return "X86ISD::FMAX";
16406   case X86ISD::FMIN:               return "X86ISD::FMIN";
16407   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16408   case X86ISD::FMINC:              return "X86ISD::FMINC";
16409   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16410   case X86ISD::FRCP:               return "X86ISD::FRCP";
16411   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16412   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16413   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16414   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16415   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16416   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16417   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16418   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16419   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16420   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16421   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16422   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16423   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
16424   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
16425   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
16426   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
16427   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
16428   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
16429   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16430   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16431   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16432   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16433   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16434   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16435   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16436   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16437   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16438   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16439   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16440   case X86ISD::VSHL:               return "X86ISD::VSHL";
16441   case X86ISD::VSRL:               return "X86ISD::VSRL";
16442   case X86ISD::VSRA:               return "X86ISD::VSRA";
16443   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16444   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16445   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16446   case X86ISD::CMPP:               return "X86ISD::CMPP";
16447   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16448   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16449   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16450   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16451   case X86ISD::ADD:                return "X86ISD::ADD";
16452   case X86ISD::SUB:                return "X86ISD::SUB";
16453   case X86ISD::ADC:                return "X86ISD::ADC";
16454   case X86ISD::SBB:                return "X86ISD::SBB";
16455   case X86ISD::SMUL:               return "X86ISD::SMUL";
16456   case X86ISD::UMUL:               return "X86ISD::UMUL";
16457   case X86ISD::INC:                return "X86ISD::INC";
16458   case X86ISD::DEC:                return "X86ISD::DEC";
16459   case X86ISD::OR:                 return "X86ISD::OR";
16460   case X86ISD::XOR:                return "X86ISD::XOR";
16461   case X86ISD::AND:                return "X86ISD::AND";
16462   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16463   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16464   case X86ISD::PTEST:              return "X86ISD::PTEST";
16465   case X86ISD::TESTP:              return "X86ISD::TESTP";
16466   case X86ISD::TESTM:              return "X86ISD::TESTM";
16467   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16468   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16469   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16470   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16471   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16472   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16473   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16474   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16475   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16476   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16477   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16478   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16479   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16480   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16481   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16482   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16483   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16484   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16485   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16486   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16487   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16488   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16489   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16490   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16491   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16492   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16493   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16494   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16495   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16496   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16497   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16498   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16499   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16500   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16501   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16502   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16503   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16504   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16505   case X86ISD::SAHF:               return "X86ISD::SAHF";
16506   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16507   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16508   case X86ISD::FMADD:              return "X86ISD::FMADD";
16509   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16510   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16511   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16512   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16513   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16514   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16515   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16516   case X86ISD::XTEST:              return "X86ISD::XTEST";
16517   }
16518 }
16519
16520 // isLegalAddressingMode - Return true if the addressing mode represented
16521 // by AM is legal for this target, for a load/store of the specified type.
16522 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16523                                               Type *Ty) const {
16524   // X86 supports extremely general addressing modes.
16525   CodeModel::Model M = getTargetMachine().getCodeModel();
16526   Reloc::Model R = getTargetMachine().getRelocationModel();
16527
16528   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16529   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16530     return false;
16531
16532   if (AM.BaseGV) {
16533     unsigned GVFlags =
16534       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16535
16536     // If a reference to this global requires an extra load, we can't fold it.
16537     if (isGlobalStubReference(GVFlags))
16538       return false;
16539
16540     // If BaseGV requires a register for the PIC base, we cannot also have a
16541     // BaseReg specified.
16542     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16543       return false;
16544
16545     // If lower 4G is not available, then we must use rip-relative addressing.
16546     if ((M != CodeModel::Small || R != Reloc::Static) &&
16547         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16548       return false;
16549   }
16550
16551   switch (AM.Scale) {
16552   case 0:
16553   case 1:
16554   case 2:
16555   case 4:
16556   case 8:
16557     // These scales always work.
16558     break;
16559   case 3:
16560   case 5:
16561   case 9:
16562     // These scales are formed with basereg+scalereg.  Only accept if there is
16563     // no basereg yet.
16564     if (AM.HasBaseReg)
16565       return false;
16566     break;
16567   default:  // Other stuff never works.
16568     return false;
16569   }
16570
16571   return true;
16572 }
16573
16574 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16575   unsigned Bits = Ty->getScalarSizeInBits();
16576
16577   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16578   // particularly cheaper than those without.
16579   if (Bits == 8)
16580     return false;
16581
16582   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16583   // variable shifts just as cheap as scalar ones.
16584   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16585     return false;
16586
16587   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16588   // fully general vector.
16589   return true;
16590 }
16591
16592 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16593   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16594     return false;
16595   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16596   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16597   return NumBits1 > NumBits2;
16598 }
16599
16600 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16601   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16602     return false;
16603
16604   if (!isTypeLegal(EVT::getEVT(Ty1)))
16605     return false;
16606
16607   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16608
16609   // Assuming the caller doesn't have a zeroext or signext return parameter,
16610   // truncation all the way down to i1 is valid.
16611   return true;
16612 }
16613
16614 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16615   return isInt<32>(Imm);
16616 }
16617
16618 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16619   // Can also use sub to handle negated immediates.
16620   return isInt<32>(Imm);
16621 }
16622
16623 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16624   if (!VT1.isInteger() || !VT2.isInteger())
16625     return false;
16626   unsigned NumBits1 = VT1.getSizeInBits();
16627   unsigned NumBits2 = VT2.getSizeInBits();
16628   return NumBits1 > NumBits2;
16629 }
16630
16631 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16632   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16633   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16634 }
16635
16636 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16637   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16638   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16639 }
16640
16641 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16642   EVT VT1 = Val.getValueType();
16643   if (isZExtFree(VT1, VT2))
16644     return true;
16645
16646   if (Val.getOpcode() != ISD::LOAD)
16647     return false;
16648
16649   if (!VT1.isSimple() || !VT1.isInteger() ||
16650       !VT2.isSimple() || !VT2.isInteger())
16651     return false;
16652
16653   switch (VT1.getSimpleVT().SimpleTy) {
16654   default: break;
16655   case MVT::i8:
16656   case MVT::i16:
16657   case MVT::i32:
16658     // X86 has 8, 16, and 32-bit zero-extending loads.
16659     return true;
16660   }
16661
16662   return false;
16663 }
16664
16665 bool
16666 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16667   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16668     return false;
16669
16670   VT = VT.getScalarType();
16671
16672   if (!VT.isSimple())
16673     return false;
16674
16675   switch (VT.getSimpleVT().SimpleTy) {
16676   case MVT::f32:
16677   case MVT::f64:
16678     return true;
16679   default:
16680     break;
16681   }
16682
16683   return false;
16684 }
16685
16686 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16687   // i16 instructions are longer (0x66 prefix) and potentially slower.
16688   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16689 }
16690
16691 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16692 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16693 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16694 /// are assumed to be legal.
16695 bool
16696 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16697                                       EVT VT) const {
16698   if (!VT.isSimple())
16699     return false;
16700
16701   MVT SVT = VT.getSimpleVT();
16702
16703   // Very little shuffling can be done for 64-bit vectors right now.
16704   if (VT.getSizeInBits() == 64)
16705     return false;
16706
16707   // If this is a single-input shuffle with no 128 bit lane crossings we can
16708   // lower it into pshufb.
16709   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16710       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16711     bool isLegal = true;
16712     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16713       if (M[I] >= (int)SVT.getVectorNumElements() ||
16714           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16715         isLegal = false;
16716         break;
16717       }
16718     }
16719     if (isLegal)
16720       return true;
16721   }
16722
16723   // FIXME: blends, shifts.
16724   return (SVT.getVectorNumElements() == 2 ||
16725           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16726           isMOVLMask(M, SVT) ||
16727           isSHUFPMask(M, SVT) ||
16728           isPSHUFDMask(M, SVT) ||
16729           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16730           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16731           isPALIGNRMask(M, SVT, Subtarget) ||
16732           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16733           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16734           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16735           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16736           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16737 }
16738
16739 bool
16740 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16741                                           EVT VT) const {
16742   if (!VT.isSimple())
16743     return false;
16744
16745   MVT SVT = VT.getSimpleVT();
16746   unsigned NumElts = SVT.getVectorNumElements();
16747   // FIXME: This collection of masks seems suspect.
16748   if (NumElts == 2)
16749     return true;
16750   if (NumElts == 4 && SVT.is128BitVector()) {
16751     return (isMOVLMask(Mask, SVT)  ||
16752             isCommutedMOVLMask(Mask, SVT, true) ||
16753             isSHUFPMask(Mask, SVT) ||
16754             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16755   }
16756   return false;
16757 }
16758
16759 //===----------------------------------------------------------------------===//
16760 //                           X86 Scheduler Hooks
16761 //===----------------------------------------------------------------------===//
16762
16763 /// Utility function to emit xbegin specifying the start of an RTM region.
16764 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16765                                      const TargetInstrInfo *TII) {
16766   DebugLoc DL = MI->getDebugLoc();
16767
16768   const BasicBlock *BB = MBB->getBasicBlock();
16769   MachineFunction::iterator I = MBB;
16770   ++I;
16771
16772   // For the v = xbegin(), we generate
16773   //
16774   // thisMBB:
16775   //  xbegin sinkMBB
16776   //
16777   // mainMBB:
16778   //  eax = -1
16779   //
16780   // sinkMBB:
16781   //  v = eax
16782
16783   MachineBasicBlock *thisMBB = MBB;
16784   MachineFunction *MF = MBB->getParent();
16785   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16786   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16787   MF->insert(I, mainMBB);
16788   MF->insert(I, sinkMBB);
16789
16790   // Transfer the remainder of BB and its successor edges to sinkMBB.
16791   sinkMBB->splice(sinkMBB->begin(), MBB,
16792                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16793   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16794
16795   // thisMBB:
16796   //  xbegin sinkMBB
16797   //  # fallthrough to mainMBB
16798   //  # abortion to sinkMBB
16799   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16800   thisMBB->addSuccessor(mainMBB);
16801   thisMBB->addSuccessor(sinkMBB);
16802
16803   // mainMBB:
16804   //  EAX = -1
16805   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16806   mainMBB->addSuccessor(sinkMBB);
16807
16808   // sinkMBB:
16809   // EAX is live into the sinkMBB
16810   sinkMBB->addLiveIn(X86::EAX);
16811   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16812           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16813     .addReg(X86::EAX);
16814
16815   MI->eraseFromParent();
16816   return sinkMBB;
16817 }
16818
16819 // Get CMPXCHG opcode for the specified data type.
16820 static unsigned getCmpXChgOpcode(EVT VT) {
16821   switch (VT.getSimpleVT().SimpleTy) {
16822   case MVT::i8:  return X86::LCMPXCHG8;
16823   case MVT::i16: return X86::LCMPXCHG16;
16824   case MVT::i32: return X86::LCMPXCHG32;
16825   case MVT::i64: return X86::LCMPXCHG64;
16826   default:
16827     break;
16828   }
16829   llvm_unreachable("Invalid operand size!");
16830 }
16831
16832 // Get LOAD opcode for the specified data type.
16833 static unsigned getLoadOpcode(EVT VT) {
16834   switch (VT.getSimpleVT().SimpleTy) {
16835   case MVT::i8:  return X86::MOV8rm;
16836   case MVT::i16: return X86::MOV16rm;
16837   case MVT::i32: return X86::MOV32rm;
16838   case MVT::i64: return X86::MOV64rm;
16839   default:
16840     break;
16841   }
16842   llvm_unreachable("Invalid operand size!");
16843 }
16844
16845 // Get opcode of the non-atomic one from the specified atomic instruction.
16846 static unsigned getNonAtomicOpcode(unsigned Opc) {
16847   switch (Opc) {
16848   case X86::ATOMAND8:  return X86::AND8rr;
16849   case X86::ATOMAND16: return X86::AND16rr;
16850   case X86::ATOMAND32: return X86::AND32rr;
16851   case X86::ATOMAND64: return X86::AND64rr;
16852   case X86::ATOMOR8:   return X86::OR8rr;
16853   case X86::ATOMOR16:  return X86::OR16rr;
16854   case X86::ATOMOR32:  return X86::OR32rr;
16855   case X86::ATOMOR64:  return X86::OR64rr;
16856   case X86::ATOMXOR8:  return X86::XOR8rr;
16857   case X86::ATOMXOR16: return X86::XOR16rr;
16858   case X86::ATOMXOR32: return X86::XOR32rr;
16859   case X86::ATOMXOR64: return X86::XOR64rr;
16860   }
16861   llvm_unreachable("Unhandled atomic-load-op opcode!");
16862 }
16863
16864 // Get opcode of the non-atomic one from the specified atomic instruction with
16865 // extra opcode.
16866 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
16867                                                unsigned &ExtraOpc) {
16868   switch (Opc) {
16869   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
16870   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
16871   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
16872   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
16873   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
16874   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
16875   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
16876   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
16877   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
16878   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
16879   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
16880   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
16881   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
16882   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
16883   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
16884   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
16885   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
16886   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
16887   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
16888   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
16889   }
16890   llvm_unreachable("Unhandled atomic-load-op opcode!");
16891 }
16892
16893 // Get opcode of the non-atomic one from the specified atomic instruction for
16894 // 64-bit data type on 32-bit target.
16895 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
16896   switch (Opc) {
16897   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
16898   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
16899   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
16900   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
16901   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
16902   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
16903   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
16904   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
16905   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
16906   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
16907   }
16908   llvm_unreachable("Unhandled atomic-load-op opcode!");
16909 }
16910
16911 // Get opcode of the non-atomic one from the specified atomic instruction for
16912 // 64-bit data type on 32-bit target with extra opcode.
16913 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
16914                                                    unsigned &HiOpc,
16915                                                    unsigned &ExtraOpc) {
16916   switch (Opc) {
16917   case X86::ATOMNAND6432:
16918     ExtraOpc = X86::NOT32r;
16919     HiOpc = X86::AND32rr;
16920     return X86::AND32rr;
16921   }
16922   llvm_unreachable("Unhandled atomic-load-op opcode!");
16923 }
16924
16925 // Get pseudo CMOV opcode from the specified data type.
16926 static unsigned getPseudoCMOVOpc(EVT VT) {
16927   switch (VT.getSimpleVT().SimpleTy) {
16928   case MVT::i8:  return X86::CMOV_GR8;
16929   case MVT::i16: return X86::CMOV_GR16;
16930   case MVT::i32: return X86::CMOV_GR32;
16931   default:
16932     break;
16933   }
16934   llvm_unreachable("Unknown CMOV opcode!");
16935 }
16936
16937 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
16938 // They will be translated into a spin-loop or compare-exchange loop from
16939 //
16940 //    ...
16941 //    dst = atomic-fetch-op MI.addr, MI.val
16942 //    ...
16943 //
16944 // to
16945 //
16946 //    ...
16947 //    t1 = LOAD MI.addr
16948 // loop:
16949 //    t4 = phi(t1, t3 / loop)
16950 //    t2 = OP MI.val, t4
16951 //    EAX = t4
16952 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
16953 //    t3 = EAX
16954 //    JNE loop
16955 // sink:
16956 //    dst = t3
16957 //    ...
16958 MachineBasicBlock *
16959 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
16960                                        MachineBasicBlock *MBB) const {
16961   MachineFunction *MF = MBB->getParent();
16962   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16963   DebugLoc DL = MI->getDebugLoc();
16964
16965   MachineRegisterInfo &MRI = MF->getRegInfo();
16966
16967   const BasicBlock *BB = MBB->getBasicBlock();
16968   MachineFunction::iterator I = MBB;
16969   ++I;
16970
16971   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
16972          "Unexpected number of operands");
16973
16974   assert(MI->hasOneMemOperand() &&
16975          "Expected atomic-load-op to have one memoperand");
16976
16977   // Memory Reference
16978   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16979   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16980
16981   unsigned DstReg, SrcReg;
16982   unsigned MemOpndSlot;
16983
16984   unsigned CurOp = 0;
16985
16986   DstReg = MI->getOperand(CurOp++).getReg();
16987   MemOpndSlot = CurOp;
16988   CurOp += X86::AddrNumOperands;
16989   SrcReg = MI->getOperand(CurOp++).getReg();
16990
16991   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16992   MVT::SimpleValueType VT = *RC->vt_begin();
16993   unsigned t1 = MRI.createVirtualRegister(RC);
16994   unsigned t2 = MRI.createVirtualRegister(RC);
16995   unsigned t3 = MRI.createVirtualRegister(RC);
16996   unsigned t4 = MRI.createVirtualRegister(RC);
16997   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
16998
16999   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
17000   unsigned LOADOpc = getLoadOpcode(VT);
17001
17002   // For the atomic load-arith operator, we generate
17003   //
17004   //  thisMBB:
17005   //    t1 = LOAD [MI.addr]
17006   //  mainMBB:
17007   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
17008   //    t1 = OP MI.val, EAX
17009   //    EAX = t4
17010   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
17011   //    t3 = EAX
17012   //    JNE mainMBB
17013   //  sinkMBB:
17014   //    dst = t3
17015
17016   MachineBasicBlock *thisMBB = MBB;
17017   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17018   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17019   MF->insert(I, mainMBB);
17020   MF->insert(I, sinkMBB);
17021
17022   MachineInstrBuilder MIB;
17023
17024   // Transfer the remainder of BB and its successor edges to sinkMBB.
17025   sinkMBB->splice(sinkMBB->begin(), MBB,
17026                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17027   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17028
17029   // thisMBB:
17030   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
17031   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17032     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17033     if (NewMO.isReg())
17034       NewMO.setIsKill(false);
17035     MIB.addOperand(NewMO);
17036   }
17037   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17038     unsigned flags = (*MMOI)->getFlags();
17039     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17040     MachineMemOperand *MMO =
17041       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17042                                (*MMOI)->getSize(),
17043                                (*MMOI)->getBaseAlignment(),
17044                                (*MMOI)->getTBAAInfo(),
17045                                (*MMOI)->getRanges());
17046     MIB.addMemOperand(MMO);
17047   }
17048
17049   thisMBB->addSuccessor(mainMBB);
17050
17051   // mainMBB:
17052   MachineBasicBlock *origMainMBB = mainMBB;
17053
17054   // Add a PHI.
17055   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
17056                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17057
17058   unsigned Opc = MI->getOpcode();
17059   switch (Opc) {
17060   default:
17061     llvm_unreachable("Unhandled atomic-load-op opcode!");
17062   case X86::ATOMAND8:
17063   case X86::ATOMAND16:
17064   case X86::ATOMAND32:
17065   case X86::ATOMAND64:
17066   case X86::ATOMOR8:
17067   case X86::ATOMOR16:
17068   case X86::ATOMOR32:
17069   case X86::ATOMOR64:
17070   case X86::ATOMXOR8:
17071   case X86::ATOMXOR16:
17072   case X86::ATOMXOR32:
17073   case X86::ATOMXOR64: {
17074     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
17075     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
17076       .addReg(t4);
17077     break;
17078   }
17079   case X86::ATOMNAND8:
17080   case X86::ATOMNAND16:
17081   case X86::ATOMNAND32:
17082   case X86::ATOMNAND64: {
17083     unsigned Tmp = MRI.createVirtualRegister(RC);
17084     unsigned NOTOpc;
17085     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
17086     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
17087       .addReg(t4);
17088     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
17089     break;
17090   }
17091   case X86::ATOMMAX8:
17092   case X86::ATOMMAX16:
17093   case X86::ATOMMAX32:
17094   case X86::ATOMMAX64:
17095   case X86::ATOMMIN8:
17096   case X86::ATOMMIN16:
17097   case X86::ATOMMIN32:
17098   case X86::ATOMMIN64:
17099   case X86::ATOMUMAX8:
17100   case X86::ATOMUMAX16:
17101   case X86::ATOMUMAX32:
17102   case X86::ATOMUMAX64:
17103   case X86::ATOMUMIN8:
17104   case X86::ATOMUMIN16:
17105   case X86::ATOMUMIN32:
17106   case X86::ATOMUMIN64: {
17107     unsigned CMPOpc;
17108     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
17109
17110     BuildMI(mainMBB, DL, TII->get(CMPOpc))
17111       .addReg(SrcReg)
17112       .addReg(t4);
17113
17114     if (Subtarget->hasCMov()) {
17115       if (VT != MVT::i8) {
17116         // Native support
17117         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
17118           .addReg(SrcReg)
17119           .addReg(t4);
17120       } else {
17121         // Promote i8 to i32 to use CMOV32
17122         const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
17123         const TargetRegisterClass *RC32 =
17124           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
17125         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
17126         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
17127         unsigned Tmp = MRI.createVirtualRegister(RC32);
17128
17129         unsigned Undef = MRI.createVirtualRegister(RC32);
17130         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
17131
17132         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
17133           .addReg(Undef)
17134           .addReg(SrcReg)
17135           .addImm(X86::sub_8bit);
17136         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
17137           .addReg(Undef)
17138           .addReg(t4)
17139           .addImm(X86::sub_8bit);
17140
17141         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
17142           .addReg(SrcReg32)
17143           .addReg(AccReg32);
17144
17145         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
17146           .addReg(Tmp, 0, X86::sub_8bit);
17147       }
17148     } else {
17149       // Use pseudo select and lower them.
17150       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
17151              "Invalid atomic-load-op transformation!");
17152       unsigned SelOpc = getPseudoCMOVOpc(VT);
17153       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
17154       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
17155       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
17156               .addReg(SrcReg).addReg(t4)
17157               .addImm(CC);
17158       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17159       // Replace the original PHI node as mainMBB is changed after CMOV
17160       // lowering.
17161       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
17162         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17163       Phi->eraseFromParent();
17164     }
17165     break;
17166   }
17167   }
17168
17169   // Copy PhyReg back from virtual register.
17170   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
17171     .addReg(t4);
17172
17173   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17174   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17175     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17176     if (NewMO.isReg())
17177       NewMO.setIsKill(false);
17178     MIB.addOperand(NewMO);
17179   }
17180   MIB.addReg(t2);
17181   MIB.setMemRefs(MMOBegin, MMOEnd);
17182
17183   // Copy PhyReg back to virtual register.
17184   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
17185     .addReg(PhyReg);
17186
17187   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17188
17189   mainMBB->addSuccessor(origMainMBB);
17190   mainMBB->addSuccessor(sinkMBB);
17191
17192   // sinkMBB:
17193   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17194           TII->get(TargetOpcode::COPY), DstReg)
17195     .addReg(t3);
17196
17197   MI->eraseFromParent();
17198   return sinkMBB;
17199 }
17200
17201 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
17202 // instructions. They will be translated into a spin-loop or compare-exchange
17203 // loop from
17204 //
17205 //    ...
17206 //    dst = atomic-fetch-op MI.addr, MI.val
17207 //    ...
17208 //
17209 // to
17210 //
17211 //    ...
17212 //    t1L = LOAD [MI.addr + 0]
17213 //    t1H = LOAD [MI.addr + 4]
17214 // loop:
17215 //    t4L = phi(t1L, t3L / loop)
17216 //    t4H = phi(t1H, t3H / loop)
17217 //    t2L = OP MI.val.lo, t4L
17218 //    t2H = OP MI.val.hi, t4H
17219 //    EAX = t4L
17220 //    EDX = t4H
17221 //    EBX = t2L
17222 //    ECX = t2H
17223 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17224 //    t3L = EAX
17225 //    t3H = EDX
17226 //    JNE loop
17227 // sink:
17228 //    dstL = t3L
17229 //    dstH = t3H
17230 //    ...
17231 MachineBasicBlock *
17232 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
17233                                            MachineBasicBlock *MBB) const {
17234   MachineFunction *MF = MBB->getParent();
17235   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17236   DebugLoc DL = MI->getDebugLoc();
17237
17238   MachineRegisterInfo &MRI = MF->getRegInfo();
17239
17240   const BasicBlock *BB = MBB->getBasicBlock();
17241   MachineFunction::iterator I = MBB;
17242   ++I;
17243
17244   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
17245          "Unexpected number of operands");
17246
17247   assert(MI->hasOneMemOperand() &&
17248          "Expected atomic-load-op32 to have one memoperand");
17249
17250   // Memory Reference
17251   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17252   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17253
17254   unsigned DstLoReg, DstHiReg;
17255   unsigned SrcLoReg, SrcHiReg;
17256   unsigned MemOpndSlot;
17257
17258   unsigned CurOp = 0;
17259
17260   DstLoReg = MI->getOperand(CurOp++).getReg();
17261   DstHiReg = MI->getOperand(CurOp++).getReg();
17262   MemOpndSlot = CurOp;
17263   CurOp += X86::AddrNumOperands;
17264   SrcLoReg = MI->getOperand(CurOp++).getReg();
17265   SrcHiReg = MI->getOperand(CurOp++).getReg();
17266
17267   const TargetRegisterClass *RC = &X86::GR32RegClass;
17268   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
17269
17270   unsigned t1L = MRI.createVirtualRegister(RC);
17271   unsigned t1H = MRI.createVirtualRegister(RC);
17272   unsigned t2L = MRI.createVirtualRegister(RC);
17273   unsigned t2H = MRI.createVirtualRegister(RC);
17274   unsigned t3L = MRI.createVirtualRegister(RC);
17275   unsigned t3H = MRI.createVirtualRegister(RC);
17276   unsigned t4L = MRI.createVirtualRegister(RC);
17277   unsigned t4H = MRI.createVirtualRegister(RC);
17278
17279   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
17280   unsigned LOADOpc = X86::MOV32rm;
17281
17282   // For the atomic load-arith operator, we generate
17283   //
17284   //  thisMBB:
17285   //    t1L = LOAD [MI.addr + 0]
17286   //    t1H = LOAD [MI.addr + 4]
17287   //  mainMBB:
17288   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
17289   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
17290   //    t2L = OP MI.val.lo, t4L
17291   //    t2H = OP MI.val.hi, t4H
17292   //    EBX = t2L
17293   //    ECX = t2H
17294   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17295   //    t3L = EAX
17296   //    t3H = EDX
17297   //    JNE loop
17298   //  sinkMBB:
17299   //    dstL = t3L
17300   //    dstH = t3H
17301
17302   MachineBasicBlock *thisMBB = MBB;
17303   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17304   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17305   MF->insert(I, mainMBB);
17306   MF->insert(I, sinkMBB);
17307
17308   MachineInstrBuilder MIB;
17309
17310   // Transfer the remainder of BB and its successor edges to sinkMBB.
17311   sinkMBB->splice(sinkMBB->begin(), MBB,
17312                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17313   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17314
17315   // thisMBB:
17316   // Lo
17317   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
17318   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17319     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17320     if (NewMO.isReg())
17321       NewMO.setIsKill(false);
17322     MIB.addOperand(NewMO);
17323   }
17324   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17325     unsigned flags = (*MMOI)->getFlags();
17326     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17327     MachineMemOperand *MMO =
17328       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17329                                (*MMOI)->getSize(),
17330                                (*MMOI)->getBaseAlignment(),
17331                                (*MMOI)->getTBAAInfo(),
17332                                (*MMOI)->getRanges());
17333     MIB.addMemOperand(MMO);
17334   };
17335   MachineInstr *LowMI = MIB;
17336
17337   // Hi
17338   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
17339   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17340     if (i == X86::AddrDisp) {
17341       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
17342     } else {
17343       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17344       if (NewMO.isReg())
17345         NewMO.setIsKill(false);
17346       MIB.addOperand(NewMO);
17347     }
17348   }
17349   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
17350
17351   thisMBB->addSuccessor(mainMBB);
17352
17353   // mainMBB:
17354   MachineBasicBlock *origMainMBB = mainMBB;
17355
17356   // Add PHIs.
17357   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
17358                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17359   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
17360                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17361
17362   unsigned Opc = MI->getOpcode();
17363   switch (Opc) {
17364   default:
17365     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
17366   case X86::ATOMAND6432:
17367   case X86::ATOMOR6432:
17368   case X86::ATOMXOR6432:
17369   case X86::ATOMADD6432:
17370   case X86::ATOMSUB6432: {
17371     unsigned HiOpc;
17372     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17373     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
17374       .addReg(SrcLoReg);
17375     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
17376       .addReg(SrcHiReg);
17377     break;
17378   }
17379   case X86::ATOMNAND6432: {
17380     unsigned HiOpc, NOTOpc;
17381     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
17382     unsigned TmpL = MRI.createVirtualRegister(RC);
17383     unsigned TmpH = MRI.createVirtualRegister(RC);
17384     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
17385       .addReg(t4L);
17386     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
17387       .addReg(t4H);
17388     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
17389     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
17390     break;
17391   }
17392   case X86::ATOMMAX6432:
17393   case X86::ATOMMIN6432:
17394   case X86::ATOMUMAX6432:
17395   case X86::ATOMUMIN6432: {
17396     unsigned HiOpc;
17397     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17398     unsigned cL = MRI.createVirtualRegister(RC8);
17399     unsigned cH = MRI.createVirtualRegister(RC8);
17400     unsigned cL32 = MRI.createVirtualRegister(RC);
17401     unsigned cH32 = MRI.createVirtualRegister(RC);
17402     unsigned cc = MRI.createVirtualRegister(RC);
17403     // cl := cmp src_lo, lo
17404     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17405       .addReg(SrcLoReg).addReg(t4L);
17406     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
17407     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
17408     // ch := cmp src_hi, hi
17409     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17410       .addReg(SrcHiReg).addReg(t4H);
17411     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
17412     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
17413     // cc := if (src_hi == hi) ? cl : ch;
17414     if (Subtarget->hasCMov()) {
17415       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
17416         .addReg(cH32).addReg(cL32);
17417     } else {
17418       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
17419               .addReg(cH32).addReg(cL32)
17420               .addImm(X86::COND_E);
17421       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17422     }
17423     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
17424     if (Subtarget->hasCMov()) {
17425       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
17426         .addReg(SrcLoReg).addReg(t4L);
17427       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
17428         .addReg(SrcHiReg).addReg(t4H);
17429     } else {
17430       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
17431               .addReg(SrcLoReg).addReg(t4L)
17432               .addImm(X86::COND_NE);
17433       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17434       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
17435       // 2nd CMOV lowering.
17436       mainMBB->addLiveIn(X86::EFLAGS);
17437       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
17438               .addReg(SrcHiReg).addReg(t4H)
17439               .addImm(X86::COND_NE);
17440       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17441       // Replace the original PHI node as mainMBB is changed after CMOV
17442       // lowering.
17443       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
17444         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17445       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
17446         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17447       PhiL->eraseFromParent();
17448       PhiH->eraseFromParent();
17449     }
17450     break;
17451   }
17452   case X86::ATOMSWAP6432: {
17453     unsigned HiOpc;
17454     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17455     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
17456     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
17457     break;
17458   }
17459   }
17460
17461   // Copy EDX:EAX back from HiReg:LoReg
17462   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
17463   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
17464   // Copy ECX:EBX from t1H:t1L
17465   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
17466   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
17467
17468   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17469   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17470     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17471     if (NewMO.isReg())
17472       NewMO.setIsKill(false);
17473     MIB.addOperand(NewMO);
17474   }
17475   MIB.setMemRefs(MMOBegin, MMOEnd);
17476
17477   // Copy EDX:EAX back to t3H:t3L
17478   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
17479   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
17480
17481   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17482
17483   mainMBB->addSuccessor(origMainMBB);
17484   mainMBB->addSuccessor(sinkMBB);
17485
17486   // sinkMBB:
17487   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17488           TII->get(TargetOpcode::COPY), DstLoReg)
17489     .addReg(t3L);
17490   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17491           TII->get(TargetOpcode::COPY), DstHiReg)
17492     .addReg(t3H);
17493
17494   MI->eraseFromParent();
17495   return sinkMBB;
17496 }
17497
17498 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17499 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17500 // in the .td file.
17501 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17502                                        const TargetInstrInfo *TII) {
17503   unsigned Opc;
17504   switch (MI->getOpcode()) {
17505   default: llvm_unreachable("illegal opcode!");
17506   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17507   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17508   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17509   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17510   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17511   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17512   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17513   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17514   }
17515
17516   DebugLoc dl = MI->getDebugLoc();
17517   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17518
17519   unsigned NumArgs = MI->getNumOperands();
17520   for (unsigned i = 1; i < NumArgs; ++i) {
17521     MachineOperand &Op = MI->getOperand(i);
17522     if (!(Op.isReg() && Op.isImplicit()))
17523       MIB.addOperand(Op);
17524   }
17525   if (MI->hasOneMemOperand())
17526     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17527
17528   BuildMI(*BB, MI, dl,
17529     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17530     .addReg(X86::XMM0);
17531
17532   MI->eraseFromParent();
17533   return BB;
17534 }
17535
17536 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17537 // defs in an instruction pattern
17538 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17539                                        const TargetInstrInfo *TII) {
17540   unsigned Opc;
17541   switch (MI->getOpcode()) {
17542   default: llvm_unreachable("illegal opcode!");
17543   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17544   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17545   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17546   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17547   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17548   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17549   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17550   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17551   }
17552
17553   DebugLoc dl = MI->getDebugLoc();
17554   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17555
17556   unsigned NumArgs = MI->getNumOperands(); // remove the results
17557   for (unsigned i = 1; i < NumArgs; ++i) {
17558     MachineOperand &Op = MI->getOperand(i);
17559     if (!(Op.isReg() && Op.isImplicit()))
17560       MIB.addOperand(Op);
17561   }
17562   if (MI->hasOneMemOperand())
17563     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17564
17565   BuildMI(*BB, MI, dl,
17566     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17567     .addReg(X86::ECX);
17568
17569   MI->eraseFromParent();
17570   return BB;
17571 }
17572
17573 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17574                                        const TargetInstrInfo *TII,
17575                                        const X86Subtarget* Subtarget) {
17576   DebugLoc dl = MI->getDebugLoc();
17577
17578   // Address into RAX/EAX, other two args into ECX, EDX.
17579   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17580   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17581   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17582   for (int i = 0; i < X86::AddrNumOperands; ++i)
17583     MIB.addOperand(MI->getOperand(i));
17584
17585   unsigned ValOps = X86::AddrNumOperands;
17586   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17587     .addReg(MI->getOperand(ValOps).getReg());
17588   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17589     .addReg(MI->getOperand(ValOps+1).getReg());
17590
17591   // The instruction doesn't actually take any operands though.
17592   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17593
17594   MI->eraseFromParent(); // The pseudo is gone now.
17595   return BB;
17596 }
17597
17598 MachineBasicBlock *
17599 X86TargetLowering::EmitVAARG64WithCustomInserter(
17600                    MachineInstr *MI,
17601                    MachineBasicBlock *MBB) const {
17602   // Emit va_arg instruction on X86-64.
17603
17604   // Operands to this pseudo-instruction:
17605   // 0  ) Output        : destination address (reg)
17606   // 1-5) Input         : va_list address (addr, i64mem)
17607   // 6  ) ArgSize       : Size (in bytes) of vararg type
17608   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17609   // 8  ) Align         : Alignment of type
17610   // 9  ) EFLAGS (implicit-def)
17611
17612   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17613   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17614
17615   unsigned DestReg = MI->getOperand(0).getReg();
17616   MachineOperand &Base = MI->getOperand(1);
17617   MachineOperand &Scale = MI->getOperand(2);
17618   MachineOperand &Index = MI->getOperand(3);
17619   MachineOperand &Disp = MI->getOperand(4);
17620   MachineOperand &Segment = MI->getOperand(5);
17621   unsigned ArgSize = MI->getOperand(6).getImm();
17622   unsigned ArgMode = MI->getOperand(7).getImm();
17623   unsigned Align = MI->getOperand(8).getImm();
17624
17625   // Memory Reference
17626   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17627   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17628   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17629
17630   // Machine Information
17631   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17632   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17633   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17634   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17635   DebugLoc DL = MI->getDebugLoc();
17636
17637   // struct va_list {
17638   //   i32   gp_offset
17639   //   i32   fp_offset
17640   //   i64   overflow_area (address)
17641   //   i64   reg_save_area (address)
17642   // }
17643   // sizeof(va_list) = 24
17644   // alignment(va_list) = 8
17645
17646   unsigned TotalNumIntRegs = 6;
17647   unsigned TotalNumXMMRegs = 8;
17648   bool UseGPOffset = (ArgMode == 1);
17649   bool UseFPOffset = (ArgMode == 2);
17650   unsigned MaxOffset = TotalNumIntRegs * 8 +
17651                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17652
17653   /* Align ArgSize to a multiple of 8 */
17654   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17655   bool NeedsAlign = (Align > 8);
17656
17657   MachineBasicBlock *thisMBB = MBB;
17658   MachineBasicBlock *overflowMBB;
17659   MachineBasicBlock *offsetMBB;
17660   MachineBasicBlock *endMBB;
17661
17662   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17663   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17664   unsigned OffsetReg = 0;
17665
17666   if (!UseGPOffset && !UseFPOffset) {
17667     // If we only pull from the overflow region, we don't create a branch.
17668     // We don't need to alter control flow.
17669     OffsetDestReg = 0; // unused
17670     OverflowDestReg = DestReg;
17671
17672     offsetMBB = nullptr;
17673     overflowMBB = thisMBB;
17674     endMBB = thisMBB;
17675   } else {
17676     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17677     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17678     // If not, pull from overflow_area. (branch to overflowMBB)
17679     //
17680     //       thisMBB
17681     //         |     .
17682     //         |        .
17683     //     offsetMBB   overflowMBB
17684     //         |        .
17685     //         |     .
17686     //        endMBB
17687
17688     // Registers for the PHI in endMBB
17689     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17690     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17691
17692     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17693     MachineFunction *MF = MBB->getParent();
17694     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17695     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17696     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17697
17698     MachineFunction::iterator MBBIter = MBB;
17699     ++MBBIter;
17700
17701     // Insert the new basic blocks
17702     MF->insert(MBBIter, offsetMBB);
17703     MF->insert(MBBIter, overflowMBB);
17704     MF->insert(MBBIter, endMBB);
17705
17706     // Transfer the remainder of MBB and its successor edges to endMBB.
17707     endMBB->splice(endMBB->begin(), thisMBB,
17708                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17709     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17710
17711     // Make offsetMBB and overflowMBB successors of thisMBB
17712     thisMBB->addSuccessor(offsetMBB);
17713     thisMBB->addSuccessor(overflowMBB);
17714
17715     // endMBB is a successor of both offsetMBB and overflowMBB
17716     offsetMBB->addSuccessor(endMBB);
17717     overflowMBB->addSuccessor(endMBB);
17718
17719     // Load the offset value into a register
17720     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17721     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17722       .addOperand(Base)
17723       .addOperand(Scale)
17724       .addOperand(Index)
17725       .addDisp(Disp, UseFPOffset ? 4 : 0)
17726       .addOperand(Segment)
17727       .setMemRefs(MMOBegin, MMOEnd);
17728
17729     // Check if there is enough room left to pull this argument.
17730     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17731       .addReg(OffsetReg)
17732       .addImm(MaxOffset + 8 - ArgSizeA8);
17733
17734     // Branch to "overflowMBB" if offset >= max
17735     // Fall through to "offsetMBB" otherwise
17736     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17737       .addMBB(overflowMBB);
17738   }
17739
17740   // In offsetMBB, emit code to use the reg_save_area.
17741   if (offsetMBB) {
17742     assert(OffsetReg != 0);
17743
17744     // Read the reg_save_area address.
17745     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17746     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17747       .addOperand(Base)
17748       .addOperand(Scale)
17749       .addOperand(Index)
17750       .addDisp(Disp, 16)
17751       .addOperand(Segment)
17752       .setMemRefs(MMOBegin, MMOEnd);
17753
17754     // Zero-extend the offset
17755     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17756       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17757         .addImm(0)
17758         .addReg(OffsetReg)
17759         .addImm(X86::sub_32bit);
17760
17761     // Add the offset to the reg_save_area to get the final address.
17762     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17763       .addReg(OffsetReg64)
17764       .addReg(RegSaveReg);
17765
17766     // Compute the offset for the next argument
17767     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17768     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17769       .addReg(OffsetReg)
17770       .addImm(UseFPOffset ? 16 : 8);
17771
17772     // Store it back into the va_list.
17773     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17774       .addOperand(Base)
17775       .addOperand(Scale)
17776       .addOperand(Index)
17777       .addDisp(Disp, UseFPOffset ? 4 : 0)
17778       .addOperand(Segment)
17779       .addReg(NextOffsetReg)
17780       .setMemRefs(MMOBegin, MMOEnd);
17781
17782     // Jump to endMBB
17783     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17784       .addMBB(endMBB);
17785   }
17786
17787   //
17788   // Emit code to use overflow area
17789   //
17790
17791   // Load the overflow_area address into a register.
17792   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17793   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17794     .addOperand(Base)
17795     .addOperand(Scale)
17796     .addOperand(Index)
17797     .addDisp(Disp, 8)
17798     .addOperand(Segment)
17799     .setMemRefs(MMOBegin, MMOEnd);
17800
17801   // If we need to align it, do so. Otherwise, just copy the address
17802   // to OverflowDestReg.
17803   if (NeedsAlign) {
17804     // Align the overflow address
17805     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17806     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17807
17808     // aligned_addr = (addr + (align-1)) & ~(align-1)
17809     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17810       .addReg(OverflowAddrReg)
17811       .addImm(Align-1);
17812
17813     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17814       .addReg(TmpReg)
17815       .addImm(~(uint64_t)(Align-1));
17816   } else {
17817     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17818       .addReg(OverflowAddrReg);
17819   }
17820
17821   // Compute the next overflow address after this argument.
17822   // (the overflow address should be kept 8-byte aligned)
17823   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17824   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17825     .addReg(OverflowDestReg)
17826     .addImm(ArgSizeA8);
17827
17828   // Store the new overflow address.
17829   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17830     .addOperand(Base)
17831     .addOperand(Scale)
17832     .addOperand(Index)
17833     .addDisp(Disp, 8)
17834     .addOperand(Segment)
17835     .addReg(NextAddrReg)
17836     .setMemRefs(MMOBegin, MMOEnd);
17837
17838   // If we branched, emit the PHI to the front of endMBB.
17839   if (offsetMBB) {
17840     BuildMI(*endMBB, endMBB->begin(), DL,
17841             TII->get(X86::PHI), DestReg)
17842       .addReg(OffsetDestReg).addMBB(offsetMBB)
17843       .addReg(OverflowDestReg).addMBB(overflowMBB);
17844   }
17845
17846   // Erase the pseudo instruction
17847   MI->eraseFromParent();
17848
17849   return endMBB;
17850 }
17851
17852 MachineBasicBlock *
17853 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17854                                                  MachineInstr *MI,
17855                                                  MachineBasicBlock *MBB) const {
17856   // Emit code to save XMM registers to the stack. The ABI says that the
17857   // number of registers to save is given in %al, so it's theoretically
17858   // possible to do an indirect jump trick to avoid saving all of them,
17859   // however this code takes a simpler approach and just executes all
17860   // of the stores if %al is non-zero. It's less code, and it's probably
17861   // easier on the hardware branch predictor, and stores aren't all that
17862   // expensive anyway.
17863
17864   // Create the new basic blocks. One block contains all the XMM stores,
17865   // and one block is the final destination regardless of whether any
17866   // stores were performed.
17867   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17868   MachineFunction *F = MBB->getParent();
17869   MachineFunction::iterator MBBIter = MBB;
17870   ++MBBIter;
17871   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17872   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17873   F->insert(MBBIter, XMMSaveMBB);
17874   F->insert(MBBIter, EndMBB);
17875
17876   // Transfer the remainder of MBB and its successor edges to EndMBB.
17877   EndMBB->splice(EndMBB->begin(), MBB,
17878                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17879   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17880
17881   // The original block will now fall through to the XMM save block.
17882   MBB->addSuccessor(XMMSaveMBB);
17883   // The XMMSaveMBB will fall through to the end block.
17884   XMMSaveMBB->addSuccessor(EndMBB);
17885
17886   // Now add the instructions.
17887   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17888   DebugLoc DL = MI->getDebugLoc();
17889
17890   unsigned CountReg = MI->getOperand(0).getReg();
17891   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17892   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17893
17894   if (!Subtarget->isTargetWin64()) {
17895     // If %al is 0, branch around the XMM save block.
17896     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17897     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17898     MBB->addSuccessor(EndMBB);
17899   }
17900
17901   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17902   // that was just emitted, but clearly shouldn't be "saved".
17903   assert((MI->getNumOperands() <= 3 ||
17904           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17905           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17906          && "Expected last argument to be EFLAGS");
17907   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17908   // In the XMM save block, save all the XMM argument registers.
17909   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17910     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17911     MachineMemOperand *MMO =
17912       F->getMachineMemOperand(
17913           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17914         MachineMemOperand::MOStore,
17915         /*Size=*/16, /*Align=*/16);
17916     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17917       .addFrameIndex(RegSaveFrameIndex)
17918       .addImm(/*Scale=*/1)
17919       .addReg(/*IndexReg=*/0)
17920       .addImm(/*Disp=*/Offset)
17921       .addReg(/*Segment=*/0)
17922       .addReg(MI->getOperand(i).getReg())
17923       .addMemOperand(MMO);
17924   }
17925
17926   MI->eraseFromParent();   // The pseudo instruction is gone now.
17927
17928   return EndMBB;
17929 }
17930
17931 // The EFLAGS operand of SelectItr might be missing a kill marker
17932 // because there were multiple uses of EFLAGS, and ISel didn't know
17933 // which to mark. Figure out whether SelectItr should have had a
17934 // kill marker, and set it if it should. Returns the correct kill
17935 // marker value.
17936 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17937                                      MachineBasicBlock* BB,
17938                                      const TargetRegisterInfo* TRI) {
17939   // Scan forward through BB for a use/def of EFLAGS.
17940   MachineBasicBlock::iterator miI(std::next(SelectItr));
17941   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17942     const MachineInstr& mi = *miI;
17943     if (mi.readsRegister(X86::EFLAGS))
17944       return false;
17945     if (mi.definesRegister(X86::EFLAGS))
17946       break; // Should have kill-flag - update below.
17947   }
17948
17949   // If we hit the end of the block, check whether EFLAGS is live into a
17950   // successor.
17951   if (miI == BB->end()) {
17952     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17953                                           sEnd = BB->succ_end();
17954          sItr != sEnd; ++sItr) {
17955       MachineBasicBlock* succ = *sItr;
17956       if (succ->isLiveIn(X86::EFLAGS))
17957         return false;
17958     }
17959   }
17960
17961   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17962   // out. SelectMI should have a kill flag on EFLAGS.
17963   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17964   return true;
17965 }
17966
17967 MachineBasicBlock *
17968 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17969                                      MachineBasicBlock *BB) const {
17970   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17971   DebugLoc DL = MI->getDebugLoc();
17972
17973   // To "insert" a SELECT_CC instruction, we actually have to insert the
17974   // diamond control-flow pattern.  The incoming instruction knows the
17975   // destination vreg to set, the condition code register to branch on, the
17976   // true/false values to select between, and a branch opcode to use.
17977   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17978   MachineFunction::iterator It = BB;
17979   ++It;
17980
17981   //  thisMBB:
17982   //  ...
17983   //   TrueVal = ...
17984   //   cmpTY ccX, r1, r2
17985   //   bCC copy1MBB
17986   //   fallthrough --> copy0MBB
17987   MachineBasicBlock *thisMBB = BB;
17988   MachineFunction *F = BB->getParent();
17989   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17990   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17991   F->insert(It, copy0MBB);
17992   F->insert(It, sinkMBB);
17993
17994   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17995   // live into the sink and copy blocks.
17996   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17997   if (!MI->killsRegister(X86::EFLAGS) &&
17998       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17999     copy0MBB->addLiveIn(X86::EFLAGS);
18000     sinkMBB->addLiveIn(X86::EFLAGS);
18001   }
18002
18003   // Transfer the remainder of BB and its successor edges to sinkMBB.
18004   sinkMBB->splice(sinkMBB->begin(), BB,
18005                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18006   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18007
18008   // Add the true and fallthrough blocks as its successors.
18009   BB->addSuccessor(copy0MBB);
18010   BB->addSuccessor(sinkMBB);
18011
18012   // Create the conditional branch instruction.
18013   unsigned Opc =
18014     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18015   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18016
18017   //  copy0MBB:
18018   //   %FalseValue = ...
18019   //   # fallthrough to sinkMBB
18020   copy0MBB->addSuccessor(sinkMBB);
18021
18022   //  sinkMBB:
18023   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18024   //  ...
18025   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18026           TII->get(X86::PHI), MI->getOperand(0).getReg())
18027     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18028     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18029
18030   MI->eraseFromParent();   // The pseudo instruction is gone now.
18031   return sinkMBB;
18032 }
18033
18034 MachineBasicBlock *
18035 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18036                                         bool Is64Bit) const {
18037   MachineFunction *MF = BB->getParent();
18038   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18039   DebugLoc DL = MI->getDebugLoc();
18040   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18041
18042   assert(MF->shouldSplitStack());
18043
18044   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18045   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18046
18047   // BB:
18048   //  ... [Till the alloca]
18049   // If stacklet is not large enough, jump to mallocMBB
18050   //
18051   // bumpMBB:
18052   //  Allocate by subtracting from RSP
18053   //  Jump to continueMBB
18054   //
18055   // mallocMBB:
18056   //  Allocate by call to runtime
18057   //
18058   // continueMBB:
18059   //  ...
18060   //  [rest of original BB]
18061   //
18062
18063   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18064   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18065   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18066
18067   MachineRegisterInfo &MRI = MF->getRegInfo();
18068   const TargetRegisterClass *AddrRegClass =
18069     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18070
18071   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18072     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18073     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18074     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18075     sizeVReg = MI->getOperand(1).getReg(),
18076     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18077
18078   MachineFunction::iterator MBBIter = BB;
18079   ++MBBIter;
18080
18081   MF->insert(MBBIter, bumpMBB);
18082   MF->insert(MBBIter, mallocMBB);
18083   MF->insert(MBBIter, continueMBB);
18084
18085   continueMBB->splice(continueMBB->begin(), BB,
18086                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18087   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18088
18089   // Add code to the main basic block to check if the stack limit has been hit,
18090   // and if so, jump to mallocMBB otherwise to bumpMBB.
18091   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18092   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18093     .addReg(tmpSPVReg).addReg(sizeVReg);
18094   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18095     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18096     .addReg(SPLimitVReg);
18097   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18098
18099   // bumpMBB simply decreases the stack pointer, since we know the current
18100   // stacklet has enough space.
18101   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18102     .addReg(SPLimitVReg);
18103   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18104     .addReg(SPLimitVReg);
18105   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18106
18107   // Calls into a routine in libgcc to allocate more space from the heap.
18108   const uint32_t *RegMask =
18109     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18110   if (Is64Bit) {
18111     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18112       .addReg(sizeVReg);
18113     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18114       .addExternalSymbol("__morestack_allocate_stack_space")
18115       .addRegMask(RegMask)
18116       .addReg(X86::RDI, RegState::Implicit)
18117       .addReg(X86::RAX, RegState::ImplicitDefine);
18118   } else {
18119     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18120       .addImm(12);
18121     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18122     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18123       .addExternalSymbol("__morestack_allocate_stack_space")
18124       .addRegMask(RegMask)
18125       .addReg(X86::EAX, RegState::ImplicitDefine);
18126   }
18127
18128   if (!Is64Bit)
18129     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18130       .addImm(16);
18131
18132   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18133     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18134   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18135
18136   // Set up the CFG correctly.
18137   BB->addSuccessor(bumpMBB);
18138   BB->addSuccessor(mallocMBB);
18139   mallocMBB->addSuccessor(continueMBB);
18140   bumpMBB->addSuccessor(continueMBB);
18141
18142   // Take care of the PHI nodes.
18143   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18144           MI->getOperand(0).getReg())
18145     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18146     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18147
18148   // Delete the original pseudo instruction.
18149   MI->eraseFromParent();
18150
18151   // And we're done.
18152   return continueMBB;
18153 }
18154
18155 MachineBasicBlock *
18156 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18157                                         MachineBasicBlock *BB) const {
18158   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18159   DebugLoc DL = MI->getDebugLoc();
18160
18161   assert(!Subtarget->isTargetMacho());
18162
18163   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18164   // non-trivial part is impdef of ESP.
18165
18166   if (Subtarget->isTargetWin64()) {
18167     if (Subtarget->isTargetCygMing()) {
18168       // ___chkstk(Mingw64):
18169       // Clobbers R10, R11, RAX and EFLAGS.
18170       // Updates RSP.
18171       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18172         .addExternalSymbol("___chkstk")
18173         .addReg(X86::RAX, RegState::Implicit)
18174         .addReg(X86::RSP, RegState::Implicit)
18175         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18176         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18177         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18178     } else {
18179       // __chkstk(MSVCRT): does not update stack pointer.
18180       // Clobbers R10, R11 and EFLAGS.
18181       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18182         .addExternalSymbol("__chkstk")
18183         .addReg(X86::RAX, RegState::Implicit)
18184         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18185       // RAX has the offset to be subtracted from RSP.
18186       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18187         .addReg(X86::RSP)
18188         .addReg(X86::RAX);
18189     }
18190   } else {
18191     const char *StackProbeSymbol =
18192       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18193
18194     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18195       .addExternalSymbol(StackProbeSymbol)
18196       .addReg(X86::EAX, RegState::Implicit)
18197       .addReg(X86::ESP, RegState::Implicit)
18198       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18199       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18200       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18201   }
18202
18203   MI->eraseFromParent();   // The pseudo instruction is gone now.
18204   return BB;
18205 }
18206
18207 MachineBasicBlock *
18208 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18209                                       MachineBasicBlock *BB) const {
18210   // This is pretty easy.  We're taking the value that we received from
18211   // our load from the relocation, sticking it in either RDI (x86-64)
18212   // or EAX and doing an indirect call.  The return value will then
18213   // be in the normal return register.
18214   MachineFunction *F = BB->getParent();
18215   const X86InstrInfo *TII
18216     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
18217   DebugLoc DL = MI->getDebugLoc();
18218
18219   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18220   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18221
18222   // Get a register mask for the lowered call.
18223   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18224   // proper register mask.
18225   const uint32_t *RegMask =
18226     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18227   if (Subtarget->is64Bit()) {
18228     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18229                                       TII->get(X86::MOV64rm), X86::RDI)
18230     .addReg(X86::RIP)
18231     .addImm(0).addReg(0)
18232     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18233                       MI->getOperand(3).getTargetFlags())
18234     .addReg(0);
18235     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18236     addDirectMem(MIB, X86::RDI);
18237     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18238   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18239     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18240                                       TII->get(X86::MOV32rm), X86::EAX)
18241     .addReg(0)
18242     .addImm(0).addReg(0)
18243     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18244                       MI->getOperand(3).getTargetFlags())
18245     .addReg(0);
18246     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18247     addDirectMem(MIB, X86::EAX);
18248     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18249   } else {
18250     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18251                                       TII->get(X86::MOV32rm), X86::EAX)
18252     .addReg(TII->getGlobalBaseReg(F))
18253     .addImm(0).addReg(0)
18254     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18255                       MI->getOperand(3).getTargetFlags())
18256     .addReg(0);
18257     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18258     addDirectMem(MIB, X86::EAX);
18259     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18260   }
18261
18262   MI->eraseFromParent(); // The pseudo instruction is gone now.
18263   return BB;
18264 }
18265
18266 MachineBasicBlock *
18267 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18268                                     MachineBasicBlock *MBB) const {
18269   DebugLoc DL = MI->getDebugLoc();
18270   MachineFunction *MF = MBB->getParent();
18271   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18272   MachineRegisterInfo &MRI = MF->getRegInfo();
18273
18274   const BasicBlock *BB = MBB->getBasicBlock();
18275   MachineFunction::iterator I = MBB;
18276   ++I;
18277
18278   // Memory Reference
18279   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18280   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18281
18282   unsigned DstReg;
18283   unsigned MemOpndSlot = 0;
18284
18285   unsigned CurOp = 0;
18286
18287   DstReg = MI->getOperand(CurOp++).getReg();
18288   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18289   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18290   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18291   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18292
18293   MemOpndSlot = CurOp;
18294
18295   MVT PVT = getPointerTy();
18296   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18297          "Invalid Pointer Size!");
18298
18299   // For v = setjmp(buf), we generate
18300   //
18301   // thisMBB:
18302   //  buf[LabelOffset] = restoreMBB
18303   //  SjLjSetup restoreMBB
18304   //
18305   // mainMBB:
18306   //  v_main = 0
18307   //
18308   // sinkMBB:
18309   //  v = phi(main, restore)
18310   //
18311   // restoreMBB:
18312   //  v_restore = 1
18313
18314   MachineBasicBlock *thisMBB = MBB;
18315   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18316   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18317   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18318   MF->insert(I, mainMBB);
18319   MF->insert(I, sinkMBB);
18320   MF->push_back(restoreMBB);
18321
18322   MachineInstrBuilder MIB;
18323
18324   // Transfer the remainder of BB and its successor edges to sinkMBB.
18325   sinkMBB->splice(sinkMBB->begin(), MBB,
18326                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18327   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18328
18329   // thisMBB:
18330   unsigned PtrStoreOpc = 0;
18331   unsigned LabelReg = 0;
18332   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18333   Reloc::Model RM = MF->getTarget().getRelocationModel();
18334   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18335                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18336
18337   // Prepare IP either in reg or imm.
18338   if (!UseImmLabel) {
18339     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18340     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18341     LabelReg = MRI.createVirtualRegister(PtrRC);
18342     if (Subtarget->is64Bit()) {
18343       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18344               .addReg(X86::RIP)
18345               .addImm(0)
18346               .addReg(0)
18347               .addMBB(restoreMBB)
18348               .addReg(0);
18349     } else {
18350       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18351       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18352               .addReg(XII->getGlobalBaseReg(MF))
18353               .addImm(0)
18354               .addReg(0)
18355               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18356               .addReg(0);
18357     }
18358   } else
18359     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18360   // Store IP
18361   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18362   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18363     if (i == X86::AddrDisp)
18364       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18365     else
18366       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18367   }
18368   if (!UseImmLabel)
18369     MIB.addReg(LabelReg);
18370   else
18371     MIB.addMBB(restoreMBB);
18372   MIB.setMemRefs(MMOBegin, MMOEnd);
18373   // Setup
18374   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18375           .addMBB(restoreMBB);
18376
18377   const X86RegisterInfo *RegInfo =
18378     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18379   MIB.addRegMask(RegInfo->getNoPreservedMask());
18380   thisMBB->addSuccessor(mainMBB);
18381   thisMBB->addSuccessor(restoreMBB);
18382
18383   // mainMBB:
18384   //  EAX = 0
18385   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18386   mainMBB->addSuccessor(sinkMBB);
18387
18388   // sinkMBB:
18389   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18390           TII->get(X86::PHI), DstReg)
18391     .addReg(mainDstReg).addMBB(mainMBB)
18392     .addReg(restoreDstReg).addMBB(restoreMBB);
18393
18394   // restoreMBB:
18395   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18396   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18397   restoreMBB->addSuccessor(sinkMBB);
18398
18399   MI->eraseFromParent();
18400   return sinkMBB;
18401 }
18402
18403 MachineBasicBlock *
18404 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18405                                      MachineBasicBlock *MBB) const {
18406   DebugLoc DL = MI->getDebugLoc();
18407   MachineFunction *MF = MBB->getParent();
18408   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18409   MachineRegisterInfo &MRI = MF->getRegInfo();
18410
18411   // Memory Reference
18412   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18413   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18414
18415   MVT PVT = getPointerTy();
18416   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18417          "Invalid Pointer Size!");
18418
18419   const TargetRegisterClass *RC =
18420     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18421   unsigned Tmp = MRI.createVirtualRegister(RC);
18422   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18423   const X86RegisterInfo *RegInfo =
18424     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18425   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18426   unsigned SP = RegInfo->getStackRegister();
18427
18428   MachineInstrBuilder MIB;
18429
18430   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18431   const int64_t SPOffset = 2 * PVT.getStoreSize();
18432
18433   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18434   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18435
18436   // Reload FP
18437   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18438   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18439     MIB.addOperand(MI->getOperand(i));
18440   MIB.setMemRefs(MMOBegin, MMOEnd);
18441   // Reload IP
18442   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18443   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18444     if (i == X86::AddrDisp)
18445       MIB.addDisp(MI->getOperand(i), LabelOffset);
18446     else
18447       MIB.addOperand(MI->getOperand(i));
18448   }
18449   MIB.setMemRefs(MMOBegin, MMOEnd);
18450   // Reload SP
18451   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18452   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18453     if (i == X86::AddrDisp)
18454       MIB.addDisp(MI->getOperand(i), SPOffset);
18455     else
18456       MIB.addOperand(MI->getOperand(i));
18457   }
18458   MIB.setMemRefs(MMOBegin, MMOEnd);
18459   // Jump
18460   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18461
18462   MI->eraseFromParent();
18463   return MBB;
18464 }
18465
18466 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18467 // accumulator loops. Writing back to the accumulator allows the coalescer
18468 // to remove extra copies in the loop.   
18469 MachineBasicBlock *
18470 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18471                                  MachineBasicBlock *MBB) const {
18472   MachineOperand &AddendOp = MI->getOperand(3);
18473
18474   // Bail out early if the addend isn't a register - we can't switch these.
18475   if (!AddendOp.isReg())
18476     return MBB;
18477
18478   MachineFunction &MF = *MBB->getParent();
18479   MachineRegisterInfo &MRI = MF.getRegInfo();
18480
18481   // Check whether the addend is defined by a PHI:
18482   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18483   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18484   if (!AddendDef.isPHI())
18485     return MBB;
18486
18487   // Look for the following pattern:
18488   // loop:
18489   //   %addend = phi [%entry, 0], [%loop, %result]
18490   //   ...
18491   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18492
18493   // Replace with:
18494   //   loop:
18495   //   %addend = phi [%entry, 0], [%loop, %result]
18496   //   ...
18497   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18498
18499   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18500     assert(AddendDef.getOperand(i).isReg());
18501     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18502     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18503     if (&PHISrcInst == MI) {
18504       // Found a matching instruction.
18505       unsigned NewFMAOpc = 0;
18506       switch (MI->getOpcode()) {
18507         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18508         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18509         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18510         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18511         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18512         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18513         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18514         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18515         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18516         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18517         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18518         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18519         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18520         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18521         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18522         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18523         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18524         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18525         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18526         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18527         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18528         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18529         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18530         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18531         default: llvm_unreachable("Unrecognized FMA variant.");
18532       }
18533
18534       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18535       MachineInstrBuilder MIB =
18536         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18537         .addOperand(MI->getOperand(0))
18538         .addOperand(MI->getOperand(3))
18539         .addOperand(MI->getOperand(2))
18540         .addOperand(MI->getOperand(1));
18541       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18542       MI->eraseFromParent();
18543     }
18544   }
18545
18546   return MBB;
18547 }
18548
18549 MachineBasicBlock *
18550 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18551                                                MachineBasicBlock *BB) const {
18552   switch (MI->getOpcode()) {
18553   default: llvm_unreachable("Unexpected instr type to insert");
18554   case X86::TAILJMPd64:
18555   case X86::TAILJMPr64:
18556   case X86::TAILJMPm64:
18557     llvm_unreachable("TAILJMP64 would not be touched here.");
18558   case X86::TCRETURNdi64:
18559   case X86::TCRETURNri64:
18560   case X86::TCRETURNmi64:
18561     return BB;
18562   case X86::WIN_ALLOCA:
18563     return EmitLoweredWinAlloca(MI, BB);
18564   case X86::SEG_ALLOCA_32:
18565     return EmitLoweredSegAlloca(MI, BB, false);
18566   case X86::SEG_ALLOCA_64:
18567     return EmitLoweredSegAlloca(MI, BB, true);
18568   case X86::TLSCall_32:
18569   case X86::TLSCall_64:
18570     return EmitLoweredTLSCall(MI, BB);
18571   case X86::CMOV_GR8:
18572   case X86::CMOV_FR32:
18573   case X86::CMOV_FR64:
18574   case X86::CMOV_V4F32:
18575   case X86::CMOV_V2F64:
18576   case X86::CMOV_V2I64:
18577   case X86::CMOV_V8F32:
18578   case X86::CMOV_V4F64:
18579   case X86::CMOV_V4I64:
18580   case X86::CMOV_V16F32:
18581   case X86::CMOV_V8F64:
18582   case X86::CMOV_V8I64:
18583   case X86::CMOV_GR16:
18584   case X86::CMOV_GR32:
18585   case X86::CMOV_RFP32:
18586   case X86::CMOV_RFP64:
18587   case X86::CMOV_RFP80:
18588     return EmitLoweredSelect(MI, BB);
18589
18590   case X86::FP32_TO_INT16_IN_MEM:
18591   case X86::FP32_TO_INT32_IN_MEM:
18592   case X86::FP32_TO_INT64_IN_MEM:
18593   case X86::FP64_TO_INT16_IN_MEM:
18594   case X86::FP64_TO_INT32_IN_MEM:
18595   case X86::FP64_TO_INT64_IN_MEM:
18596   case X86::FP80_TO_INT16_IN_MEM:
18597   case X86::FP80_TO_INT32_IN_MEM:
18598   case X86::FP80_TO_INT64_IN_MEM: {
18599     MachineFunction *F = BB->getParent();
18600     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18601     DebugLoc DL = MI->getDebugLoc();
18602
18603     // Change the floating point control register to use "round towards zero"
18604     // mode when truncating to an integer value.
18605     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18606     addFrameReference(BuildMI(*BB, MI, DL,
18607                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18608
18609     // Load the old value of the high byte of the control word...
18610     unsigned OldCW =
18611       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18612     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18613                       CWFrameIdx);
18614
18615     // Set the high part to be round to zero...
18616     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18617       .addImm(0xC7F);
18618
18619     // Reload the modified control word now...
18620     addFrameReference(BuildMI(*BB, MI, DL,
18621                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18622
18623     // Restore the memory image of control word to original value
18624     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18625       .addReg(OldCW);
18626
18627     // Get the X86 opcode to use.
18628     unsigned Opc;
18629     switch (MI->getOpcode()) {
18630     default: llvm_unreachable("illegal opcode!");
18631     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18632     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18633     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18634     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18635     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18636     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18637     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18638     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18639     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18640     }
18641
18642     X86AddressMode AM;
18643     MachineOperand &Op = MI->getOperand(0);
18644     if (Op.isReg()) {
18645       AM.BaseType = X86AddressMode::RegBase;
18646       AM.Base.Reg = Op.getReg();
18647     } else {
18648       AM.BaseType = X86AddressMode::FrameIndexBase;
18649       AM.Base.FrameIndex = Op.getIndex();
18650     }
18651     Op = MI->getOperand(1);
18652     if (Op.isImm())
18653       AM.Scale = Op.getImm();
18654     Op = MI->getOperand(2);
18655     if (Op.isImm())
18656       AM.IndexReg = Op.getImm();
18657     Op = MI->getOperand(3);
18658     if (Op.isGlobal()) {
18659       AM.GV = Op.getGlobal();
18660     } else {
18661       AM.Disp = Op.getImm();
18662     }
18663     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18664                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18665
18666     // Reload the original control word now.
18667     addFrameReference(BuildMI(*BB, MI, DL,
18668                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18669
18670     MI->eraseFromParent();   // The pseudo instruction is gone now.
18671     return BB;
18672   }
18673     // String/text processing lowering.
18674   case X86::PCMPISTRM128REG:
18675   case X86::VPCMPISTRM128REG:
18676   case X86::PCMPISTRM128MEM:
18677   case X86::VPCMPISTRM128MEM:
18678   case X86::PCMPESTRM128REG:
18679   case X86::VPCMPESTRM128REG:
18680   case X86::PCMPESTRM128MEM:
18681   case X86::VPCMPESTRM128MEM:
18682     assert(Subtarget->hasSSE42() &&
18683            "Target must have SSE4.2 or AVX features enabled");
18684     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18685
18686   // String/text processing lowering.
18687   case X86::PCMPISTRIREG:
18688   case X86::VPCMPISTRIREG:
18689   case X86::PCMPISTRIMEM:
18690   case X86::VPCMPISTRIMEM:
18691   case X86::PCMPESTRIREG:
18692   case X86::VPCMPESTRIREG:
18693   case X86::PCMPESTRIMEM:
18694   case X86::VPCMPESTRIMEM:
18695     assert(Subtarget->hasSSE42() &&
18696            "Target must have SSE4.2 or AVX features enabled");
18697     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18698
18699   // Thread synchronization.
18700   case X86::MONITOR:
18701     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18702
18703   // xbegin
18704   case X86::XBEGIN:
18705     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18706
18707   // Atomic Lowering.
18708   case X86::ATOMAND8:
18709   case X86::ATOMAND16:
18710   case X86::ATOMAND32:
18711   case X86::ATOMAND64:
18712     // Fall through
18713   case X86::ATOMOR8:
18714   case X86::ATOMOR16:
18715   case X86::ATOMOR32:
18716   case X86::ATOMOR64:
18717     // Fall through
18718   case X86::ATOMXOR16:
18719   case X86::ATOMXOR8:
18720   case X86::ATOMXOR32:
18721   case X86::ATOMXOR64:
18722     // Fall through
18723   case X86::ATOMNAND8:
18724   case X86::ATOMNAND16:
18725   case X86::ATOMNAND32:
18726   case X86::ATOMNAND64:
18727     // Fall through
18728   case X86::ATOMMAX8:
18729   case X86::ATOMMAX16:
18730   case X86::ATOMMAX32:
18731   case X86::ATOMMAX64:
18732     // Fall through
18733   case X86::ATOMMIN8:
18734   case X86::ATOMMIN16:
18735   case X86::ATOMMIN32:
18736   case X86::ATOMMIN64:
18737     // Fall through
18738   case X86::ATOMUMAX8:
18739   case X86::ATOMUMAX16:
18740   case X86::ATOMUMAX32:
18741   case X86::ATOMUMAX64:
18742     // Fall through
18743   case X86::ATOMUMIN8:
18744   case X86::ATOMUMIN16:
18745   case X86::ATOMUMIN32:
18746   case X86::ATOMUMIN64:
18747     return EmitAtomicLoadArith(MI, BB);
18748
18749   // This group does 64-bit operations on a 32-bit host.
18750   case X86::ATOMAND6432:
18751   case X86::ATOMOR6432:
18752   case X86::ATOMXOR6432:
18753   case X86::ATOMNAND6432:
18754   case X86::ATOMADD6432:
18755   case X86::ATOMSUB6432:
18756   case X86::ATOMMAX6432:
18757   case X86::ATOMMIN6432:
18758   case X86::ATOMUMAX6432:
18759   case X86::ATOMUMIN6432:
18760   case X86::ATOMSWAP6432:
18761     return EmitAtomicLoadArith6432(MI, BB);
18762
18763   case X86::VASTART_SAVE_XMM_REGS:
18764     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18765
18766   case X86::VAARG_64:
18767     return EmitVAARG64WithCustomInserter(MI, BB);
18768
18769   case X86::EH_SjLj_SetJmp32:
18770   case X86::EH_SjLj_SetJmp64:
18771     return emitEHSjLjSetJmp(MI, BB);
18772
18773   case X86::EH_SjLj_LongJmp32:
18774   case X86::EH_SjLj_LongJmp64:
18775     return emitEHSjLjLongJmp(MI, BB);
18776
18777   case TargetOpcode::STACKMAP:
18778   case TargetOpcode::PATCHPOINT:
18779     return emitPatchPoint(MI, BB);
18780
18781   case X86::VFMADDPDr213r:
18782   case X86::VFMADDPSr213r:
18783   case X86::VFMADDSDr213r:
18784   case X86::VFMADDSSr213r:
18785   case X86::VFMSUBPDr213r:
18786   case X86::VFMSUBPSr213r:
18787   case X86::VFMSUBSDr213r:
18788   case X86::VFMSUBSSr213r:
18789   case X86::VFNMADDPDr213r:
18790   case X86::VFNMADDPSr213r:
18791   case X86::VFNMADDSDr213r:
18792   case X86::VFNMADDSSr213r:
18793   case X86::VFNMSUBPDr213r:
18794   case X86::VFNMSUBPSr213r:
18795   case X86::VFNMSUBSDr213r:
18796   case X86::VFNMSUBSSr213r:
18797   case X86::VFMADDPDr213rY:
18798   case X86::VFMADDPSr213rY:
18799   case X86::VFMSUBPDr213rY:
18800   case X86::VFMSUBPSr213rY:
18801   case X86::VFNMADDPDr213rY:
18802   case X86::VFNMADDPSr213rY:
18803   case X86::VFNMSUBPDr213rY:
18804   case X86::VFNMSUBPSr213rY:
18805     return emitFMA3Instr(MI, BB);
18806   }
18807 }
18808
18809 //===----------------------------------------------------------------------===//
18810 //                           X86 Optimization Hooks
18811 //===----------------------------------------------------------------------===//
18812
18813 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18814                                                       APInt &KnownZero,
18815                                                       APInt &KnownOne,
18816                                                       const SelectionDAG &DAG,
18817                                                       unsigned Depth) const {
18818   unsigned BitWidth = KnownZero.getBitWidth();
18819   unsigned Opc = Op.getOpcode();
18820   assert((Opc >= ISD::BUILTIN_OP_END ||
18821           Opc == ISD::INTRINSIC_WO_CHAIN ||
18822           Opc == ISD::INTRINSIC_W_CHAIN ||
18823           Opc == ISD::INTRINSIC_VOID) &&
18824          "Should use MaskedValueIsZero if you don't know whether Op"
18825          " is a target node!");
18826
18827   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18828   switch (Opc) {
18829   default: break;
18830   case X86ISD::ADD:
18831   case X86ISD::SUB:
18832   case X86ISD::ADC:
18833   case X86ISD::SBB:
18834   case X86ISD::SMUL:
18835   case X86ISD::UMUL:
18836   case X86ISD::INC:
18837   case X86ISD::DEC:
18838   case X86ISD::OR:
18839   case X86ISD::XOR:
18840   case X86ISD::AND:
18841     // These nodes' second result is a boolean.
18842     if (Op.getResNo() == 0)
18843       break;
18844     // Fallthrough
18845   case X86ISD::SETCC:
18846     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18847     break;
18848   case ISD::INTRINSIC_WO_CHAIN: {
18849     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18850     unsigned NumLoBits = 0;
18851     switch (IntId) {
18852     default: break;
18853     case Intrinsic::x86_sse_movmsk_ps:
18854     case Intrinsic::x86_avx_movmsk_ps_256:
18855     case Intrinsic::x86_sse2_movmsk_pd:
18856     case Intrinsic::x86_avx_movmsk_pd_256:
18857     case Intrinsic::x86_mmx_pmovmskb:
18858     case Intrinsic::x86_sse2_pmovmskb_128:
18859     case Intrinsic::x86_avx2_pmovmskb: {
18860       // High bits of movmskp{s|d}, pmovmskb are known zero.
18861       switch (IntId) {
18862         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18863         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18864         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18865         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18866         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18867         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18868         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18869         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18870       }
18871       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18872       break;
18873     }
18874     }
18875     break;
18876   }
18877   }
18878 }
18879
18880 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18881   SDValue Op,
18882   const SelectionDAG &,
18883   unsigned Depth) const {
18884   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18885   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18886     return Op.getValueType().getScalarType().getSizeInBits();
18887
18888   // Fallback case.
18889   return 1;
18890 }
18891
18892 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18893 /// node is a GlobalAddress + offset.
18894 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18895                                        const GlobalValue* &GA,
18896                                        int64_t &Offset) const {
18897   if (N->getOpcode() == X86ISD::Wrapper) {
18898     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18899       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18900       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18901       return true;
18902     }
18903   }
18904   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18905 }
18906
18907 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18908 /// same as extracting the high 128-bit part of 256-bit vector and then
18909 /// inserting the result into the low part of a new 256-bit vector
18910 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18911   EVT VT = SVOp->getValueType(0);
18912   unsigned NumElems = VT.getVectorNumElements();
18913
18914   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18915   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18916     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18917         SVOp->getMaskElt(j) >= 0)
18918       return false;
18919
18920   return true;
18921 }
18922
18923 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18924 /// same as extracting the low 128-bit part of 256-bit vector and then
18925 /// inserting the result into the high part of a new 256-bit vector
18926 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18927   EVT VT = SVOp->getValueType(0);
18928   unsigned NumElems = VT.getVectorNumElements();
18929
18930   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18931   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18932     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18933         SVOp->getMaskElt(j) >= 0)
18934       return false;
18935
18936   return true;
18937 }
18938
18939 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18940 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18941                                         TargetLowering::DAGCombinerInfo &DCI,
18942                                         const X86Subtarget* Subtarget) {
18943   SDLoc dl(N);
18944   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18945   SDValue V1 = SVOp->getOperand(0);
18946   SDValue V2 = SVOp->getOperand(1);
18947   EVT VT = SVOp->getValueType(0);
18948   unsigned NumElems = VT.getVectorNumElements();
18949
18950   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18951       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18952     //
18953     //                   0,0,0,...
18954     //                      |
18955     //    V      UNDEF    BUILD_VECTOR    UNDEF
18956     //     \      /           \           /
18957     //  CONCAT_VECTOR         CONCAT_VECTOR
18958     //         \                  /
18959     //          \                /
18960     //          RESULT: V + zero extended
18961     //
18962     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18963         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18964         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18965       return SDValue();
18966
18967     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18968       return SDValue();
18969
18970     // To match the shuffle mask, the first half of the mask should
18971     // be exactly the first vector, and all the rest a splat with the
18972     // first element of the second one.
18973     for (unsigned i = 0; i != NumElems/2; ++i)
18974       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18975           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18976         return SDValue();
18977
18978     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18979     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18980       if (Ld->hasNUsesOfValue(1, 0)) {
18981         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18982         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18983         SDValue ResNode =
18984           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18985                                   Ld->getMemoryVT(),
18986                                   Ld->getPointerInfo(),
18987                                   Ld->getAlignment(),
18988                                   false/*isVolatile*/, true/*ReadMem*/,
18989                                   false/*WriteMem*/);
18990
18991         // Make sure the newly-created LOAD is in the same position as Ld in
18992         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18993         // and update uses of Ld's output chain to use the TokenFactor.
18994         if (Ld->hasAnyUseOfValue(1)) {
18995           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18996                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18997           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18998           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18999                                  SDValue(ResNode.getNode(), 1));
19000         }
19001
19002         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19003       }
19004     }
19005
19006     // Emit a zeroed vector and insert the desired subvector on its
19007     // first half.
19008     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19009     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19010     return DCI.CombineTo(N, InsV);
19011   }
19012
19013   //===--------------------------------------------------------------------===//
19014   // Combine some shuffles into subvector extracts and inserts:
19015   //
19016
19017   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19018   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19019     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19020     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19021     return DCI.CombineTo(N, InsV);
19022   }
19023
19024   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19025   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19026     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19027     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19028     return DCI.CombineTo(N, InsV);
19029   }
19030
19031   return SDValue();
19032 }
19033
19034 /// \brief Get the PSHUF-style mask from PSHUF node.
19035 ///
19036 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19037 /// PSHUF-style masks that can be reused with such instructions.
19038 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19039   SmallVector<int, 4> Mask;
19040   bool IsUnary;
19041   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19042   (void)HaveMask;
19043   assert(HaveMask);
19044
19045   switch (N.getOpcode()) {
19046   case X86ISD::PSHUFD:
19047     return Mask;
19048   case X86ISD::PSHUFLW:
19049     Mask.resize(4);
19050     return Mask;
19051   case X86ISD::PSHUFHW:
19052     Mask.erase(Mask.begin(), Mask.begin() + 4);
19053     for (int &M : Mask)
19054       M -= 4;
19055     return Mask;
19056   default:
19057     llvm_unreachable("No valid shuffle instruction found!");
19058   }
19059 }
19060
19061 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19062 ///
19063 /// We walk up the chain and look for a combinable shuffle, skipping over
19064 /// shuffles that we could hoist this shuffle's transformation past without
19065 /// altering anything.
19066 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19067                                          SelectionDAG &DAG,
19068                                          TargetLowering::DAGCombinerInfo &DCI) {
19069   assert(N.getOpcode() == X86ISD::PSHUFD &&
19070          "Called with something other than an x86 128-bit half shuffle!");
19071   SDLoc DL(N);
19072
19073   // Walk up a single-use chain looking for a combinable shuffle.
19074   SDValue V = N.getOperand(0);
19075   for (; V.hasOneUse(); V = V.getOperand(0)) {
19076     switch (V.getOpcode()) {
19077     default:
19078       return false; // Nothing combined!
19079
19080     case ISD::BITCAST:
19081       // Skip bitcasts as we always know the type for the target specific
19082       // instructions.
19083       continue;
19084
19085     case X86ISD::PSHUFD:
19086       // Found another dword shuffle.
19087       break;
19088
19089     case X86ISD::PSHUFLW:
19090       // Check that the low words (being shuffled) are the identity in the
19091       // dword shuffle, and the high words are self-contained.
19092       if (Mask[0] != 0 || Mask[1] != 1 ||
19093           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19094         return false;
19095
19096       continue;
19097
19098     case X86ISD::PSHUFHW:
19099       // Check that the high words (being shuffled) are the identity in the
19100       // dword shuffle, and the low words are self-contained.
19101       if (Mask[2] != 2 || Mask[3] != 3 ||
19102           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19103         return false;
19104
19105       continue;
19106     }
19107     // Break out of the loop if we break out of the switch.
19108     break;
19109   }
19110
19111   if (!V.hasOneUse())
19112     // We fell out of the loop without finding a viable combining instruction.
19113     return false;
19114
19115   // Record the old value to use in RAUW-ing.
19116   SDValue Old = V;
19117
19118   // Merge this node's mask and our incoming mask.
19119   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19120   for (int &M : Mask)
19121     M = VMask[M];
19122   V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
19123                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19124
19125   // Replace N with its operand as we're going to combine that shuffle away.
19126   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19127
19128   // Replace the combinable shuffle with the combined one, updating all users
19129   // so that we re-evaluate the chain here.
19130   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19131   return true;
19132 }
19133
19134 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19135 ///
19136 /// We walk up the chain, skipping shuffles of the other half and looking
19137 /// through shuffles which switch halves trying to find a shuffle of the same
19138 /// pair of dwords.
19139 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19140                                         SelectionDAG &DAG,
19141                                         TargetLowering::DAGCombinerInfo &DCI) {
19142   assert(
19143       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19144       "Called with something other than an x86 128-bit half shuffle!");
19145   SDLoc DL(N);
19146   unsigned CombineOpcode = N.getOpcode();
19147
19148   // Walk up a single-use chain looking for a combinable shuffle.
19149   SDValue V = N.getOperand(0);
19150   for (; V.hasOneUse(); V = V.getOperand(0)) {
19151     switch (V.getOpcode()) {
19152     default:
19153       return false; // Nothing combined!
19154
19155     case ISD::BITCAST:
19156       // Skip bitcasts as we always know the type for the target specific
19157       // instructions.
19158       continue;
19159
19160     case X86ISD::PSHUFLW:
19161     case X86ISD::PSHUFHW:
19162       if (V.getOpcode() == CombineOpcode)
19163         break;
19164
19165       // Other-half shuffles are no-ops.
19166       continue;
19167
19168     case X86ISD::PSHUFD: {
19169       // We can only handle pshufd if the half we are combining either stays in
19170       // its half, or switches to the other half. Bail if one of these isn't
19171       // true.
19172       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19173       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19174       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19175             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19176         return false;
19177
19178       // Map the mask through the pshufd and keep walking up the chain.
19179       for (int i = 0; i < 4; ++i)
19180         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19181
19182       // Switch halves if the pshufd does.
19183       CombineOpcode =
19184           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19185       continue;
19186     }
19187     }
19188     // Break out of the loop if we break out of the switch.
19189     break;
19190   }
19191
19192   if (!V.hasOneUse())
19193     // We fell out of the loop without finding a viable combining instruction.
19194     return false;
19195
19196   // Record the old value to use in RAUW-ing.
19197   SDValue Old = V;
19198
19199   // Merge this node's mask and our incoming mask (adjusted to account for all
19200   // the pshufd instructions encountered).
19201   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19202   for (int &M : Mask)
19203     M = VMask[M];
19204   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19205                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19206
19207   // Replace N with its operand as we're going to combine that shuffle away.
19208   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19209
19210   // Replace the combinable shuffle with the combined one, updating all users
19211   // so that we re-evaluate the chain here.
19212   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19213   return true;
19214 }
19215
19216 /// \brief Try to combine x86 target specific shuffles.
19217 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19218                                            TargetLowering::DAGCombinerInfo &DCI,
19219                                            const X86Subtarget *Subtarget) {
19220   SDLoc DL(N);
19221   MVT VT = N.getSimpleValueType();
19222   SmallVector<int, 4> Mask;
19223
19224   switch (N.getOpcode()) {
19225   case X86ISD::PSHUFD:
19226   case X86ISD::PSHUFLW:
19227   case X86ISD::PSHUFHW:
19228     Mask = getPSHUFShuffleMask(N);
19229     assert(Mask.size() == 4);
19230     break;
19231   default:
19232     return SDValue();
19233   }
19234
19235   // Nuke no-op shuffles that show up after combining.
19236   if (isNoopShuffleMask(Mask))
19237     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19238
19239   // Look for simplifications involving one or two shuffle instructions.
19240   SDValue V = N.getOperand(0);
19241   switch (N.getOpcode()) {
19242   default:
19243     break;
19244   case X86ISD::PSHUFLW:
19245   case X86ISD::PSHUFHW:
19246     assert(VT == MVT::v8i16);
19247     (void)VT;
19248
19249     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19250       return SDValue(); // We combined away this shuffle, so we're done.
19251
19252     // See if this reduces to a PSHUFD which is no more expensive and can
19253     // combine with more operations.
19254     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19255         areAdjacentMasksSequential(Mask)) {
19256       int DMask[] = {-1, -1, -1, -1};
19257       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19258       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19259       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19260       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19261       DCI.AddToWorklist(V.getNode());
19262       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19263                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19264       DCI.AddToWorklist(V.getNode());
19265       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19266     }
19267
19268     break;
19269
19270   case X86ISD::PSHUFD:
19271     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19272       return SDValue(); // We combined away this shuffle.
19273
19274     break;
19275   }
19276
19277   return SDValue();
19278 }
19279
19280 /// PerformShuffleCombine - Performs several different shuffle combines.
19281 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19282                                      TargetLowering::DAGCombinerInfo &DCI,
19283                                      const X86Subtarget *Subtarget) {
19284   SDLoc dl(N);
19285   SDValue N0 = N->getOperand(0);
19286   SDValue N1 = N->getOperand(1);
19287   EVT VT = N->getValueType(0);
19288
19289   // Canonicalize shuffles that perform 'addsub' on packed float vectors
19290   // according to the rule:
19291   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
19292   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
19293   //
19294   // Where 'Mask' is:
19295   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
19296   //  <0,3>                 -- for v2f64 shuffles;
19297   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
19298   //
19299   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
19300   // during ISel stage.
19301   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
19302       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19303        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19304       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
19305       // Operands to the FADD and FSUB must be the same.
19306       ((N0->getOperand(0) == N1->getOperand(0) &&
19307         N0->getOperand(1) == N1->getOperand(1)) ||
19308        // FADD is commutable. See if by commuting the operands of the FADD
19309        // we would still be able to match the operands of the FSUB dag node.
19310        (N0->getOperand(1) == N1->getOperand(0) &&
19311         N0->getOperand(0) == N1->getOperand(1))) &&
19312       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
19313       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
19314     
19315     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
19316     unsigned NumElts = VT.getVectorNumElements();
19317     ArrayRef<int> Mask = SV->getMask();
19318     bool CanFold = true;
19319
19320     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
19321       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
19322
19323     if (CanFold) {
19324       SDValue Op0 = N1->getOperand(0);
19325       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
19326       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
19327       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
19328       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
19329     }
19330   }
19331
19332   // Don't create instructions with illegal types after legalize types has run.
19333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19334   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19335     return SDValue();
19336
19337   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19338   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19339       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19340     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19341
19342   // During Type Legalization, when promoting illegal vector types,
19343   // the backend might introduce new shuffle dag nodes and bitcasts.
19344   //
19345   // This code performs the following transformation:
19346   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19347   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19348   //
19349   // We do this only if both the bitcast and the BINOP dag nodes have
19350   // one use. Also, perform this transformation only if the new binary
19351   // operation is legal. This is to avoid introducing dag nodes that
19352   // potentially need to be further expanded (or custom lowered) into a
19353   // less optimal sequence of dag nodes.
19354   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19355       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19356       N0.getOpcode() == ISD::BITCAST) {
19357     SDValue BC0 = N0.getOperand(0);
19358     EVT SVT = BC0.getValueType();
19359     unsigned Opcode = BC0.getOpcode();
19360     unsigned NumElts = VT.getVectorNumElements();
19361     
19362     if (BC0.hasOneUse() && SVT.isVector() &&
19363         SVT.getVectorNumElements() * 2 == NumElts &&
19364         TLI.isOperationLegal(Opcode, VT)) {
19365       bool CanFold = false;
19366       switch (Opcode) {
19367       default : break;
19368       case ISD::ADD :
19369       case ISD::FADD :
19370       case ISD::SUB :
19371       case ISD::FSUB :
19372       case ISD::MUL :
19373       case ISD::FMUL :
19374         CanFold = true;
19375       }
19376
19377       unsigned SVTNumElts = SVT.getVectorNumElements();
19378       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19379       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19380         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19381       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19382         CanFold = SVOp->getMaskElt(i) < 0;
19383
19384       if (CanFold) {
19385         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19386         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19387         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19388         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19389       }
19390     }
19391   }
19392
19393   // Only handle 128 wide vector from here on.
19394   if (!VT.is128BitVector())
19395     return SDValue();
19396
19397   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19398   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19399   // consecutive, non-overlapping, and in the right order.
19400   SmallVector<SDValue, 16> Elts;
19401   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19402     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19403
19404   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19405   if (LD.getNode())
19406     return LD;
19407
19408   if (isTargetShuffle(N->getOpcode())) {
19409     SDValue Shuffle =
19410         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19411     if (Shuffle.getNode())
19412       return Shuffle;
19413   }
19414
19415   return SDValue();
19416 }
19417
19418 /// PerformTruncateCombine - Converts truncate operation to
19419 /// a sequence of vector shuffle operations.
19420 /// It is possible when we truncate 256-bit vector to 128-bit vector
19421 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19422                                       TargetLowering::DAGCombinerInfo &DCI,
19423                                       const X86Subtarget *Subtarget)  {
19424   return SDValue();
19425 }
19426
19427 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19428 /// specific shuffle of a load can be folded into a single element load.
19429 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19430 /// shuffles have been customed lowered so we need to handle those here.
19431 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19432                                          TargetLowering::DAGCombinerInfo &DCI) {
19433   if (DCI.isBeforeLegalizeOps())
19434     return SDValue();
19435
19436   SDValue InVec = N->getOperand(0);
19437   SDValue EltNo = N->getOperand(1);
19438
19439   if (!isa<ConstantSDNode>(EltNo))
19440     return SDValue();
19441
19442   EVT VT = InVec.getValueType();
19443
19444   bool HasShuffleIntoBitcast = false;
19445   if (InVec.getOpcode() == ISD::BITCAST) {
19446     // Don't duplicate a load with other uses.
19447     if (!InVec.hasOneUse())
19448       return SDValue();
19449     EVT BCVT = InVec.getOperand(0).getValueType();
19450     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19451       return SDValue();
19452     InVec = InVec.getOperand(0);
19453     HasShuffleIntoBitcast = true;
19454   }
19455
19456   if (!isTargetShuffle(InVec.getOpcode()))
19457     return SDValue();
19458
19459   // Don't duplicate a load with other uses.
19460   if (!InVec.hasOneUse())
19461     return SDValue();
19462
19463   SmallVector<int, 16> ShuffleMask;
19464   bool UnaryShuffle;
19465   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19466                             UnaryShuffle))
19467     return SDValue();
19468
19469   // Select the input vector, guarding against out of range extract vector.
19470   unsigned NumElems = VT.getVectorNumElements();
19471   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19472   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19473   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19474                                          : InVec.getOperand(1);
19475
19476   // If inputs to shuffle are the same for both ops, then allow 2 uses
19477   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19478
19479   if (LdNode.getOpcode() == ISD::BITCAST) {
19480     // Don't duplicate a load with other uses.
19481     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19482       return SDValue();
19483
19484     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19485     LdNode = LdNode.getOperand(0);
19486   }
19487
19488   if (!ISD::isNormalLoad(LdNode.getNode()))
19489     return SDValue();
19490
19491   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19492
19493   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19494     return SDValue();
19495
19496   if (HasShuffleIntoBitcast) {
19497     // If there's a bitcast before the shuffle, check if the load type and
19498     // alignment is valid.
19499     unsigned Align = LN0->getAlignment();
19500     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19501     unsigned NewAlign = TLI.getDataLayout()->
19502       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19503
19504     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19505       return SDValue();
19506   }
19507
19508   // All checks match so transform back to vector_shuffle so that DAG combiner
19509   // can finish the job
19510   SDLoc dl(N);
19511
19512   // Create shuffle node taking into account the case that its a unary shuffle
19513   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19514   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19515                                  InVec.getOperand(0), Shuffle,
19516                                  &ShuffleMask[0]);
19517   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19518   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19519                      EltNo);
19520 }
19521
19522 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19523 /// generation and convert it from being a bunch of shuffles and extracts
19524 /// to a simple store and scalar loads to extract the elements.
19525 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19526                                          TargetLowering::DAGCombinerInfo &DCI) {
19527   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19528   if (NewOp.getNode())
19529     return NewOp;
19530
19531   SDValue InputVector = N->getOperand(0);
19532
19533   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19534   // from mmx to v2i32 has a single usage.
19535   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19536       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19537       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19538     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19539                        N->getValueType(0),
19540                        InputVector.getNode()->getOperand(0));
19541
19542   // Only operate on vectors of 4 elements, where the alternative shuffling
19543   // gets to be more expensive.
19544   if (InputVector.getValueType() != MVT::v4i32)
19545     return SDValue();
19546
19547   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19548   // single use which is a sign-extend or zero-extend, and all elements are
19549   // used.
19550   SmallVector<SDNode *, 4> Uses;
19551   unsigned ExtractedElements = 0;
19552   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19553        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19554     if (UI.getUse().getResNo() != InputVector.getResNo())
19555       return SDValue();
19556
19557     SDNode *Extract = *UI;
19558     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19559       return SDValue();
19560
19561     if (Extract->getValueType(0) != MVT::i32)
19562       return SDValue();
19563     if (!Extract->hasOneUse())
19564       return SDValue();
19565     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19566         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19567       return SDValue();
19568     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19569       return SDValue();
19570
19571     // Record which element was extracted.
19572     ExtractedElements |=
19573       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19574
19575     Uses.push_back(Extract);
19576   }
19577
19578   // If not all the elements were used, this may not be worthwhile.
19579   if (ExtractedElements != 15)
19580     return SDValue();
19581
19582   // Ok, we've now decided to do the transformation.
19583   SDLoc dl(InputVector);
19584
19585   // Store the value to a temporary stack slot.
19586   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19587   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19588                             MachinePointerInfo(), false, false, 0);
19589
19590   // Replace each use (extract) with a load of the appropriate element.
19591   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19592        UE = Uses.end(); UI != UE; ++UI) {
19593     SDNode *Extract = *UI;
19594
19595     // cOMpute the element's address.
19596     SDValue Idx = Extract->getOperand(1);
19597     unsigned EltSize =
19598         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19599     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19600     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19601     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19602
19603     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19604                                      StackPtr, OffsetVal);
19605
19606     // Load the scalar.
19607     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19608                                      ScalarAddr, MachinePointerInfo(),
19609                                      false, false, false, 0);
19610
19611     // Replace the exact with the load.
19612     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19613   }
19614
19615   // The replacement was made in place; don't return anything.
19616   return SDValue();
19617 }
19618
19619 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19620 static std::pair<unsigned, bool>
19621 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19622                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19623   if (!VT.isVector())
19624     return std::make_pair(0, false);
19625
19626   bool NeedSplit = false;
19627   switch (VT.getSimpleVT().SimpleTy) {
19628   default: return std::make_pair(0, false);
19629   case MVT::v32i8:
19630   case MVT::v16i16:
19631   case MVT::v8i32:
19632     if (!Subtarget->hasAVX2())
19633       NeedSplit = true;
19634     if (!Subtarget->hasAVX())
19635       return std::make_pair(0, false);
19636     break;
19637   case MVT::v16i8:
19638   case MVT::v8i16:
19639   case MVT::v4i32:
19640     if (!Subtarget->hasSSE2())
19641       return std::make_pair(0, false);
19642   }
19643
19644   // SSE2 has only a small subset of the operations.
19645   bool hasUnsigned = Subtarget->hasSSE41() ||
19646                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19647   bool hasSigned = Subtarget->hasSSE41() ||
19648                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19649
19650   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19651
19652   unsigned Opc = 0;
19653   // Check for x CC y ? x : y.
19654   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19655       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19656     switch (CC) {
19657     default: break;
19658     case ISD::SETULT:
19659     case ISD::SETULE:
19660       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19661     case ISD::SETUGT:
19662     case ISD::SETUGE:
19663       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19664     case ISD::SETLT:
19665     case ISD::SETLE:
19666       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19667     case ISD::SETGT:
19668     case ISD::SETGE:
19669       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19670     }
19671   // Check for x CC y ? y : x -- a min/max with reversed arms.
19672   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19673              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19674     switch (CC) {
19675     default: break;
19676     case ISD::SETULT:
19677     case ISD::SETULE:
19678       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19679     case ISD::SETUGT:
19680     case ISD::SETUGE:
19681       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19682     case ISD::SETLT:
19683     case ISD::SETLE:
19684       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19685     case ISD::SETGT:
19686     case ISD::SETGE:
19687       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19688     }
19689   }
19690
19691   return std::make_pair(Opc, NeedSplit);
19692 }
19693
19694 static SDValue
19695 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19696                                       const X86Subtarget *Subtarget) {
19697   SDLoc dl(N);
19698   SDValue Cond = N->getOperand(0);
19699   SDValue LHS = N->getOperand(1);
19700   SDValue RHS = N->getOperand(2);
19701
19702   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19703     SDValue CondSrc = Cond->getOperand(0);
19704     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19705       Cond = CondSrc->getOperand(0);
19706   }
19707
19708   MVT VT = N->getSimpleValueType(0);
19709   MVT EltVT = VT.getVectorElementType();
19710   unsigned NumElems = VT.getVectorNumElements();
19711   // There is no blend with immediate in AVX-512.
19712   if (VT.is512BitVector())
19713     return SDValue();
19714
19715   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19716     return SDValue();
19717   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19718     return SDValue();
19719
19720   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19721     return SDValue();
19722
19723   unsigned MaskValue = 0;
19724   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19725     return SDValue();
19726
19727   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19728   for (unsigned i = 0; i < NumElems; ++i) {
19729     // Be sure we emit undef where we can.
19730     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19731       ShuffleMask[i] = -1;
19732     else
19733       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19734   }
19735
19736   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19737 }
19738
19739 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19740 /// nodes.
19741 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19742                                     TargetLowering::DAGCombinerInfo &DCI,
19743                                     const X86Subtarget *Subtarget) {
19744   SDLoc DL(N);
19745   SDValue Cond = N->getOperand(0);
19746   // Get the LHS/RHS of the select.
19747   SDValue LHS = N->getOperand(1);
19748   SDValue RHS = N->getOperand(2);
19749   EVT VT = LHS.getValueType();
19750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19751
19752   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19753   // instructions match the semantics of the common C idiom x<y?x:y but not
19754   // x<=y?x:y, because of how they handle negative zero (which can be
19755   // ignored in unsafe-math mode).
19756   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19757       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19758       (Subtarget->hasSSE2() ||
19759        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19760     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19761
19762     unsigned Opcode = 0;
19763     // Check for x CC y ? x : y.
19764     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19765         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19766       switch (CC) {
19767       default: break;
19768       case ISD::SETULT:
19769         // Converting this to a min would handle NaNs incorrectly, and swapping
19770         // the operands would cause it to handle comparisons between positive
19771         // and negative zero incorrectly.
19772         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19773           if (!DAG.getTarget().Options.UnsafeFPMath &&
19774               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19775             break;
19776           std::swap(LHS, RHS);
19777         }
19778         Opcode = X86ISD::FMIN;
19779         break;
19780       case ISD::SETOLE:
19781         // Converting this to a min would handle comparisons between positive
19782         // and negative zero incorrectly.
19783         if (!DAG.getTarget().Options.UnsafeFPMath &&
19784             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19785           break;
19786         Opcode = X86ISD::FMIN;
19787         break;
19788       case ISD::SETULE:
19789         // Converting this to a min would handle both negative zeros and NaNs
19790         // incorrectly, but we can swap the operands to fix both.
19791         std::swap(LHS, RHS);
19792       case ISD::SETOLT:
19793       case ISD::SETLT:
19794       case ISD::SETLE:
19795         Opcode = X86ISD::FMIN;
19796         break;
19797
19798       case ISD::SETOGE:
19799         // Converting this to a max would handle comparisons between positive
19800         // and negative zero incorrectly.
19801         if (!DAG.getTarget().Options.UnsafeFPMath &&
19802             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19803           break;
19804         Opcode = X86ISD::FMAX;
19805         break;
19806       case ISD::SETUGT:
19807         // Converting this to a max would handle NaNs incorrectly, and swapping
19808         // the operands would cause it to handle comparisons between positive
19809         // and negative zero incorrectly.
19810         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19811           if (!DAG.getTarget().Options.UnsafeFPMath &&
19812               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19813             break;
19814           std::swap(LHS, RHS);
19815         }
19816         Opcode = X86ISD::FMAX;
19817         break;
19818       case ISD::SETUGE:
19819         // Converting this to a max would handle both negative zeros and NaNs
19820         // incorrectly, but we can swap the operands to fix both.
19821         std::swap(LHS, RHS);
19822       case ISD::SETOGT:
19823       case ISD::SETGT:
19824       case ISD::SETGE:
19825         Opcode = X86ISD::FMAX;
19826         break;
19827       }
19828     // Check for x CC y ? y : x -- a min/max with reversed arms.
19829     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19830                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19831       switch (CC) {
19832       default: break;
19833       case ISD::SETOGE:
19834         // Converting this to a min would handle comparisons between positive
19835         // and negative zero incorrectly, and swapping the operands would
19836         // cause it to handle NaNs incorrectly.
19837         if (!DAG.getTarget().Options.UnsafeFPMath &&
19838             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19839           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19840             break;
19841           std::swap(LHS, RHS);
19842         }
19843         Opcode = X86ISD::FMIN;
19844         break;
19845       case ISD::SETUGT:
19846         // Converting this to a min would handle NaNs incorrectly.
19847         if (!DAG.getTarget().Options.UnsafeFPMath &&
19848             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19849           break;
19850         Opcode = X86ISD::FMIN;
19851         break;
19852       case ISD::SETUGE:
19853         // Converting this to a min would handle both negative zeros and NaNs
19854         // incorrectly, but we can swap the operands to fix both.
19855         std::swap(LHS, RHS);
19856       case ISD::SETOGT:
19857       case ISD::SETGT:
19858       case ISD::SETGE:
19859         Opcode = X86ISD::FMIN;
19860         break;
19861
19862       case ISD::SETULT:
19863         // Converting this to a max would handle NaNs incorrectly.
19864         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19865           break;
19866         Opcode = X86ISD::FMAX;
19867         break;
19868       case ISD::SETOLE:
19869         // Converting this to a max would handle comparisons between positive
19870         // and negative zero incorrectly, and swapping the operands would
19871         // cause it to handle NaNs incorrectly.
19872         if (!DAG.getTarget().Options.UnsafeFPMath &&
19873             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19874           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19875             break;
19876           std::swap(LHS, RHS);
19877         }
19878         Opcode = X86ISD::FMAX;
19879         break;
19880       case ISD::SETULE:
19881         // Converting this to a max would handle both negative zeros and NaNs
19882         // incorrectly, but we can swap the operands to fix both.
19883         std::swap(LHS, RHS);
19884       case ISD::SETOLT:
19885       case ISD::SETLT:
19886       case ISD::SETLE:
19887         Opcode = X86ISD::FMAX;
19888         break;
19889       }
19890     }
19891
19892     if (Opcode)
19893       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19894   }
19895
19896   EVT CondVT = Cond.getValueType();
19897   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19898       CondVT.getVectorElementType() == MVT::i1) {
19899     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19900     // lowering on AVX-512. In this case we convert it to
19901     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19902     // The same situation for all 128 and 256-bit vectors of i8 and i16
19903     EVT OpVT = LHS.getValueType();
19904     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19905         (OpVT.getVectorElementType() == MVT::i8 ||
19906          OpVT.getVectorElementType() == MVT::i16)) {
19907       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19908       DCI.AddToWorklist(Cond.getNode());
19909       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19910     }
19911   }
19912   // If this is a select between two integer constants, try to do some
19913   // optimizations.
19914   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19915     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19916       // Don't do this for crazy integer types.
19917       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19918         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19919         // so that TrueC (the true value) is larger than FalseC.
19920         bool NeedsCondInvert = false;
19921
19922         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19923             // Efficiently invertible.
19924             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19925              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19926               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19927           NeedsCondInvert = true;
19928           std::swap(TrueC, FalseC);
19929         }
19930
19931         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19932         if (FalseC->getAPIntValue() == 0 &&
19933             TrueC->getAPIntValue().isPowerOf2()) {
19934           if (NeedsCondInvert) // Invert the condition if needed.
19935             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19936                                DAG.getConstant(1, Cond.getValueType()));
19937
19938           // Zero extend the condition if needed.
19939           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19940
19941           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19942           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19943                              DAG.getConstant(ShAmt, MVT::i8));
19944         }
19945
19946         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19947         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19948           if (NeedsCondInvert) // Invert the condition if needed.
19949             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19950                                DAG.getConstant(1, Cond.getValueType()));
19951
19952           // Zero extend the condition if needed.
19953           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19954                              FalseC->getValueType(0), Cond);
19955           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19956                              SDValue(FalseC, 0));
19957         }
19958
19959         // Optimize cases that will turn into an LEA instruction.  This requires
19960         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19961         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19962           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19963           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19964
19965           bool isFastMultiplier = false;
19966           if (Diff < 10) {
19967             switch ((unsigned char)Diff) {
19968               default: break;
19969               case 1:  // result = add base, cond
19970               case 2:  // result = lea base(    , cond*2)
19971               case 3:  // result = lea base(cond, cond*2)
19972               case 4:  // result = lea base(    , cond*4)
19973               case 5:  // result = lea base(cond, cond*4)
19974               case 8:  // result = lea base(    , cond*8)
19975               case 9:  // result = lea base(cond, cond*8)
19976                 isFastMultiplier = true;
19977                 break;
19978             }
19979           }
19980
19981           if (isFastMultiplier) {
19982             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19983             if (NeedsCondInvert) // Invert the condition if needed.
19984               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19985                                  DAG.getConstant(1, Cond.getValueType()));
19986
19987             // Zero extend the condition if needed.
19988             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19989                                Cond);
19990             // Scale the condition by the difference.
19991             if (Diff != 1)
19992               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19993                                  DAG.getConstant(Diff, Cond.getValueType()));
19994
19995             // Add the base if non-zero.
19996             if (FalseC->getAPIntValue() != 0)
19997               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19998                                  SDValue(FalseC, 0));
19999             return Cond;
20000           }
20001         }
20002       }
20003   }
20004
20005   // Canonicalize max and min:
20006   // (x > y) ? x : y -> (x >= y) ? x : y
20007   // (x < y) ? x : y -> (x <= y) ? x : y
20008   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20009   // the need for an extra compare
20010   // against zero. e.g.
20011   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20012   // subl   %esi, %edi
20013   // testl  %edi, %edi
20014   // movl   $0, %eax
20015   // cmovgl %edi, %eax
20016   // =>
20017   // xorl   %eax, %eax
20018   // subl   %esi, $edi
20019   // cmovsl %eax, %edi
20020   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20021       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20022       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20023     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20024     switch (CC) {
20025     default: break;
20026     case ISD::SETLT:
20027     case ISD::SETGT: {
20028       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20029       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20030                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20031       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20032     }
20033     }
20034   }
20035
20036   // Early exit check
20037   if (!TLI.isTypeLegal(VT))
20038     return SDValue();
20039
20040   // Match VSELECTs into subs with unsigned saturation.
20041   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20042       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20043       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20044        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20045     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20046
20047     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20048     // left side invert the predicate to simplify logic below.
20049     SDValue Other;
20050     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20051       Other = RHS;
20052       CC = ISD::getSetCCInverse(CC, true);
20053     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20054       Other = LHS;
20055     }
20056
20057     if (Other.getNode() && Other->getNumOperands() == 2 &&
20058         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20059       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20060       SDValue CondRHS = Cond->getOperand(1);
20061
20062       // Look for a general sub with unsigned saturation first.
20063       // x >= y ? x-y : 0 --> subus x, y
20064       // x >  y ? x-y : 0 --> subus x, y
20065       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20066           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20067         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20068
20069       // If the RHS is a constant we have to reverse the const canonicalization.
20070       // x > C-1 ? x+-C : 0 --> subus x, C
20071       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20072           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
20073         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20074         if (CondRHS.getConstantOperandVal(0) == -A-1)
20075           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
20076                              DAG.getConstant(-A, VT));
20077       }
20078
20079       // Another special case: If C was a sign bit, the sub has been
20080       // canonicalized into a xor.
20081       // FIXME: Would it be better to use computeKnownBits to determine whether
20082       //        it's safe to decanonicalize the xor?
20083       // x s< 0 ? x^C : 0 --> subus x, C
20084       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20085           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20086           isSplatVector(OpRHS.getNode())) {
20087         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20088         if (A.isSignBit())
20089           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20090       }
20091     }
20092   }
20093
20094   // Try to match a min/max vector operation.
20095   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20096     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20097     unsigned Opc = ret.first;
20098     bool NeedSplit = ret.second;
20099
20100     if (Opc && NeedSplit) {
20101       unsigned NumElems = VT.getVectorNumElements();
20102       // Extract the LHS vectors
20103       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20104       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20105
20106       // Extract the RHS vectors
20107       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20108       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20109
20110       // Create min/max for each subvector
20111       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20112       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20113
20114       // Merge the result
20115       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20116     } else if (Opc)
20117       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20118   }
20119
20120   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20121   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20122       // Check if SETCC has already been promoted
20123       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20124       // Check that condition value type matches vselect operand type
20125       CondVT == VT) { 
20126
20127     assert(Cond.getValueType().isVector() &&
20128            "vector select expects a vector selector!");
20129
20130     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20131     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20132
20133     if (!TValIsAllOnes && !FValIsAllZeros) {
20134       // Try invert the condition if true value is not all 1s and false value
20135       // is not all 0s.
20136       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20137       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20138
20139       if (TValIsAllZeros || FValIsAllOnes) {
20140         SDValue CC = Cond.getOperand(2);
20141         ISD::CondCode NewCC =
20142           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20143                                Cond.getOperand(0).getValueType().isInteger());
20144         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20145         std::swap(LHS, RHS);
20146         TValIsAllOnes = FValIsAllOnes;
20147         FValIsAllZeros = TValIsAllZeros;
20148       }
20149     }
20150
20151     if (TValIsAllOnes || FValIsAllZeros) {
20152       SDValue Ret;
20153
20154       if (TValIsAllOnes && FValIsAllZeros)
20155         Ret = Cond;
20156       else if (TValIsAllOnes)
20157         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20158                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20159       else if (FValIsAllZeros)
20160         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20161                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20162
20163       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20164     }
20165   }
20166
20167   // Try to fold this VSELECT into a MOVSS/MOVSD
20168   if (N->getOpcode() == ISD::VSELECT &&
20169       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20170     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20171         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20172       bool CanFold = false;
20173       unsigned NumElems = Cond.getNumOperands();
20174       SDValue A = LHS;
20175       SDValue B = RHS;
20176       
20177       if (isZero(Cond.getOperand(0))) {
20178         CanFold = true;
20179
20180         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20181         // fold (vselect <0,-1> -> (movsd A, B)
20182         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20183           CanFold = isAllOnes(Cond.getOperand(i));
20184       } else if (isAllOnes(Cond.getOperand(0))) {
20185         CanFold = true;
20186         std::swap(A, B);
20187
20188         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20189         // fold (vselect <-1,0> -> (movsd B, A)
20190         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20191           CanFold = isZero(Cond.getOperand(i));
20192       }
20193
20194       if (CanFold) {
20195         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20196           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20197         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20198       }
20199
20200       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20201         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20202         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20203         //                             (v2i64 (bitcast B)))))
20204         //
20205         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20206         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20207         //                             (v2f64 (bitcast B)))))
20208         //
20209         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20210         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20211         //                             (v2i64 (bitcast A)))))
20212         //
20213         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20214         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20215         //                             (v2f64 (bitcast A)))))
20216
20217         CanFold = (isZero(Cond.getOperand(0)) &&
20218                    isZero(Cond.getOperand(1)) &&
20219                    isAllOnes(Cond.getOperand(2)) &&
20220                    isAllOnes(Cond.getOperand(3)));
20221
20222         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20223             isAllOnes(Cond.getOperand(1)) &&
20224             isZero(Cond.getOperand(2)) &&
20225             isZero(Cond.getOperand(3))) {
20226           CanFold = true;
20227           std::swap(LHS, RHS);
20228         }
20229
20230         if (CanFold) {
20231           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20232           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20233           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20234           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20235                                                 NewB, DAG);
20236           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20237         }
20238       }
20239     }
20240   }
20241
20242   // If we know that this node is legal then we know that it is going to be
20243   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20244   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20245   // to simplify previous instructions.
20246   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20247       !DCI.isBeforeLegalize() &&
20248       // We explicitly check against v8i16 and v16i16 because, although
20249       // they're marked as Custom, they might only be legal when Cond is a
20250       // build_vector of constants. This will be taken care in a later
20251       // condition.
20252       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20253        VT != MVT::v8i16)) {
20254     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20255
20256     // Don't optimize vector selects that map to mask-registers.
20257     if (BitWidth == 1)
20258       return SDValue();
20259
20260     // Check all uses of that condition operand to check whether it will be
20261     // consumed by non-BLEND instructions, which may depend on all bits are set
20262     // properly.
20263     for (SDNode::use_iterator I = Cond->use_begin(),
20264                               E = Cond->use_end(); I != E; ++I)
20265       if (I->getOpcode() != ISD::VSELECT)
20266         // TODO: Add other opcodes eventually lowered into BLEND.
20267         return SDValue();
20268
20269     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20270     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20271
20272     APInt KnownZero, KnownOne;
20273     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20274                                           DCI.isBeforeLegalizeOps());
20275     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20276         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20277       DCI.CommitTargetLoweringOpt(TLO);
20278   }
20279
20280   // We should generate an X86ISD::BLENDI from a vselect if its argument
20281   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20282   // constants. This specific pattern gets generated when we split a
20283   // selector for a 512 bit vector in a machine without AVX512 (but with
20284   // 256-bit vectors), during legalization:
20285   //
20286   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20287   //
20288   // Iff we find this pattern and the build_vectors are built from
20289   // constants, we translate the vselect into a shuffle_vector that we
20290   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20291   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20292     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20293     if (Shuffle.getNode())
20294       return Shuffle;
20295   }
20296
20297   return SDValue();
20298 }
20299
20300 // Check whether a boolean test is testing a boolean value generated by
20301 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20302 // code.
20303 //
20304 // Simplify the following patterns:
20305 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20306 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20307 // to (Op EFLAGS Cond)
20308 //
20309 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20310 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20311 // to (Op EFLAGS !Cond)
20312 //
20313 // where Op could be BRCOND or CMOV.
20314 //
20315 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20316   // Quit if not CMP and SUB with its value result used.
20317   if (Cmp.getOpcode() != X86ISD::CMP &&
20318       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20319       return SDValue();
20320
20321   // Quit if not used as a boolean value.
20322   if (CC != X86::COND_E && CC != X86::COND_NE)
20323     return SDValue();
20324
20325   // Check CMP operands. One of them should be 0 or 1 and the other should be
20326   // an SetCC or extended from it.
20327   SDValue Op1 = Cmp.getOperand(0);
20328   SDValue Op2 = Cmp.getOperand(1);
20329
20330   SDValue SetCC;
20331   const ConstantSDNode* C = nullptr;
20332   bool needOppositeCond = (CC == X86::COND_E);
20333   bool checkAgainstTrue = false; // Is it a comparison against 1?
20334
20335   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20336     SetCC = Op2;
20337   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20338     SetCC = Op1;
20339   else // Quit if all operands are not constants.
20340     return SDValue();
20341
20342   if (C->getZExtValue() == 1) {
20343     needOppositeCond = !needOppositeCond;
20344     checkAgainstTrue = true;
20345   } else if (C->getZExtValue() != 0)
20346     // Quit if the constant is neither 0 or 1.
20347     return SDValue();
20348
20349   bool truncatedToBoolWithAnd = false;
20350   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20351   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20352          SetCC.getOpcode() == ISD::TRUNCATE ||
20353          SetCC.getOpcode() == ISD::AND) {
20354     if (SetCC.getOpcode() == ISD::AND) {
20355       int OpIdx = -1;
20356       ConstantSDNode *CS;
20357       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20358           CS->getZExtValue() == 1)
20359         OpIdx = 1;
20360       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20361           CS->getZExtValue() == 1)
20362         OpIdx = 0;
20363       if (OpIdx == -1)
20364         break;
20365       SetCC = SetCC.getOperand(OpIdx);
20366       truncatedToBoolWithAnd = true;
20367     } else
20368       SetCC = SetCC.getOperand(0);
20369   }
20370
20371   switch (SetCC.getOpcode()) {
20372   case X86ISD::SETCC_CARRY:
20373     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20374     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20375     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20376     // truncated to i1 using 'and'.
20377     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20378       break;
20379     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20380            "Invalid use of SETCC_CARRY!");
20381     // FALL THROUGH
20382   case X86ISD::SETCC:
20383     // Set the condition code or opposite one if necessary.
20384     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20385     if (needOppositeCond)
20386       CC = X86::GetOppositeBranchCondition(CC);
20387     return SetCC.getOperand(1);
20388   case X86ISD::CMOV: {
20389     // Check whether false/true value has canonical one, i.e. 0 or 1.
20390     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20391     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20392     // Quit if true value is not a constant.
20393     if (!TVal)
20394       return SDValue();
20395     // Quit if false value is not a constant.
20396     if (!FVal) {
20397       SDValue Op = SetCC.getOperand(0);
20398       // Skip 'zext' or 'trunc' node.
20399       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20400           Op.getOpcode() == ISD::TRUNCATE)
20401         Op = Op.getOperand(0);
20402       // A special case for rdrand/rdseed, where 0 is set if false cond is
20403       // found.
20404       if ((Op.getOpcode() != X86ISD::RDRAND &&
20405            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20406         return SDValue();
20407     }
20408     // Quit if false value is not the constant 0 or 1.
20409     bool FValIsFalse = true;
20410     if (FVal && FVal->getZExtValue() != 0) {
20411       if (FVal->getZExtValue() != 1)
20412         return SDValue();
20413       // If FVal is 1, opposite cond is needed.
20414       needOppositeCond = !needOppositeCond;
20415       FValIsFalse = false;
20416     }
20417     // Quit if TVal is not the constant opposite of FVal.
20418     if (FValIsFalse && TVal->getZExtValue() != 1)
20419       return SDValue();
20420     if (!FValIsFalse && TVal->getZExtValue() != 0)
20421       return SDValue();
20422     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20423     if (needOppositeCond)
20424       CC = X86::GetOppositeBranchCondition(CC);
20425     return SetCC.getOperand(3);
20426   }
20427   }
20428
20429   return SDValue();
20430 }
20431
20432 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20433 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20434                                   TargetLowering::DAGCombinerInfo &DCI,
20435                                   const X86Subtarget *Subtarget) {
20436   SDLoc DL(N);
20437
20438   // If the flag operand isn't dead, don't touch this CMOV.
20439   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20440     return SDValue();
20441
20442   SDValue FalseOp = N->getOperand(0);
20443   SDValue TrueOp = N->getOperand(1);
20444   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20445   SDValue Cond = N->getOperand(3);
20446
20447   if (CC == X86::COND_E || CC == X86::COND_NE) {
20448     switch (Cond.getOpcode()) {
20449     default: break;
20450     case X86ISD::BSR:
20451     case X86ISD::BSF:
20452       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20453       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20454         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20455     }
20456   }
20457
20458   SDValue Flags;
20459
20460   Flags = checkBoolTestSetCCCombine(Cond, CC);
20461   if (Flags.getNode() &&
20462       // Extra check as FCMOV only supports a subset of X86 cond.
20463       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20464     SDValue Ops[] = { FalseOp, TrueOp,
20465                       DAG.getConstant(CC, MVT::i8), Flags };
20466     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20467   }
20468
20469   // If this is a select between two integer constants, try to do some
20470   // optimizations.  Note that the operands are ordered the opposite of SELECT
20471   // operands.
20472   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20473     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20474       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20475       // larger than FalseC (the false value).
20476       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20477         CC = X86::GetOppositeBranchCondition(CC);
20478         std::swap(TrueC, FalseC);
20479         std::swap(TrueOp, FalseOp);
20480       }
20481
20482       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20483       // This is efficient for any integer data type (including i8/i16) and
20484       // shift amount.
20485       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20486         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20487                            DAG.getConstant(CC, MVT::i8), Cond);
20488
20489         // Zero extend the condition if needed.
20490         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20491
20492         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20493         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20494                            DAG.getConstant(ShAmt, MVT::i8));
20495         if (N->getNumValues() == 2)  // Dead flag value?
20496           return DCI.CombineTo(N, Cond, SDValue());
20497         return Cond;
20498       }
20499
20500       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20501       // for any integer data type, including i8/i16.
20502       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20503         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20504                            DAG.getConstant(CC, MVT::i8), Cond);
20505
20506         // Zero extend the condition if needed.
20507         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20508                            FalseC->getValueType(0), Cond);
20509         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20510                            SDValue(FalseC, 0));
20511
20512         if (N->getNumValues() == 2)  // Dead flag value?
20513           return DCI.CombineTo(N, Cond, SDValue());
20514         return Cond;
20515       }
20516
20517       // Optimize cases that will turn into an LEA instruction.  This requires
20518       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20519       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20520         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20521         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20522
20523         bool isFastMultiplier = false;
20524         if (Diff < 10) {
20525           switch ((unsigned char)Diff) {
20526           default: break;
20527           case 1:  // result = add base, cond
20528           case 2:  // result = lea base(    , cond*2)
20529           case 3:  // result = lea base(cond, cond*2)
20530           case 4:  // result = lea base(    , cond*4)
20531           case 5:  // result = lea base(cond, cond*4)
20532           case 8:  // result = lea base(    , cond*8)
20533           case 9:  // result = lea base(cond, cond*8)
20534             isFastMultiplier = true;
20535             break;
20536           }
20537         }
20538
20539         if (isFastMultiplier) {
20540           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20541           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20542                              DAG.getConstant(CC, MVT::i8), Cond);
20543           // Zero extend the condition if needed.
20544           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20545                              Cond);
20546           // Scale the condition by the difference.
20547           if (Diff != 1)
20548             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20549                                DAG.getConstant(Diff, Cond.getValueType()));
20550
20551           // Add the base if non-zero.
20552           if (FalseC->getAPIntValue() != 0)
20553             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20554                                SDValue(FalseC, 0));
20555           if (N->getNumValues() == 2)  // Dead flag value?
20556             return DCI.CombineTo(N, Cond, SDValue());
20557           return Cond;
20558         }
20559       }
20560     }
20561   }
20562
20563   // Handle these cases:
20564   //   (select (x != c), e, c) -> select (x != c), e, x),
20565   //   (select (x == c), c, e) -> select (x == c), x, e)
20566   // where the c is an integer constant, and the "select" is the combination
20567   // of CMOV and CMP.
20568   //
20569   // The rationale for this change is that the conditional-move from a constant
20570   // needs two instructions, however, conditional-move from a register needs
20571   // only one instruction.
20572   //
20573   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20574   //  some instruction-combining opportunities. This opt needs to be
20575   //  postponed as late as possible.
20576   //
20577   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20578     // the DCI.xxxx conditions are provided to postpone the optimization as
20579     // late as possible.
20580
20581     ConstantSDNode *CmpAgainst = nullptr;
20582     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20583         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20584         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20585
20586       if (CC == X86::COND_NE &&
20587           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20588         CC = X86::GetOppositeBranchCondition(CC);
20589         std::swap(TrueOp, FalseOp);
20590       }
20591
20592       if (CC == X86::COND_E &&
20593           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20594         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20595                           DAG.getConstant(CC, MVT::i8), Cond };
20596         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20597       }
20598     }
20599   }
20600
20601   return SDValue();
20602 }
20603
20604 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20605                                                 const X86Subtarget *Subtarget) {
20606   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20607   switch (IntNo) {
20608   default: return SDValue();
20609   // SSE/AVX/AVX2 blend intrinsics.
20610   case Intrinsic::x86_avx2_pblendvb:
20611   case Intrinsic::x86_avx2_pblendw:
20612   case Intrinsic::x86_avx2_pblendd_128:
20613   case Intrinsic::x86_avx2_pblendd_256:
20614     // Don't try to simplify this intrinsic if we don't have AVX2.
20615     if (!Subtarget->hasAVX2())
20616       return SDValue();
20617     // FALL-THROUGH
20618   case Intrinsic::x86_avx_blend_pd_256:
20619   case Intrinsic::x86_avx_blend_ps_256:
20620   case Intrinsic::x86_avx_blendv_pd_256:
20621   case Intrinsic::x86_avx_blendv_ps_256:
20622     // Don't try to simplify this intrinsic if we don't have AVX.
20623     if (!Subtarget->hasAVX())
20624       return SDValue();
20625     // FALL-THROUGH
20626   case Intrinsic::x86_sse41_pblendw:
20627   case Intrinsic::x86_sse41_blendpd:
20628   case Intrinsic::x86_sse41_blendps:
20629   case Intrinsic::x86_sse41_blendvps:
20630   case Intrinsic::x86_sse41_blendvpd:
20631   case Intrinsic::x86_sse41_pblendvb: {
20632     SDValue Op0 = N->getOperand(1);
20633     SDValue Op1 = N->getOperand(2);
20634     SDValue Mask = N->getOperand(3);
20635
20636     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20637     if (!Subtarget->hasSSE41())
20638       return SDValue();
20639
20640     // fold (blend A, A, Mask) -> A
20641     if (Op0 == Op1)
20642       return Op0;
20643     // fold (blend A, B, allZeros) -> A
20644     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20645       return Op0;
20646     // fold (blend A, B, allOnes) -> B
20647     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20648       return Op1;
20649     
20650     // Simplify the case where the mask is a constant i32 value.
20651     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20652       if (C->isNullValue())
20653         return Op0;
20654       if (C->isAllOnesValue())
20655         return Op1;
20656     }
20657
20658     return SDValue();
20659   }
20660
20661   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20662   case Intrinsic::x86_sse2_psrai_w:
20663   case Intrinsic::x86_sse2_psrai_d:
20664   case Intrinsic::x86_avx2_psrai_w:
20665   case Intrinsic::x86_avx2_psrai_d:
20666   case Intrinsic::x86_sse2_psra_w:
20667   case Intrinsic::x86_sse2_psra_d:
20668   case Intrinsic::x86_avx2_psra_w:
20669   case Intrinsic::x86_avx2_psra_d: {
20670     SDValue Op0 = N->getOperand(1);
20671     SDValue Op1 = N->getOperand(2);
20672     EVT VT = Op0.getValueType();
20673     assert(VT.isVector() && "Expected a vector type!");
20674
20675     if (isa<BuildVectorSDNode>(Op1))
20676       Op1 = Op1.getOperand(0);
20677
20678     if (!isa<ConstantSDNode>(Op1))
20679       return SDValue();
20680
20681     EVT SVT = VT.getVectorElementType();
20682     unsigned SVTBits = SVT.getSizeInBits();
20683
20684     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20685     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20686     uint64_t ShAmt = C.getZExtValue();
20687
20688     // Don't try to convert this shift into a ISD::SRA if the shift
20689     // count is bigger than or equal to the element size.
20690     if (ShAmt >= SVTBits)
20691       return SDValue();
20692
20693     // Trivial case: if the shift count is zero, then fold this
20694     // into the first operand.
20695     if (ShAmt == 0)
20696       return Op0;
20697
20698     // Replace this packed shift intrinsic with a target independent
20699     // shift dag node.
20700     SDValue Splat = DAG.getConstant(C, VT);
20701     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20702   }
20703   }
20704 }
20705
20706 /// PerformMulCombine - Optimize a single multiply with constant into two
20707 /// in order to implement it with two cheaper instructions, e.g.
20708 /// LEA + SHL, LEA + LEA.
20709 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20710                                  TargetLowering::DAGCombinerInfo &DCI) {
20711   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20712     return SDValue();
20713
20714   EVT VT = N->getValueType(0);
20715   if (VT != MVT::i64)
20716     return SDValue();
20717
20718   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20719   if (!C)
20720     return SDValue();
20721   uint64_t MulAmt = C->getZExtValue();
20722   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20723     return SDValue();
20724
20725   uint64_t MulAmt1 = 0;
20726   uint64_t MulAmt2 = 0;
20727   if ((MulAmt % 9) == 0) {
20728     MulAmt1 = 9;
20729     MulAmt2 = MulAmt / 9;
20730   } else if ((MulAmt % 5) == 0) {
20731     MulAmt1 = 5;
20732     MulAmt2 = MulAmt / 5;
20733   } else if ((MulAmt % 3) == 0) {
20734     MulAmt1 = 3;
20735     MulAmt2 = MulAmt / 3;
20736   }
20737   if (MulAmt2 &&
20738       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20739     SDLoc DL(N);
20740
20741     if (isPowerOf2_64(MulAmt2) &&
20742         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20743       // If second multiplifer is pow2, issue it first. We want the multiply by
20744       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20745       // is an add.
20746       std::swap(MulAmt1, MulAmt2);
20747
20748     SDValue NewMul;
20749     if (isPowerOf2_64(MulAmt1))
20750       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20751                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20752     else
20753       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20754                            DAG.getConstant(MulAmt1, VT));
20755
20756     if (isPowerOf2_64(MulAmt2))
20757       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20758                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20759     else
20760       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20761                            DAG.getConstant(MulAmt2, VT));
20762
20763     // Do not add new nodes to DAG combiner worklist.
20764     DCI.CombineTo(N, NewMul, false);
20765   }
20766   return SDValue();
20767 }
20768
20769 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20770   SDValue N0 = N->getOperand(0);
20771   SDValue N1 = N->getOperand(1);
20772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20773   EVT VT = N0.getValueType();
20774
20775   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20776   // since the result of setcc_c is all zero's or all ones.
20777   if (VT.isInteger() && !VT.isVector() &&
20778       N1C && N0.getOpcode() == ISD::AND &&
20779       N0.getOperand(1).getOpcode() == ISD::Constant) {
20780     SDValue N00 = N0.getOperand(0);
20781     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20782         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20783           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20784          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20785       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20786       APInt ShAmt = N1C->getAPIntValue();
20787       Mask = Mask.shl(ShAmt);
20788       if (Mask != 0)
20789         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20790                            N00, DAG.getConstant(Mask, VT));
20791     }
20792   }
20793
20794   // Hardware support for vector shifts is sparse which makes us scalarize the
20795   // vector operations in many cases. Also, on sandybridge ADD is faster than
20796   // shl.
20797   // (shl V, 1) -> add V,V
20798   if (isSplatVector(N1.getNode())) {
20799     assert(N0.getValueType().isVector() && "Invalid vector shift type");
20800     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20801     // We shift all of the values by one. In many cases we do not have
20802     // hardware support for this operation. This is better expressed as an ADD
20803     // of two values.
20804     if (N1C && (1 == N1C->getZExtValue())) {
20805       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20806     }
20807   }
20808
20809   return SDValue();
20810 }
20811
20812 /// \brief Returns a vector of 0s if the node in input is a vector logical
20813 /// shift by a constant amount which is known to be bigger than or equal
20814 /// to the vector element size in bits.
20815 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20816                                       const X86Subtarget *Subtarget) {
20817   EVT VT = N->getValueType(0);
20818
20819   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20820       (!Subtarget->hasInt256() ||
20821        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20822     return SDValue();
20823
20824   SDValue Amt = N->getOperand(1);
20825   SDLoc DL(N);
20826   if (isSplatVector(Amt.getNode())) {
20827     SDValue SclrAmt = Amt->getOperand(0);
20828     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20829       APInt ShiftAmt = C->getAPIntValue();
20830       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20831
20832       // SSE2/AVX2 logical shifts always return a vector of 0s
20833       // if the shift amount is bigger than or equal to
20834       // the element size. The constant shift amount will be
20835       // encoded as a 8-bit immediate.
20836       if (ShiftAmt.trunc(8).uge(MaxAmount))
20837         return getZeroVector(VT, Subtarget, DAG, DL);
20838     }
20839   }
20840
20841   return SDValue();
20842 }
20843
20844 /// PerformShiftCombine - Combine shifts.
20845 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20846                                    TargetLowering::DAGCombinerInfo &DCI,
20847                                    const X86Subtarget *Subtarget) {
20848   if (N->getOpcode() == ISD::SHL) {
20849     SDValue V = PerformSHLCombine(N, DAG);
20850     if (V.getNode()) return V;
20851   }
20852
20853   if (N->getOpcode() != ISD::SRA) {
20854     // Try to fold this logical shift into a zero vector.
20855     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20856     if (V.getNode()) return V;
20857   }
20858
20859   return SDValue();
20860 }
20861
20862 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20863 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20864 // and friends.  Likewise for OR -> CMPNEQSS.
20865 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20866                             TargetLowering::DAGCombinerInfo &DCI,
20867                             const X86Subtarget *Subtarget) {
20868   unsigned opcode;
20869
20870   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20871   // we're requiring SSE2 for both.
20872   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20873     SDValue N0 = N->getOperand(0);
20874     SDValue N1 = N->getOperand(1);
20875     SDValue CMP0 = N0->getOperand(1);
20876     SDValue CMP1 = N1->getOperand(1);
20877     SDLoc DL(N);
20878
20879     // The SETCCs should both refer to the same CMP.
20880     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20881       return SDValue();
20882
20883     SDValue CMP00 = CMP0->getOperand(0);
20884     SDValue CMP01 = CMP0->getOperand(1);
20885     EVT     VT    = CMP00.getValueType();
20886
20887     if (VT == MVT::f32 || VT == MVT::f64) {
20888       bool ExpectingFlags = false;
20889       // Check for any users that want flags:
20890       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20891            !ExpectingFlags && UI != UE; ++UI)
20892         switch (UI->getOpcode()) {
20893         default:
20894         case ISD::BR_CC:
20895         case ISD::BRCOND:
20896         case ISD::SELECT:
20897           ExpectingFlags = true;
20898           break;
20899         case ISD::CopyToReg:
20900         case ISD::SIGN_EXTEND:
20901         case ISD::ZERO_EXTEND:
20902         case ISD::ANY_EXTEND:
20903           break;
20904         }
20905
20906       if (!ExpectingFlags) {
20907         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20908         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20909
20910         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20911           X86::CondCode tmp = cc0;
20912           cc0 = cc1;
20913           cc1 = tmp;
20914         }
20915
20916         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20917             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20918           // FIXME: need symbolic constants for these magic numbers.
20919           // See X86ATTInstPrinter.cpp:printSSECC().
20920           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20921           if (Subtarget->hasAVX512()) {
20922             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20923                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20924             if (N->getValueType(0) != MVT::i1)
20925               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20926                                  FSetCC);
20927             return FSetCC;
20928           }
20929           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20930                                               CMP00.getValueType(), CMP00, CMP01,
20931                                               DAG.getConstant(x86cc, MVT::i8));
20932
20933           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20934           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20935
20936           if (is64BitFP && !Subtarget->is64Bit()) {
20937             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20938             // 64-bit integer, since that's not a legal type. Since
20939             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20940             // bits, but can do this little dance to extract the lowest 32 bits
20941             // and work with those going forward.
20942             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20943                                            OnesOrZeroesF);
20944             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20945                                            Vector64);
20946             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20947                                         Vector32, DAG.getIntPtrConstant(0));
20948             IntVT = MVT::i32;
20949           }
20950
20951           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20952           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20953                                       DAG.getConstant(1, IntVT));
20954           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20955           return OneBitOfTruth;
20956         }
20957       }
20958     }
20959   }
20960   return SDValue();
20961 }
20962
20963 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20964 /// so it can be folded inside ANDNP.
20965 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20966   EVT VT = N->getValueType(0);
20967
20968   // Match direct AllOnes for 128 and 256-bit vectors
20969   if (ISD::isBuildVectorAllOnes(N))
20970     return true;
20971
20972   // Look through a bit convert.
20973   if (N->getOpcode() == ISD::BITCAST)
20974     N = N->getOperand(0).getNode();
20975
20976   // Sometimes the operand may come from a insert_subvector building a 256-bit
20977   // allones vector
20978   if (VT.is256BitVector() &&
20979       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20980     SDValue V1 = N->getOperand(0);
20981     SDValue V2 = N->getOperand(1);
20982
20983     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20984         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20985         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20986         ISD::isBuildVectorAllOnes(V2.getNode()))
20987       return true;
20988   }
20989
20990   return false;
20991 }
20992
20993 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20994 // register. In most cases we actually compare or select YMM-sized registers
20995 // and mixing the two types creates horrible code. This method optimizes
20996 // some of the transition sequences.
20997 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20998                                  TargetLowering::DAGCombinerInfo &DCI,
20999                                  const X86Subtarget *Subtarget) {
21000   EVT VT = N->getValueType(0);
21001   if (!VT.is256BitVector())
21002     return SDValue();
21003
21004   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21005           N->getOpcode() == ISD::ZERO_EXTEND ||
21006           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21007
21008   SDValue Narrow = N->getOperand(0);
21009   EVT NarrowVT = Narrow->getValueType(0);
21010   if (!NarrowVT.is128BitVector())
21011     return SDValue();
21012
21013   if (Narrow->getOpcode() != ISD::XOR &&
21014       Narrow->getOpcode() != ISD::AND &&
21015       Narrow->getOpcode() != ISD::OR)
21016     return SDValue();
21017
21018   SDValue N0  = Narrow->getOperand(0);
21019   SDValue N1  = Narrow->getOperand(1);
21020   SDLoc DL(Narrow);
21021
21022   // The Left side has to be a trunc.
21023   if (N0.getOpcode() != ISD::TRUNCATE)
21024     return SDValue();
21025
21026   // The type of the truncated inputs.
21027   EVT WideVT = N0->getOperand(0)->getValueType(0);
21028   if (WideVT != VT)
21029     return SDValue();
21030
21031   // The right side has to be a 'trunc' or a constant vector.
21032   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21033   bool RHSConst = (isSplatVector(N1.getNode()) &&
21034                    isa<ConstantSDNode>(N1->getOperand(0)));
21035   if (!RHSTrunc && !RHSConst)
21036     return SDValue();
21037
21038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21039
21040   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21041     return SDValue();
21042
21043   // Set N0 and N1 to hold the inputs to the new wide operation.
21044   N0 = N0->getOperand(0);
21045   if (RHSConst) {
21046     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21047                      N1->getOperand(0));
21048     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21049     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21050   } else if (RHSTrunc) {
21051     N1 = N1->getOperand(0);
21052   }
21053
21054   // Generate the wide operation.
21055   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21056   unsigned Opcode = N->getOpcode();
21057   switch (Opcode) {
21058   case ISD::ANY_EXTEND:
21059     return Op;
21060   case ISD::ZERO_EXTEND: {
21061     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21062     APInt Mask = APInt::getAllOnesValue(InBits);
21063     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21064     return DAG.getNode(ISD::AND, DL, VT,
21065                        Op, DAG.getConstant(Mask, VT));
21066   }
21067   case ISD::SIGN_EXTEND:
21068     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21069                        Op, DAG.getValueType(NarrowVT));
21070   default:
21071     llvm_unreachable("Unexpected opcode");
21072   }
21073 }
21074
21075 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21076                                  TargetLowering::DAGCombinerInfo &DCI,
21077                                  const X86Subtarget *Subtarget) {
21078   EVT VT = N->getValueType(0);
21079   if (DCI.isBeforeLegalizeOps())
21080     return SDValue();
21081
21082   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21083   if (R.getNode())
21084     return R;
21085
21086   // Create BEXTR instructions
21087   // BEXTR is ((X >> imm) & (2**size-1))
21088   if (VT == MVT::i32 || VT == MVT::i64) {
21089     SDValue N0 = N->getOperand(0);
21090     SDValue N1 = N->getOperand(1);
21091     SDLoc DL(N);
21092
21093     // Check for BEXTR.
21094     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21095         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21096       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21097       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21098       if (MaskNode && ShiftNode) {
21099         uint64_t Mask = MaskNode->getZExtValue();
21100         uint64_t Shift = ShiftNode->getZExtValue();
21101         if (isMask_64(Mask)) {
21102           uint64_t MaskSize = CountPopulation_64(Mask);
21103           if (Shift + MaskSize <= VT.getSizeInBits())
21104             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21105                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21106         }
21107       }
21108     } // BEXTR
21109
21110     return SDValue();
21111   }
21112
21113   // Want to form ANDNP nodes:
21114   // 1) In the hopes of then easily combining them with OR and AND nodes
21115   //    to form PBLEND/PSIGN.
21116   // 2) To match ANDN packed intrinsics
21117   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21118     return SDValue();
21119
21120   SDValue N0 = N->getOperand(0);
21121   SDValue N1 = N->getOperand(1);
21122   SDLoc DL(N);
21123
21124   // Check LHS for vnot
21125   if (N0.getOpcode() == ISD::XOR &&
21126       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21127       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21128     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21129
21130   // Check RHS for vnot
21131   if (N1.getOpcode() == ISD::XOR &&
21132       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21133       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21134     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21135
21136   return SDValue();
21137 }
21138
21139 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21140                                 TargetLowering::DAGCombinerInfo &DCI,
21141                                 const X86Subtarget *Subtarget) {
21142   if (DCI.isBeforeLegalizeOps())
21143     return SDValue();
21144
21145   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21146   if (R.getNode())
21147     return R;
21148
21149   SDValue N0 = N->getOperand(0);
21150   SDValue N1 = N->getOperand(1);
21151   EVT VT = N->getValueType(0);
21152
21153   // look for psign/blend
21154   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21155     if (!Subtarget->hasSSSE3() ||
21156         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21157       return SDValue();
21158
21159     // Canonicalize pandn to RHS
21160     if (N0.getOpcode() == X86ISD::ANDNP)
21161       std::swap(N0, N1);
21162     // or (and (m, y), (pandn m, x))
21163     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21164       SDValue Mask = N1.getOperand(0);
21165       SDValue X    = N1.getOperand(1);
21166       SDValue Y;
21167       if (N0.getOperand(0) == Mask)
21168         Y = N0.getOperand(1);
21169       if (N0.getOperand(1) == Mask)
21170         Y = N0.getOperand(0);
21171
21172       // Check to see if the mask appeared in both the AND and ANDNP and
21173       if (!Y.getNode())
21174         return SDValue();
21175
21176       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21177       // Look through mask bitcast.
21178       if (Mask.getOpcode() == ISD::BITCAST)
21179         Mask = Mask.getOperand(0);
21180       if (X.getOpcode() == ISD::BITCAST)
21181         X = X.getOperand(0);
21182       if (Y.getOpcode() == ISD::BITCAST)
21183         Y = Y.getOperand(0);
21184
21185       EVT MaskVT = Mask.getValueType();
21186
21187       // Validate that the Mask operand is a vector sra node.
21188       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21189       // there is no psrai.b
21190       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21191       unsigned SraAmt = ~0;
21192       if (Mask.getOpcode() == ISD::SRA) {
21193         SDValue Amt = Mask.getOperand(1);
21194         if (isSplatVector(Amt.getNode())) {
21195           SDValue SclrAmt = Amt->getOperand(0);
21196           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
21197             SraAmt = C->getZExtValue();
21198         }
21199       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21200         SDValue SraC = Mask.getOperand(1);
21201         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21202       }
21203       if ((SraAmt + 1) != EltBits)
21204         return SDValue();
21205
21206       SDLoc DL(N);
21207
21208       // Now we know we at least have a plendvb with the mask val.  See if
21209       // we can form a psignb/w/d.
21210       // psign = x.type == y.type == mask.type && y = sub(0, x);
21211       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21212           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21213           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21214         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21215                "Unsupported VT for PSIGN");
21216         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21217         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21218       }
21219       // PBLENDVB only available on SSE 4.1
21220       if (!Subtarget->hasSSE41())
21221         return SDValue();
21222
21223       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21224
21225       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21226       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21227       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21228       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21229       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21230     }
21231   }
21232
21233   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21234     return SDValue();
21235
21236   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21237   MachineFunction &MF = DAG.getMachineFunction();
21238   bool OptForSize = MF.getFunction()->getAttributes().
21239     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21240
21241   // SHLD/SHRD instructions have lower register pressure, but on some
21242   // platforms they have higher latency than the equivalent
21243   // series of shifts/or that would otherwise be generated.
21244   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21245   // have higher latencies and we are not optimizing for size.
21246   if (!OptForSize && Subtarget->isSHLDSlow())
21247     return SDValue();
21248
21249   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21250     std::swap(N0, N1);
21251   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21252     return SDValue();
21253   if (!N0.hasOneUse() || !N1.hasOneUse())
21254     return SDValue();
21255
21256   SDValue ShAmt0 = N0.getOperand(1);
21257   if (ShAmt0.getValueType() != MVT::i8)
21258     return SDValue();
21259   SDValue ShAmt1 = N1.getOperand(1);
21260   if (ShAmt1.getValueType() != MVT::i8)
21261     return SDValue();
21262   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21263     ShAmt0 = ShAmt0.getOperand(0);
21264   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21265     ShAmt1 = ShAmt1.getOperand(0);
21266
21267   SDLoc DL(N);
21268   unsigned Opc = X86ISD::SHLD;
21269   SDValue Op0 = N0.getOperand(0);
21270   SDValue Op1 = N1.getOperand(0);
21271   if (ShAmt0.getOpcode() == ISD::SUB) {
21272     Opc = X86ISD::SHRD;
21273     std::swap(Op0, Op1);
21274     std::swap(ShAmt0, ShAmt1);
21275   }
21276
21277   unsigned Bits = VT.getSizeInBits();
21278   if (ShAmt1.getOpcode() == ISD::SUB) {
21279     SDValue Sum = ShAmt1.getOperand(0);
21280     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21281       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21282       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21283         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21284       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21285         return DAG.getNode(Opc, DL, VT,
21286                            Op0, Op1,
21287                            DAG.getNode(ISD::TRUNCATE, DL,
21288                                        MVT::i8, ShAmt0));
21289     }
21290   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21291     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21292     if (ShAmt0C &&
21293         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21294       return DAG.getNode(Opc, DL, VT,
21295                          N0.getOperand(0), N1.getOperand(0),
21296                          DAG.getNode(ISD::TRUNCATE, DL,
21297                                        MVT::i8, ShAmt0));
21298   }
21299
21300   return SDValue();
21301 }
21302
21303 // Generate NEG and CMOV for integer abs.
21304 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21305   EVT VT = N->getValueType(0);
21306
21307   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21308   // 8-bit integer abs to NEG and CMOV.
21309   if (VT.isInteger() && VT.getSizeInBits() == 8)
21310     return SDValue();
21311
21312   SDValue N0 = N->getOperand(0);
21313   SDValue N1 = N->getOperand(1);
21314   SDLoc DL(N);
21315
21316   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21317   // and change it to SUB and CMOV.
21318   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21319       N0.getOpcode() == ISD::ADD &&
21320       N0.getOperand(1) == N1 &&
21321       N1.getOpcode() == ISD::SRA &&
21322       N1.getOperand(0) == N0.getOperand(0))
21323     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21324       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21325         // Generate SUB & CMOV.
21326         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21327                                   DAG.getConstant(0, VT), N0.getOperand(0));
21328
21329         SDValue Ops[] = { N0.getOperand(0), Neg,
21330                           DAG.getConstant(X86::COND_GE, MVT::i8),
21331                           SDValue(Neg.getNode(), 1) };
21332         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21333       }
21334   return SDValue();
21335 }
21336
21337 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21338 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21339                                  TargetLowering::DAGCombinerInfo &DCI,
21340                                  const X86Subtarget *Subtarget) {
21341   if (DCI.isBeforeLegalizeOps())
21342     return SDValue();
21343
21344   if (Subtarget->hasCMov()) {
21345     SDValue RV = performIntegerAbsCombine(N, DAG);
21346     if (RV.getNode())
21347       return RV;
21348   }
21349
21350   return SDValue();
21351 }
21352
21353 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21354 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21355                                   TargetLowering::DAGCombinerInfo &DCI,
21356                                   const X86Subtarget *Subtarget) {
21357   LoadSDNode *Ld = cast<LoadSDNode>(N);
21358   EVT RegVT = Ld->getValueType(0);
21359   EVT MemVT = Ld->getMemoryVT();
21360   SDLoc dl(Ld);
21361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21362   unsigned RegSz = RegVT.getSizeInBits();
21363
21364   // On Sandybridge unaligned 256bit loads are inefficient.
21365   ISD::LoadExtType Ext = Ld->getExtensionType();
21366   unsigned Alignment = Ld->getAlignment();
21367   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21368   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21369       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21370     unsigned NumElems = RegVT.getVectorNumElements();
21371     if (NumElems < 2)
21372       return SDValue();
21373
21374     SDValue Ptr = Ld->getBasePtr();
21375     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21376
21377     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21378                                   NumElems/2);
21379     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21380                                 Ld->getPointerInfo(), Ld->isVolatile(),
21381                                 Ld->isNonTemporal(), Ld->isInvariant(),
21382                                 Alignment);
21383     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21384     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21385                                 Ld->getPointerInfo(), Ld->isVolatile(),
21386                                 Ld->isNonTemporal(), Ld->isInvariant(),
21387                                 std::min(16U, Alignment));
21388     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21389                              Load1.getValue(1),
21390                              Load2.getValue(1));
21391
21392     SDValue NewVec = DAG.getUNDEF(RegVT);
21393     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21394     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21395     return DCI.CombineTo(N, NewVec, TF, true);
21396   }
21397
21398   // If this is a vector EXT Load then attempt to optimize it using a
21399   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
21400   // expansion is still better than scalar code.
21401   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
21402   // emit a shuffle and a arithmetic shift.
21403   // TODO: It is possible to support ZExt by zeroing the undef values
21404   // during the shuffle phase or after the shuffle.
21405   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
21406       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
21407     assert(MemVT != RegVT && "Cannot extend to the same type");
21408     assert(MemVT.isVector() && "Must load a vector from memory");
21409
21410     unsigned NumElems = RegVT.getVectorNumElements();
21411     unsigned MemSz = MemVT.getSizeInBits();
21412     assert(RegSz > MemSz && "Register size must be greater than the mem size");
21413
21414     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
21415       return SDValue();
21416
21417     // All sizes must be a power of two.
21418     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
21419       return SDValue();
21420
21421     // Attempt to load the original value using scalar loads.
21422     // Find the largest scalar type that divides the total loaded size.
21423     MVT SclrLoadTy = MVT::i8;
21424     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21425          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21426       MVT Tp = (MVT::SimpleValueType)tp;
21427       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
21428         SclrLoadTy = Tp;
21429       }
21430     }
21431
21432     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21433     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
21434         (64 <= MemSz))
21435       SclrLoadTy = MVT::f64;
21436
21437     // Calculate the number of scalar loads that we need to perform
21438     // in order to load our vector from memory.
21439     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
21440     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
21441       return SDValue();
21442
21443     unsigned loadRegZize = RegSz;
21444     if (Ext == ISD::SEXTLOAD && RegSz == 256)
21445       loadRegZize /= 2;
21446
21447     // Represent our vector as a sequence of elements which are the
21448     // largest scalar that we can load.
21449     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
21450       loadRegZize/SclrLoadTy.getSizeInBits());
21451
21452     // Represent the data using the same element type that is stored in
21453     // memory. In practice, we ''widen'' MemVT.
21454     EVT WideVecVT =
21455           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21456                        loadRegZize/MemVT.getScalarType().getSizeInBits());
21457
21458     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
21459       "Invalid vector type");
21460
21461     // We can't shuffle using an illegal type.
21462     if (!TLI.isTypeLegal(WideVecVT))
21463       return SDValue();
21464
21465     SmallVector<SDValue, 8> Chains;
21466     SDValue Ptr = Ld->getBasePtr();
21467     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
21468                                         TLI.getPointerTy());
21469     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
21470
21471     for (unsigned i = 0; i < NumLoads; ++i) {
21472       // Perform a single load.
21473       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
21474                                        Ptr, Ld->getPointerInfo(),
21475                                        Ld->isVolatile(), Ld->isNonTemporal(),
21476                                        Ld->isInvariant(), Ld->getAlignment());
21477       Chains.push_back(ScalarLoad.getValue(1));
21478       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
21479       // another round of DAGCombining.
21480       if (i == 0)
21481         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21482       else
21483         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21484                           ScalarLoad, DAG.getIntPtrConstant(i));
21485
21486       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21487     }
21488
21489     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21490
21491     // Bitcast the loaded value to a vector of the original element type, in
21492     // the size of the target vector type.
21493     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21494     unsigned SizeRatio = RegSz/MemSz;
21495
21496     if (Ext == ISD::SEXTLOAD) {
21497       // If we have SSE4.1 we can directly emit a VSEXT node.
21498       if (Subtarget->hasSSE41()) {
21499         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21500         return DCI.CombineTo(N, Sext, TF, true);
21501       }
21502
21503       // Otherwise we'll shuffle the small elements in the high bits of the
21504       // larger type and perform an arithmetic shift. If the shift is not legal
21505       // it's better to scalarize.
21506       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21507         return SDValue();
21508
21509       // Redistribute the loaded elements into the different locations.
21510       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21511       for (unsigned i = 0; i != NumElems; ++i)
21512         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21513
21514       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21515                                            DAG.getUNDEF(WideVecVT),
21516                                            &ShuffleVec[0]);
21517
21518       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21519
21520       // Build the arithmetic shift.
21521       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21522                      MemVT.getVectorElementType().getSizeInBits();
21523       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21524                           DAG.getConstant(Amt, RegVT));
21525
21526       return DCI.CombineTo(N, Shuff, TF, true);
21527     }
21528
21529     // Redistribute the loaded elements into the different locations.
21530     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21531     for (unsigned i = 0; i != NumElems; ++i)
21532       ShuffleVec[i*SizeRatio] = i;
21533
21534     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21535                                          DAG.getUNDEF(WideVecVT),
21536                                          &ShuffleVec[0]);
21537
21538     // Bitcast to the requested type.
21539     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21540     // Replace the original load with the new sequence
21541     // and return the new chain.
21542     return DCI.CombineTo(N, Shuff, TF, true);
21543   }
21544
21545   return SDValue();
21546 }
21547
21548 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21549 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21550                                    const X86Subtarget *Subtarget) {
21551   StoreSDNode *St = cast<StoreSDNode>(N);
21552   EVT VT = St->getValue().getValueType();
21553   EVT StVT = St->getMemoryVT();
21554   SDLoc dl(St);
21555   SDValue StoredVal = St->getOperand(1);
21556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21557
21558   // If we are saving a concatenation of two XMM registers, perform two stores.
21559   // On Sandy Bridge, 256-bit memory operations are executed by two
21560   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21561   // memory  operation.
21562   unsigned Alignment = St->getAlignment();
21563   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21564   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21565       StVT == VT && !IsAligned) {
21566     unsigned NumElems = VT.getVectorNumElements();
21567     if (NumElems < 2)
21568       return SDValue();
21569
21570     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21571     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21572
21573     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21574     SDValue Ptr0 = St->getBasePtr();
21575     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21576
21577     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21578                                 St->getPointerInfo(), St->isVolatile(),
21579                                 St->isNonTemporal(), Alignment);
21580     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21581                                 St->getPointerInfo(), St->isVolatile(),
21582                                 St->isNonTemporal(),
21583                                 std::min(16U, Alignment));
21584     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21585   }
21586
21587   // Optimize trunc store (of multiple scalars) to shuffle and store.
21588   // First, pack all of the elements in one place. Next, store to memory
21589   // in fewer chunks.
21590   if (St->isTruncatingStore() && VT.isVector()) {
21591     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21592     unsigned NumElems = VT.getVectorNumElements();
21593     assert(StVT != VT && "Cannot truncate to the same type");
21594     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21595     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21596
21597     // From, To sizes and ElemCount must be pow of two
21598     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21599     // We are going to use the original vector elt for storing.
21600     // Accumulated smaller vector elements must be a multiple of the store size.
21601     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21602
21603     unsigned SizeRatio  = FromSz / ToSz;
21604
21605     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21606
21607     // Create a type on which we perform the shuffle
21608     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21609             StVT.getScalarType(), NumElems*SizeRatio);
21610
21611     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21612
21613     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21614     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21615     for (unsigned i = 0; i != NumElems; ++i)
21616       ShuffleVec[i] = i * SizeRatio;
21617
21618     // Can't shuffle using an illegal type.
21619     if (!TLI.isTypeLegal(WideVecVT))
21620       return SDValue();
21621
21622     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21623                                          DAG.getUNDEF(WideVecVT),
21624                                          &ShuffleVec[0]);
21625     // At this point all of the data is stored at the bottom of the
21626     // register. We now need to save it to mem.
21627
21628     // Find the largest store unit
21629     MVT StoreType = MVT::i8;
21630     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21631          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21632       MVT Tp = (MVT::SimpleValueType)tp;
21633       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21634         StoreType = Tp;
21635     }
21636
21637     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21638     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21639         (64 <= NumElems * ToSz))
21640       StoreType = MVT::f64;
21641
21642     // Bitcast the original vector into a vector of store-size units
21643     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21644             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21645     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21646     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21647     SmallVector<SDValue, 8> Chains;
21648     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21649                                         TLI.getPointerTy());
21650     SDValue Ptr = St->getBasePtr();
21651
21652     // Perform one or more big stores into memory.
21653     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21654       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21655                                    StoreType, ShuffWide,
21656                                    DAG.getIntPtrConstant(i));
21657       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21658                                 St->getPointerInfo(), St->isVolatile(),
21659                                 St->isNonTemporal(), St->getAlignment());
21660       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21661       Chains.push_back(Ch);
21662     }
21663
21664     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21665   }
21666
21667   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21668   // the FP state in cases where an emms may be missing.
21669   // A preferable solution to the general problem is to figure out the right
21670   // places to insert EMMS.  This qualifies as a quick hack.
21671
21672   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21673   if (VT.getSizeInBits() != 64)
21674     return SDValue();
21675
21676   const Function *F = DAG.getMachineFunction().getFunction();
21677   bool NoImplicitFloatOps = F->getAttributes().
21678     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21679   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21680                      && Subtarget->hasSSE2();
21681   if ((VT.isVector() ||
21682        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21683       isa<LoadSDNode>(St->getValue()) &&
21684       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21685       St->getChain().hasOneUse() && !St->isVolatile()) {
21686     SDNode* LdVal = St->getValue().getNode();
21687     LoadSDNode *Ld = nullptr;
21688     int TokenFactorIndex = -1;
21689     SmallVector<SDValue, 8> Ops;
21690     SDNode* ChainVal = St->getChain().getNode();
21691     // Must be a store of a load.  We currently handle two cases:  the load
21692     // is a direct child, and it's under an intervening TokenFactor.  It is
21693     // possible to dig deeper under nested TokenFactors.
21694     if (ChainVal == LdVal)
21695       Ld = cast<LoadSDNode>(St->getChain());
21696     else if (St->getValue().hasOneUse() &&
21697              ChainVal->getOpcode() == ISD::TokenFactor) {
21698       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21699         if (ChainVal->getOperand(i).getNode() == LdVal) {
21700           TokenFactorIndex = i;
21701           Ld = cast<LoadSDNode>(St->getValue());
21702         } else
21703           Ops.push_back(ChainVal->getOperand(i));
21704       }
21705     }
21706
21707     if (!Ld || !ISD::isNormalLoad(Ld))
21708       return SDValue();
21709
21710     // If this is not the MMX case, i.e. we are just turning i64 load/store
21711     // into f64 load/store, avoid the transformation if there are multiple
21712     // uses of the loaded value.
21713     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21714       return SDValue();
21715
21716     SDLoc LdDL(Ld);
21717     SDLoc StDL(N);
21718     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21719     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21720     // pair instead.
21721     if (Subtarget->is64Bit() || F64IsLegal) {
21722       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21723       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21724                                   Ld->getPointerInfo(), Ld->isVolatile(),
21725                                   Ld->isNonTemporal(), Ld->isInvariant(),
21726                                   Ld->getAlignment());
21727       SDValue NewChain = NewLd.getValue(1);
21728       if (TokenFactorIndex != -1) {
21729         Ops.push_back(NewChain);
21730         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21731       }
21732       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21733                           St->getPointerInfo(),
21734                           St->isVolatile(), St->isNonTemporal(),
21735                           St->getAlignment());
21736     }
21737
21738     // Otherwise, lower to two pairs of 32-bit loads / stores.
21739     SDValue LoAddr = Ld->getBasePtr();
21740     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21741                                  DAG.getConstant(4, MVT::i32));
21742
21743     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21744                                Ld->getPointerInfo(),
21745                                Ld->isVolatile(), Ld->isNonTemporal(),
21746                                Ld->isInvariant(), Ld->getAlignment());
21747     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21748                                Ld->getPointerInfo().getWithOffset(4),
21749                                Ld->isVolatile(), Ld->isNonTemporal(),
21750                                Ld->isInvariant(),
21751                                MinAlign(Ld->getAlignment(), 4));
21752
21753     SDValue NewChain = LoLd.getValue(1);
21754     if (TokenFactorIndex != -1) {
21755       Ops.push_back(LoLd);
21756       Ops.push_back(HiLd);
21757       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21758     }
21759
21760     LoAddr = St->getBasePtr();
21761     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21762                          DAG.getConstant(4, MVT::i32));
21763
21764     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21765                                 St->getPointerInfo(),
21766                                 St->isVolatile(), St->isNonTemporal(),
21767                                 St->getAlignment());
21768     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21769                                 St->getPointerInfo().getWithOffset(4),
21770                                 St->isVolatile(),
21771                                 St->isNonTemporal(),
21772                                 MinAlign(St->getAlignment(), 4));
21773     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21774   }
21775   return SDValue();
21776 }
21777
21778 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21779 /// and return the operands for the horizontal operation in LHS and RHS.  A
21780 /// horizontal operation performs the binary operation on successive elements
21781 /// of its first operand, then on successive elements of its second operand,
21782 /// returning the resulting values in a vector.  For example, if
21783 ///   A = < float a0, float a1, float a2, float a3 >
21784 /// and
21785 ///   B = < float b0, float b1, float b2, float b3 >
21786 /// then the result of doing a horizontal operation on A and B is
21787 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21788 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21789 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21790 /// set to A, RHS to B, and the routine returns 'true'.
21791 /// Note that the binary operation should have the property that if one of the
21792 /// operands is UNDEF then the result is UNDEF.
21793 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21794   // Look for the following pattern: if
21795   //   A = < float a0, float a1, float a2, float a3 >
21796   //   B = < float b0, float b1, float b2, float b3 >
21797   // and
21798   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21799   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21800   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21801   // which is A horizontal-op B.
21802
21803   // At least one of the operands should be a vector shuffle.
21804   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21805       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21806     return false;
21807
21808   MVT VT = LHS.getSimpleValueType();
21809
21810   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21811          "Unsupported vector type for horizontal add/sub");
21812
21813   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21814   // operate independently on 128-bit lanes.
21815   unsigned NumElts = VT.getVectorNumElements();
21816   unsigned NumLanes = VT.getSizeInBits()/128;
21817   unsigned NumLaneElts = NumElts / NumLanes;
21818   assert((NumLaneElts % 2 == 0) &&
21819          "Vector type should have an even number of elements in each lane");
21820   unsigned HalfLaneElts = NumLaneElts/2;
21821
21822   // View LHS in the form
21823   //   LHS = VECTOR_SHUFFLE A, B, LMask
21824   // If LHS is not a shuffle then pretend it is the shuffle
21825   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21826   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21827   // type VT.
21828   SDValue A, B;
21829   SmallVector<int, 16> LMask(NumElts);
21830   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21831     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21832       A = LHS.getOperand(0);
21833     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21834       B = LHS.getOperand(1);
21835     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21836     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21837   } else {
21838     if (LHS.getOpcode() != ISD::UNDEF)
21839       A = LHS;
21840     for (unsigned i = 0; i != NumElts; ++i)
21841       LMask[i] = i;
21842   }
21843
21844   // Likewise, view RHS in the form
21845   //   RHS = VECTOR_SHUFFLE C, D, RMask
21846   SDValue C, D;
21847   SmallVector<int, 16> RMask(NumElts);
21848   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21849     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21850       C = RHS.getOperand(0);
21851     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21852       D = RHS.getOperand(1);
21853     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21854     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21855   } else {
21856     if (RHS.getOpcode() != ISD::UNDEF)
21857       C = RHS;
21858     for (unsigned i = 0; i != NumElts; ++i)
21859       RMask[i] = i;
21860   }
21861
21862   // Check that the shuffles are both shuffling the same vectors.
21863   if (!(A == C && B == D) && !(A == D && B == C))
21864     return false;
21865
21866   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21867   if (!A.getNode() && !B.getNode())
21868     return false;
21869
21870   // If A and B occur in reverse order in RHS, then "swap" them (which means
21871   // rewriting the mask).
21872   if (A != C)
21873     CommuteVectorShuffleMask(RMask, NumElts);
21874
21875   // At this point LHS and RHS are equivalent to
21876   //   LHS = VECTOR_SHUFFLE A, B, LMask
21877   //   RHS = VECTOR_SHUFFLE A, B, RMask
21878   // Check that the masks correspond to performing a horizontal operation.
21879   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21880     for (unsigned i = 0; i != NumLaneElts; ++i) {
21881       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21882
21883       // Ignore any UNDEF components.
21884       if (LIdx < 0 || RIdx < 0 ||
21885           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21886           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21887         continue;
21888
21889       // Check that successive elements are being operated on.  If not, this is
21890       // not a horizontal operation.
21891       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21892       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21893       if (!(LIdx == Index && RIdx == Index + 1) &&
21894           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21895         return false;
21896     }
21897   }
21898
21899   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21900   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21901   return true;
21902 }
21903
21904 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21905 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21906                                   const X86Subtarget *Subtarget) {
21907   EVT VT = N->getValueType(0);
21908   SDValue LHS = N->getOperand(0);
21909   SDValue RHS = N->getOperand(1);
21910
21911   // Try to synthesize horizontal adds from adds of shuffles.
21912   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21913        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21914       isHorizontalBinOp(LHS, RHS, true))
21915     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21916   return SDValue();
21917 }
21918
21919 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21920 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21921                                   const X86Subtarget *Subtarget) {
21922   EVT VT = N->getValueType(0);
21923   SDValue LHS = N->getOperand(0);
21924   SDValue RHS = N->getOperand(1);
21925
21926   // Try to synthesize horizontal subs from subs of shuffles.
21927   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21928        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21929       isHorizontalBinOp(LHS, RHS, false))
21930     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21931   return SDValue();
21932 }
21933
21934 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21935 /// X86ISD::FXOR nodes.
21936 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21937   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21938   // F[X]OR(0.0, x) -> x
21939   // F[X]OR(x, 0.0) -> x
21940   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21941     if (C->getValueAPF().isPosZero())
21942       return N->getOperand(1);
21943   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21944     if (C->getValueAPF().isPosZero())
21945       return N->getOperand(0);
21946   return SDValue();
21947 }
21948
21949 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21950 /// X86ISD::FMAX nodes.
21951 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21952   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21953
21954   // Only perform optimizations if UnsafeMath is used.
21955   if (!DAG.getTarget().Options.UnsafeFPMath)
21956     return SDValue();
21957
21958   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21959   // into FMINC and FMAXC, which are Commutative operations.
21960   unsigned NewOp = 0;
21961   switch (N->getOpcode()) {
21962     default: llvm_unreachable("unknown opcode");
21963     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21964     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21965   }
21966
21967   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21968                      N->getOperand(0), N->getOperand(1));
21969 }
21970
21971 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21972 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21973   // FAND(0.0, x) -> 0.0
21974   // FAND(x, 0.0) -> 0.0
21975   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21976     if (C->getValueAPF().isPosZero())
21977       return N->getOperand(0);
21978   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21979     if (C->getValueAPF().isPosZero())
21980       return N->getOperand(1);
21981   return SDValue();
21982 }
21983
21984 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21985 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21986   // FANDN(x, 0.0) -> 0.0
21987   // FANDN(0.0, x) -> x
21988   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21989     if (C->getValueAPF().isPosZero())
21990       return N->getOperand(1);
21991   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21992     if (C->getValueAPF().isPosZero())
21993       return N->getOperand(1);
21994   return SDValue();
21995 }
21996
21997 static SDValue PerformBTCombine(SDNode *N,
21998                                 SelectionDAG &DAG,
21999                                 TargetLowering::DAGCombinerInfo &DCI) {
22000   // BT ignores high bits in the bit index operand.
22001   SDValue Op1 = N->getOperand(1);
22002   if (Op1.hasOneUse()) {
22003     unsigned BitWidth = Op1.getValueSizeInBits();
22004     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22005     APInt KnownZero, KnownOne;
22006     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22007                                           !DCI.isBeforeLegalizeOps());
22008     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22009     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22010         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22011       DCI.CommitTargetLoweringOpt(TLO);
22012   }
22013   return SDValue();
22014 }
22015
22016 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22017   SDValue Op = N->getOperand(0);
22018   if (Op.getOpcode() == ISD::BITCAST)
22019     Op = Op.getOperand(0);
22020   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22021   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22022       VT.getVectorElementType().getSizeInBits() ==
22023       OpVT.getVectorElementType().getSizeInBits()) {
22024     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22025   }
22026   return SDValue();
22027 }
22028
22029 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22030                                                const X86Subtarget *Subtarget) {
22031   EVT VT = N->getValueType(0);
22032   if (!VT.isVector())
22033     return SDValue();
22034
22035   SDValue N0 = N->getOperand(0);
22036   SDValue N1 = N->getOperand(1);
22037   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22038   SDLoc dl(N);
22039
22040   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22041   // both SSE and AVX2 since there is no sign-extended shift right
22042   // operation on a vector with 64-bit elements.
22043   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22044   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22045   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22046       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22047     SDValue N00 = N0.getOperand(0);
22048
22049     // EXTLOAD has a better solution on AVX2,
22050     // it may be replaced with X86ISD::VSEXT node.
22051     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22052       if (!ISD::isNormalLoad(N00.getNode()))
22053         return SDValue();
22054
22055     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22056         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22057                                   N00, N1);
22058       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22059     }
22060   }
22061   return SDValue();
22062 }
22063
22064 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22065                                   TargetLowering::DAGCombinerInfo &DCI,
22066                                   const X86Subtarget *Subtarget) {
22067   if (!DCI.isBeforeLegalizeOps())
22068     return SDValue();
22069
22070   if (!Subtarget->hasFp256())
22071     return SDValue();
22072
22073   EVT VT = N->getValueType(0);
22074   if (VT.isVector() && VT.getSizeInBits() == 256) {
22075     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22076     if (R.getNode())
22077       return R;
22078   }
22079
22080   return SDValue();
22081 }
22082
22083 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22084                                  const X86Subtarget* Subtarget) {
22085   SDLoc dl(N);
22086   EVT VT = N->getValueType(0);
22087
22088   // Let legalize expand this if it isn't a legal type yet.
22089   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22090     return SDValue();
22091
22092   EVT ScalarVT = VT.getScalarType();
22093   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22094       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22095     return SDValue();
22096
22097   SDValue A = N->getOperand(0);
22098   SDValue B = N->getOperand(1);
22099   SDValue C = N->getOperand(2);
22100
22101   bool NegA = (A.getOpcode() == ISD::FNEG);
22102   bool NegB = (B.getOpcode() == ISD::FNEG);
22103   bool NegC = (C.getOpcode() == ISD::FNEG);
22104
22105   // Negative multiplication when NegA xor NegB
22106   bool NegMul = (NegA != NegB);
22107   if (NegA)
22108     A = A.getOperand(0);
22109   if (NegB)
22110     B = B.getOperand(0);
22111   if (NegC)
22112     C = C.getOperand(0);
22113
22114   unsigned Opcode;
22115   if (!NegMul)
22116     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22117   else
22118     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22119
22120   return DAG.getNode(Opcode, dl, VT, A, B, C);
22121 }
22122
22123 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22124                                   TargetLowering::DAGCombinerInfo &DCI,
22125                                   const X86Subtarget *Subtarget) {
22126   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22127   //           (and (i32 x86isd::setcc_carry), 1)
22128   // This eliminates the zext. This transformation is necessary because
22129   // ISD::SETCC is always legalized to i8.
22130   SDLoc dl(N);
22131   SDValue N0 = N->getOperand(0);
22132   EVT VT = N->getValueType(0);
22133
22134   if (N0.getOpcode() == ISD::AND &&
22135       N0.hasOneUse() &&
22136       N0.getOperand(0).hasOneUse()) {
22137     SDValue N00 = N0.getOperand(0);
22138     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22139       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22140       if (!C || C->getZExtValue() != 1)
22141         return SDValue();
22142       return DAG.getNode(ISD::AND, dl, VT,
22143                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22144                                      N00.getOperand(0), N00.getOperand(1)),
22145                          DAG.getConstant(1, VT));
22146     }
22147   }
22148
22149   if (N0.getOpcode() == ISD::TRUNCATE &&
22150       N0.hasOneUse() &&
22151       N0.getOperand(0).hasOneUse()) {
22152     SDValue N00 = N0.getOperand(0);
22153     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22154       return DAG.getNode(ISD::AND, dl, VT,
22155                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22156                                      N00.getOperand(0), N00.getOperand(1)),
22157                          DAG.getConstant(1, VT));
22158     }
22159   }
22160   if (VT.is256BitVector()) {
22161     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22162     if (R.getNode())
22163       return R;
22164   }
22165
22166   return SDValue();
22167 }
22168
22169 // Optimize x == -y --> x+y == 0
22170 //          x != -y --> x+y != 0
22171 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22172                                       const X86Subtarget* Subtarget) {
22173   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22174   SDValue LHS = N->getOperand(0);
22175   SDValue RHS = N->getOperand(1);
22176   EVT VT = N->getValueType(0);
22177   SDLoc DL(N);
22178
22179   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22180     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22181       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22182         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22183                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22184         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22185                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22186       }
22187   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22188     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22189       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22190         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22191                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22192         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22193                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22194       }
22195
22196   if (VT.getScalarType() == MVT::i1) {
22197     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22198       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22199     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22200     if (!IsSEXT0 && !IsVZero0)
22201       return SDValue();
22202     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22203       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22204     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22205
22206     if (!IsSEXT1 && !IsVZero1)
22207       return SDValue();
22208
22209     if (IsSEXT0 && IsVZero1) {
22210       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22211       if (CC == ISD::SETEQ)
22212         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22213       return LHS.getOperand(0);
22214     }
22215     if (IsSEXT1 && IsVZero0) {
22216       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22217       if (CC == ISD::SETEQ)
22218         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22219       return RHS.getOperand(0);
22220     }
22221   }
22222
22223   return SDValue();
22224 }
22225
22226 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22227                                       const X86Subtarget *Subtarget) {
22228   SDLoc dl(N);
22229   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22230   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22231          "X86insertps is only defined for v4x32");
22232
22233   SDValue Ld = N->getOperand(1);
22234   if (MayFoldLoad(Ld)) {
22235     // Extract the countS bits from the immediate so we can get the proper
22236     // address when narrowing the vector load to a specific element.
22237     // When the second source op is a memory address, interps doesn't use
22238     // countS and just gets an f32 from that address.
22239     unsigned DestIndex =
22240         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22241     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22242   } else
22243     return SDValue();
22244
22245   // Create this as a scalar to vector to match the instruction pattern.
22246   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22247   // countS bits are ignored when loading from memory on insertps, which
22248   // means we don't need to explicitly set them to 0.
22249   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22250                      LoadScalarToVector, N->getOperand(2));
22251 }
22252
22253 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22254 // as "sbb reg,reg", since it can be extended without zext and produces
22255 // an all-ones bit which is more useful than 0/1 in some cases.
22256 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22257                                MVT VT) {
22258   if (VT == MVT::i8)
22259     return DAG.getNode(ISD::AND, DL, VT,
22260                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22261                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22262                        DAG.getConstant(1, VT));
22263   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22264   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22265                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22266                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22267 }
22268
22269 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22270 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22271                                    TargetLowering::DAGCombinerInfo &DCI,
22272                                    const X86Subtarget *Subtarget) {
22273   SDLoc DL(N);
22274   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22275   SDValue EFLAGS = N->getOperand(1);
22276
22277   if (CC == X86::COND_A) {
22278     // Try to convert COND_A into COND_B in an attempt to facilitate
22279     // materializing "setb reg".
22280     //
22281     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22282     // cannot take an immediate as its first operand.
22283     //
22284     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22285         EFLAGS.getValueType().isInteger() &&
22286         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22287       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22288                                    EFLAGS.getNode()->getVTList(),
22289                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22290       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22291       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22292     }
22293   }
22294
22295   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22296   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22297   // cases.
22298   if (CC == X86::COND_B)
22299     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22300
22301   SDValue Flags;
22302
22303   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22304   if (Flags.getNode()) {
22305     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22306     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22307   }
22308
22309   return SDValue();
22310 }
22311
22312 // Optimize branch condition evaluation.
22313 //
22314 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22315                                     TargetLowering::DAGCombinerInfo &DCI,
22316                                     const X86Subtarget *Subtarget) {
22317   SDLoc DL(N);
22318   SDValue Chain = N->getOperand(0);
22319   SDValue Dest = N->getOperand(1);
22320   SDValue EFLAGS = N->getOperand(3);
22321   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22322
22323   SDValue Flags;
22324
22325   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22326   if (Flags.getNode()) {
22327     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22328     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22329                        Flags);
22330   }
22331
22332   return SDValue();
22333 }
22334
22335 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22336                                         const X86TargetLowering *XTLI) {
22337   SDValue Op0 = N->getOperand(0);
22338   EVT InVT = Op0->getValueType(0);
22339
22340   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22341   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22342     SDLoc dl(N);
22343     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22344     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22345     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22346   }
22347
22348   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22349   // a 32-bit target where SSE doesn't support i64->FP operations.
22350   if (Op0.getOpcode() == ISD::LOAD) {
22351     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22352     EVT VT = Ld->getValueType(0);
22353     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22354         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22355         !XTLI->getSubtarget()->is64Bit() &&
22356         VT == MVT::i64) {
22357       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22358                                           Ld->getChain(), Op0, DAG);
22359       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22360       return FILDChain;
22361     }
22362   }
22363   return SDValue();
22364 }
22365
22366 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22367 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22368                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22369   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22370   // the result is either zero or one (depending on the input carry bit).
22371   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22372   if (X86::isZeroNode(N->getOperand(0)) &&
22373       X86::isZeroNode(N->getOperand(1)) &&
22374       // We don't have a good way to replace an EFLAGS use, so only do this when
22375       // dead right now.
22376       SDValue(N, 1).use_empty()) {
22377     SDLoc DL(N);
22378     EVT VT = N->getValueType(0);
22379     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22380     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22381                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22382                                            DAG.getConstant(X86::COND_B,MVT::i8),
22383                                            N->getOperand(2)),
22384                                DAG.getConstant(1, VT));
22385     return DCI.CombineTo(N, Res1, CarryOut);
22386   }
22387
22388   return SDValue();
22389 }
22390
22391 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22392 //      (add Y, (setne X, 0)) -> sbb -1, Y
22393 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22394 //      (sub (setne X, 0), Y) -> adc -1, Y
22395 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22396   SDLoc DL(N);
22397
22398   // Look through ZExts.
22399   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22400   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22401     return SDValue();
22402
22403   SDValue SetCC = Ext.getOperand(0);
22404   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22405     return SDValue();
22406
22407   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22408   if (CC != X86::COND_E && CC != X86::COND_NE)
22409     return SDValue();
22410
22411   SDValue Cmp = SetCC.getOperand(1);
22412   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22413       !X86::isZeroNode(Cmp.getOperand(1)) ||
22414       !Cmp.getOperand(0).getValueType().isInteger())
22415     return SDValue();
22416
22417   SDValue CmpOp0 = Cmp.getOperand(0);
22418   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22419                                DAG.getConstant(1, CmpOp0.getValueType()));
22420
22421   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22422   if (CC == X86::COND_NE)
22423     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22424                        DL, OtherVal.getValueType(), OtherVal,
22425                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22426   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22427                      DL, OtherVal.getValueType(), OtherVal,
22428                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22429 }
22430
22431 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22432 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22433                                  const X86Subtarget *Subtarget) {
22434   EVT VT = N->getValueType(0);
22435   SDValue Op0 = N->getOperand(0);
22436   SDValue Op1 = N->getOperand(1);
22437
22438   // Try to synthesize horizontal adds from adds of shuffles.
22439   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22440        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22441       isHorizontalBinOp(Op0, Op1, true))
22442     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22443
22444   return OptimizeConditionalInDecrement(N, DAG);
22445 }
22446
22447 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22448                                  const X86Subtarget *Subtarget) {
22449   SDValue Op0 = N->getOperand(0);
22450   SDValue Op1 = N->getOperand(1);
22451
22452   // X86 can't encode an immediate LHS of a sub. See if we can push the
22453   // negation into a preceding instruction.
22454   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22455     // If the RHS of the sub is a XOR with one use and a constant, invert the
22456     // immediate. Then add one to the LHS of the sub so we can turn
22457     // X-Y -> X+~Y+1, saving one register.
22458     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22459         isa<ConstantSDNode>(Op1.getOperand(1))) {
22460       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22461       EVT VT = Op0.getValueType();
22462       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22463                                    Op1.getOperand(0),
22464                                    DAG.getConstant(~XorC, VT));
22465       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22466                          DAG.getConstant(C->getAPIntValue()+1, VT));
22467     }
22468   }
22469
22470   // Try to synthesize horizontal adds from adds of shuffles.
22471   EVT VT = N->getValueType(0);
22472   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22473        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22474       isHorizontalBinOp(Op0, Op1, true))
22475     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22476
22477   return OptimizeConditionalInDecrement(N, DAG);
22478 }
22479
22480 /// performVZEXTCombine - Performs build vector combines
22481 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22482                                         TargetLowering::DAGCombinerInfo &DCI,
22483                                         const X86Subtarget *Subtarget) {
22484   // (vzext (bitcast (vzext (x)) -> (vzext x)
22485   SDValue In = N->getOperand(0);
22486   while (In.getOpcode() == ISD::BITCAST)
22487     In = In.getOperand(0);
22488
22489   if (In.getOpcode() != X86ISD::VZEXT)
22490     return SDValue();
22491
22492   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22493                      In.getOperand(0));
22494 }
22495
22496 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22497                                              DAGCombinerInfo &DCI) const {
22498   SelectionDAG &DAG = DCI.DAG;
22499   switch (N->getOpcode()) {
22500   default: break;
22501   case ISD::EXTRACT_VECTOR_ELT:
22502     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22503   case ISD::VSELECT:
22504   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22505   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22506   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22507   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22508   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22509   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22510   case ISD::SHL:
22511   case ISD::SRA:
22512   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22513   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22514   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22515   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22516   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22517   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22518   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22519   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22520   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22521   case X86ISD::FXOR:
22522   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22523   case X86ISD::FMIN:
22524   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22525   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22526   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22527   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22528   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22529   case ISD::ANY_EXTEND:
22530   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22531   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22532   case ISD::SIGN_EXTEND_INREG:
22533     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22534   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22535   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22536   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22537   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22538   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22539   case X86ISD::SHUFP:       // Handle all target specific shuffles
22540   case X86ISD::PALIGNR:
22541   case X86ISD::UNPCKH:
22542   case X86ISD::UNPCKL:
22543   case X86ISD::MOVHLPS:
22544   case X86ISD::MOVLHPS:
22545   case X86ISD::PSHUFD:
22546   case X86ISD::PSHUFHW:
22547   case X86ISD::PSHUFLW:
22548   case X86ISD::MOVSS:
22549   case X86ISD::MOVSD:
22550   case X86ISD::VPERMILP:
22551   case X86ISD::VPERM2X128:
22552   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22553   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22554   case ISD::INTRINSIC_WO_CHAIN:
22555     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22556   case X86ISD::INSERTPS:
22557     return PerformINSERTPSCombine(N, DAG, Subtarget);
22558   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22559   }
22560
22561   return SDValue();
22562 }
22563
22564 /// isTypeDesirableForOp - Return true if the target has native support for
22565 /// the specified value type and it is 'desirable' to use the type for the
22566 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22567 /// instruction encodings are longer and some i16 instructions are slow.
22568 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22569   if (!isTypeLegal(VT))
22570     return false;
22571   if (VT != MVT::i16)
22572     return true;
22573
22574   switch (Opc) {
22575   default:
22576     return true;
22577   case ISD::LOAD:
22578   case ISD::SIGN_EXTEND:
22579   case ISD::ZERO_EXTEND:
22580   case ISD::ANY_EXTEND:
22581   case ISD::SHL:
22582   case ISD::SRL:
22583   case ISD::SUB:
22584   case ISD::ADD:
22585   case ISD::MUL:
22586   case ISD::AND:
22587   case ISD::OR:
22588   case ISD::XOR:
22589     return false;
22590   }
22591 }
22592
22593 /// IsDesirableToPromoteOp - This method query the target whether it is
22594 /// beneficial for dag combiner to promote the specified node. If true, it
22595 /// should return the desired promotion type by reference.
22596 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22597   EVT VT = Op.getValueType();
22598   if (VT != MVT::i16)
22599     return false;
22600
22601   bool Promote = false;
22602   bool Commute = false;
22603   switch (Op.getOpcode()) {
22604   default: break;
22605   case ISD::LOAD: {
22606     LoadSDNode *LD = cast<LoadSDNode>(Op);
22607     // If the non-extending load has a single use and it's not live out, then it
22608     // might be folded.
22609     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22610                                                      Op.hasOneUse()*/) {
22611       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22612              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22613         // The only case where we'd want to promote LOAD (rather then it being
22614         // promoted as an operand is when it's only use is liveout.
22615         if (UI->getOpcode() != ISD::CopyToReg)
22616           return false;
22617       }
22618     }
22619     Promote = true;
22620     break;
22621   }
22622   case ISD::SIGN_EXTEND:
22623   case ISD::ZERO_EXTEND:
22624   case ISD::ANY_EXTEND:
22625     Promote = true;
22626     break;
22627   case ISD::SHL:
22628   case ISD::SRL: {
22629     SDValue N0 = Op.getOperand(0);
22630     // Look out for (store (shl (load), x)).
22631     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22632       return false;
22633     Promote = true;
22634     break;
22635   }
22636   case ISD::ADD:
22637   case ISD::MUL:
22638   case ISD::AND:
22639   case ISD::OR:
22640   case ISD::XOR:
22641     Commute = true;
22642     // fallthrough
22643   case ISD::SUB: {
22644     SDValue N0 = Op.getOperand(0);
22645     SDValue N1 = Op.getOperand(1);
22646     if (!Commute && MayFoldLoad(N1))
22647       return false;
22648     // Avoid disabling potential load folding opportunities.
22649     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22650       return false;
22651     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22652       return false;
22653     Promote = true;
22654   }
22655   }
22656
22657   PVT = MVT::i32;
22658   return Promote;
22659 }
22660
22661 //===----------------------------------------------------------------------===//
22662 //                           X86 Inline Assembly Support
22663 //===----------------------------------------------------------------------===//
22664
22665 namespace {
22666   // Helper to match a string separated by whitespace.
22667   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22668     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22669
22670     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22671       StringRef piece(*args[i]);
22672       if (!s.startswith(piece)) // Check if the piece matches.
22673         return false;
22674
22675       s = s.substr(piece.size());
22676       StringRef::size_type pos = s.find_first_not_of(" \t");
22677       if (pos == 0) // We matched a prefix.
22678         return false;
22679
22680       s = s.substr(pos);
22681     }
22682
22683     return s.empty();
22684   }
22685   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22686 }
22687
22688 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22689
22690   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22691     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22692         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22693         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22694
22695       if (AsmPieces.size() == 3)
22696         return true;
22697       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22698         return true;
22699     }
22700   }
22701   return false;
22702 }
22703
22704 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22705   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22706
22707   std::string AsmStr = IA->getAsmString();
22708
22709   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22710   if (!Ty || Ty->getBitWidth() % 16 != 0)
22711     return false;
22712
22713   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22714   SmallVector<StringRef, 4> AsmPieces;
22715   SplitString(AsmStr, AsmPieces, ";\n");
22716
22717   switch (AsmPieces.size()) {
22718   default: return false;
22719   case 1:
22720     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22721     // we will turn this bswap into something that will be lowered to logical
22722     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22723     // lower so don't worry about this.
22724     // bswap $0
22725     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22726         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22727         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22728         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22729         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22730         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22731       // No need to check constraints, nothing other than the equivalent of
22732       // "=r,0" would be valid here.
22733       return IntrinsicLowering::LowerToByteSwap(CI);
22734     }
22735
22736     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22737     if (CI->getType()->isIntegerTy(16) &&
22738         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22739         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22740          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22741       AsmPieces.clear();
22742       const std::string &ConstraintsStr = IA->getConstraintString();
22743       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22744       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22745       if (clobbersFlagRegisters(AsmPieces))
22746         return IntrinsicLowering::LowerToByteSwap(CI);
22747     }
22748     break;
22749   case 3:
22750     if (CI->getType()->isIntegerTy(32) &&
22751         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22752         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22753         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22754         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22755       AsmPieces.clear();
22756       const std::string &ConstraintsStr = IA->getConstraintString();
22757       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22758       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22759       if (clobbersFlagRegisters(AsmPieces))
22760         return IntrinsicLowering::LowerToByteSwap(CI);
22761     }
22762
22763     if (CI->getType()->isIntegerTy(64)) {
22764       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22765       if (Constraints.size() >= 2 &&
22766           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22767           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22768         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22769         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22770             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22771             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22772           return IntrinsicLowering::LowerToByteSwap(CI);
22773       }
22774     }
22775     break;
22776   }
22777   return false;
22778 }
22779
22780 /// getConstraintType - Given a constraint letter, return the type of
22781 /// constraint it is for this target.
22782 X86TargetLowering::ConstraintType
22783 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22784   if (Constraint.size() == 1) {
22785     switch (Constraint[0]) {
22786     case 'R':
22787     case 'q':
22788     case 'Q':
22789     case 'f':
22790     case 't':
22791     case 'u':
22792     case 'y':
22793     case 'x':
22794     case 'Y':
22795     case 'l':
22796       return C_RegisterClass;
22797     case 'a':
22798     case 'b':
22799     case 'c':
22800     case 'd':
22801     case 'S':
22802     case 'D':
22803     case 'A':
22804       return C_Register;
22805     case 'I':
22806     case 'J':
22807     case 'K':
22808     case 'L':
22809     case 'M':
22810     case 'N':
22811     case 'G':
22812     case 'C':
22813     case 'e':
22814     case 'Z':
22815       return C_Other;
22816     default:
22817       break;
22818     }
22819   }
22820   return TargetLowering::getConstraintType(Constraint);
22821 }
22822
22823 /// Examine constraint type and operand type and determine a weight value.
22824 /// This object must already have been set up with the operand type
22825 /// and the current alternative constraint selected.
22826 TargetLowering::ConstraintWeight
22827   X86TargetLowering::getSingleConstraintMatchWeight(
22828     AsmOperandInfo &info, const char *constraint) const {
22829   ConstraintWeight weight = CW_Invalid;
22830   Value *CallOperandVal = info.CallOperandVal;
22831     // If we don't have a value, we can't do a match,
22832     // but allow it at the lowest weight.
22833   if (!CallOperandVal)
22834     return CW_Default;
22835   Type *type = CallOperandVal->getType();
22836   // Look at the constraint type.
22837   switch (*constraint) {
22838   default:
22839     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22840   case 'R':
22841   case 'q':
22842   case 'Q':
22843   case 'a':
22844   case 'b':
22845   case 'c':
22846   case 'd':
22847   case 'S':
22848   case 'D':
22849   case 'A':
22850     if (CallOperandVal->getType()->isIntegerTy())
22851       weight = CW_SpecificReg;
22852     break;
22853   case 'f':
22854   case 't':
22855   case 'u':
22856     if (type->isFloatingPointTy())
22857       weight = CW_SpecificReg;
22858     break;
22859   case 'y':
22860     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22861       weight = CW_SpecificReg;
22862     break;
22863   case 'x':
22864   case 'Y':
22865     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22866         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22867       weight = CW_Register;
22868     break;
22869   case 'I':
22870     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22871       if (C->getZExtValue() <= 31)
22872         weight = CW_Constant;
22873     }
22874     break;
22875   case 'J':
22876     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22877       if (C->getZExtValue() <= 63)
22878         weight = CW_Constant;
22879     }
22880     break;
22881   case 'K':
22882     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22883       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22884         weight = CW_Constant;
22885     }
22886     break;
22887   case 'L':
22888     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22889       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22890         weight = CW_Constant;
22891     }
22892     break;
22893   case 'M':
22894     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22895       if (C->getZExtValue() <= 3)
22896         weight = CW_Constant;
22897     }
22898     break;
22899   case 'N':
22900     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22901       if (C->getZExtValue() <= 0xff)
22902         weight = CW_Constant;
22903     }
22904     break;
22905   case 'G':
22906   case 'C':
22907     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22908       weight = CW_Constant;
22909     }
22910     break;
22911   case 'e':
22912     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22913       if ((C->getSExtValue() >= -0x80000000LL) &&
22914           (C->getSExtValue() <= 0x7fffffffLL))
22915         weight = CW_Constant;
22916     }
22917     break;
22918   case 'Z':
22919     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22920       if (C->getZExtValue() <= 0xffffffff)
22921         weight = CW_Constant;
22922     }
22923     break;
22924   }
22925   return weight;
22926 }
22927
22928 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22929 /// with another that has more specific requirements based on the type of the
22930 /// corresponding operand.
22931 const char *X86TargetLowering::
22932 LowerXConstraint(EVT ConstraintVT) const {
22933   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22934   // 'f' like normal targets.
22935   if (ConstraintVT.isFloatingPoint()) {
22936     if (Subtarget->hasSSE2())
22937       return "Y";
22938     if (Subtarget->hasSSE1())
22939       return "x";
22940   }
22941
22942   return TargetLowering::LowerXConstraint(ConstraintVT);
22943 }
22944
22945 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22946 /// vector.  If it is invalid, don't add anything to Ops.
22947 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22948                                                      std::string &Constraint,
22949                                                      std::vector<SDValue>&Ops,
22950                                                      SelectionDAG &DAG) const {
22951   SDValue Result;
22952
22953   // Only support length 1 constraints for now.
22954   if (Constraint.length() > 1) return;
22955
22956   char ConstraintLetter = Constraint[0];
22957   switch (ConstraintLetter) {
22958   default: break;
22959   case 'I':
22960     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22961       if (C->getZExtValue() <= 31) {
22962         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22963         break;
22964       }
22965     }
22966     return;
22967   case 'J':
22968     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22969       if (C->getZExtValue() <= 63) {
22970         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22971         break;
22972       }
22973     }
22974     return;
22975   case 'K':
22976     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22977       if (isInt<8>(C->getSExtValue())) {
22978         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22979         break;
22980       }
22981     }
22982     return;
22983   case 'N':
22984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22985       if (C->getZExtValue() <= 255) {
22986         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22987         break;
22988       }
22989     }
22990     return;
22991   case 'e': {
22992     // 32-bit signed value
22993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22994       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22995                                            C->getSExtValue())) {
22996         // Widen to 64 bits here to get it sign extended.
22997         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22998         break;
22999       }
23000     // FIXME gcc accepts some relocatable values here too, but only in certain
23001     // memory models; it's complicated.
23002     }
23003     return;
23004   }
23005   case 'Z': {
23006     // 32-bit unsigned value
23007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23008       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23009                                            C->getZExtValue())) {
23010         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23011         break;
23012       }
23013     }
23014     // FIXME gcc accepts some relocatable values here too, but only in certain
23015     // memory models; it's complicated.
23016     return;
23017   }
23018   case 'i': {
23019     // Literal immediates are always ok.
23020     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23021       // Widen to 64 bits here to get it sign extended.
23022       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23023       break;
23024     }
23025
23026     // In any sort of PIC mode addresses need to be computed at runtime by
23027     // adding in a register or some sort of table lookup.  These can't
23028     // be used as immediates.
23029     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23030       return;
23031
23032     // If we are in non-pic codegen mode, we allow the address of a global (with
23033     // an optional displacement) to be used with 'i'.
23034     GlobalAddressSDNode *GA = nullptr;
23035     int64_t Offset = 0;
23036
23037     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23038     while (1) {
23039       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23040         Offset += GA->getOffset();
23041         break;
23042       } else if (Op.getOpcode() == ISD::ADD) {
23043         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23044           Offset += C->getZExtValue();
23045           Op = Op.getOperand(0);
23046           continue;
23047         }
23048       } else if (Op.getOpcode() == ISD::SUB) {
23049         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23050           Offset += -C->getZExtValue();
23051           Op = Op.getOperand(0);
23052           continue;
23053         }
23054       }
23055
23056       // Otherwise, this isn't something we can handle, reject it.
23057       return;
23058     }
23059
23060     const GlobalValue *GV = GA->getGlobal();
23061     // If we require an extra load to get this address, as in PIC mode, we
23062     // can't accept it.
23063     if (isGlobalStubReference(
23064             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23065       return;
23066
23067     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23068                                         GA->getValueType(0), Offset);
23069     break;
23070   }
23071   }
23072
23073   if (Result.getNode()) {
23074     Ops.push_back(Result);
23075     return;
23076   }
23077   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23078 }
23079
23080 std::pair<unsigned, const TargetRegisterClass*>
23081 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23082                                                 MVT VT) const {
23083   // First, see if this is a constraint that directly corresponds to an LLVM
23084   // register class.
23085   if (Constraint.size() == 1) {
23086     // GCC Constraint Letters
23087     switch (Constraint[0]) {
23088     default: break;
23089       // TODO: Slight differences here in allocation order and leaving
23090       // RIP in the class. Do they matter any more here than they do
23091       // in the normal allocation?
23092     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23093       if (Subtarget->is64Bit()) {
23094         if (VT == MVT::i32 || VT == MVT::f32)
23095           return std::make_pair(0U, &X86::GR32RegClass);
23096         if (VT == MVT::i16)
23097           return std::make_pair(0U, &X86::GR16RegClass);
23098         if (VT == MVT::i8 || VT == MVT::i1)
23099           return std::make_pair(0U, &X86::GR8RegClass);
23100         if (VT == MVT::i64 || VT == MVT::f64)
23101           return std::make_pair(0U, &X86::GR64RegClass);
23102         break;
23103       }
23104       // 32-bit fallthrough
23105     case 'Q':   // Q_REGS
23106       if (VT == MVT::i32 || VT == MVT::f32)
23107         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23108       if (VT == MVT::i16)
23109         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23110       if (VT == MVT::i8 || VT == MVT::i1)
23111         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23112       if (VT == MVT::i64)
23113         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23114       break;
23115     case 'r':   // GENERAL_REGS
23116     case 'l':   // INDEX_REGS
23117       if (VT == MVT::i8 || VT == MVT::i1)
23118         return std::make_pair(0U, &X86::GR8RegClass);
23119       if (VT == MVT::i16)
23120         return std::make_pair(0U, &X86::GR16RegClass);
23121       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23122         return std::make_pair(0U, &X86::GR32RegClass);
23123       return std::make_pair(0U, &X86::GR64RegClass);
23124     case 'R':   // LEGACY_REGS
23125       if (VT == MVT::i8 || VT == MVT::i1)
23126         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23127       if (VT == MVT::i16)
23128         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23129       if (VT == MVT::i32 || !Subtarget->is64Bit())
23130         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23131       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23132     case 'f':  // FP Stack registers.
23133       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23134       // value to the correct fpstack register class.
23135       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23136         return std::make_pair(0U, &X86::RFP32RegClass);
23137       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23138         return std::make_pair(0U, &X86::RFP64RegClass);
23139       return std::make_pair(0U, &X86::RFP80RegClass);
23140     case 'y':   // MMX_REGS if MMX allowed.
23141       if (!Subtarget->hasMMX()) break;
23142       return std::make_pair(0U, &X86::VR64RegClass);
23143     case 'Y':   // SSE_REGS if SSE2 allowed
23144       if (!Subtarget->hasSSE2()) break;
23145       // FALL THROUGH.
23146     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23147       if (!Subtarget->hasSSE1()) break;
23148
23149       switch (VT.SimpleTy) {
23150       default: break;
23151       // Scalar SSE types.
23152       case MVT::f32:
23153       case MVT::i32:
23154         return std::make_pair(0U, &X86::FR32RegClass);
23155       case MVT::f64:
23156       case MVT::i64:
23157         return std::make_pair(0U, &X86::FR64RegClass);
23158       // Vector types.
23159       case MVT::v16i8:
23160       case MVT::v8i16:
23161       case MVT::v4i32:
23162       case MVT::v2i64:
23163       case MVT::v4f32:
23164       case MVT::v2f64:
23165         return std::make_pair(0U, &X86::VR128RegClass);
23166       // AVX types.
23167       case MVT::v32i8:
23168       case MVT::v16i16:
23169       case MVT::v8i32:
23170       case MVT::v4i64:
23171       case MVT::v8f32:
23172       case MVT::v4f64:
23173         return std::make_pair(0U, &X86::VR256RegClass);
23174       case MVT::v8f64:
23175       case MVT::v16f32:
23176       case MVT::v16i32:
23177       case MVT::v8i64:
23178         return std::make_pair(0U, &X86::VR512RegClass);
23179       }
23180       break;
23181     }
23182   }
23183
23184   // Use the default implementation in TargetLowering to convert the register
23185   // constraint into a member of a register class.
23186   std::pair<unsigned, const TargetRegisterClass*> Res;
23187   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23188
23189   // Not found as a standard register?
23190   if (!Res.second) {
23191     // Map st(0) -> st(7) -> ST0
23192     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23193         tolower(Constraint[1]) == 's' &&
23194         tolower(Constraint[2]) == 't' &&
23195         Constraint[3] == '(' &&
23196         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23197         Constraint[5] == ')' &&
23198         Constraint[6] == '}') {
23199
23200       Res.first = X86::ST0+Constraint[4]-'0';
23201       Res.second = &X86::RFP80RegClass;
23202       return Res;
23203     }
23204
23205     // GCC allows "st(0)" to be called just plain "st".
23206     if (StringRef("{st}").equals_lower(Constraint)) {
23207       Res.first = X86::ST0;
23208       Res.second = &X86::RFP80RegClass;
23209       return Res;
23210     }
23211
23212     // flags -> EFLAGS
23213     if (StringRef("{flags}").equals_lower(Constraint)) {
23214       Res.first = X86::EFLAGS;
23215       Res.second = &X86::CCRRegClass;
23216       return Res;
23217     }
23218
23219     // 'A' means EAX + EDX.
23220     if (Constraint == "A") {
23221       Res.first = X86::EAX;
23222       Res.second = &X86::GR32_ADRegClass;
23223       return Res;
23224     }
23225     return Res;
23226   }
23227
23228   // Otherwise, check to see if this is a register class of the wrong value
23229   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23230   // turn into {ax},{dx}.
23231   if (Res.second->hasType(VT))
23232     return Res;   // Correct type already, nothing to do.
23233
23234   // All of the single-register GCC register classes map their values onto
23235   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23236   // really want an 8-bit or 32-bit register, map to the appropriate register
23237   // class and return the appropriate register.
23238   if (Res.second == &X86::GR16RegClass) {
23239     if (VT == MVT::i8 || VT == MVT::i1) {
23240       unsigned DestReg = 0;
23241       switch (Res.first) {
23242       default: break;
23243       case X86::AX: DestReg = X86::AL; break;
23244       case X86::DX: DestReg = X86::DL; break;
23245       case X86::CX: DestReg = X86::CL; break;
23246       case X86::BX: DestReg = X86::BL; break;
23247       }
23248       if (DestReg) {
23249         Res.first = DestReg;
23250         Res.second = &X86::GR8RegClass;
23251       }
23252     } else if (VT == MVT::i32 || VT == MVT::f32) {
23253       unsigned DestReg = 0;
23254       switch (Res.first) {
23255       default: break;
23256       case X86::AX: DestReg = X86::EAX; break;
23257       case X86::DX: DestReg = X86::EDX; break;
23258       case X86::CX: DestReg = X86::ECX; break;
23259       case X86::BX: DestReg = X86::EBX; break;
23260       case X86::SI: DestReg = X86::ESI; break;
23261       case X86::DI: DestReg = X86::EDI; break;
23262       case X86::BP: DestReg = X86::EBP; break;
23263       case X86::SP: DestReg = X86::ESP; break;
23264       }
23265       if (DestReg) {
23266         Res.first = DestReg;
23267         Res.second = &X86::GR32RegClass;
23268       }
23269     } else if (VT == MVT::i64 || VT == MVT::f64) {
23270       unsigned DestReg = 0;
23271       switch (Res.first) {
23272       default: break;
23273       case X86::AX: DestReg = X86::RAX; break;
23274       case X86::DX: DestReg = X86::RDX; break;
23275       case X86::CX: DestReg = X86::RCX; break;
23276       case X86::BX: DestReg = X86::RBX; break;
23277       case X86::SI: DestReg = X86::RSI; break;
23278       case X86::DI: DestReg = X86::RDI; break;
23279       case X86::BP: DestReg = X86::RBP; break;
23280       case X86::SP: DestReg = X86::RSP; break;
23281       }
23282       if (DestReg) {
23283         Res.first = DestReg;
23284         Res.second = &X86::GR64RegClass;
23285       }
23286     }
23287   } else if (Res.second == &X86::FR32RegClass ||
23288              Res.second == &X86::FR64RegClass ||
23289              Res.second == &X86::VR128RegClass ||
23290              Res.second == &X86::VR256RegClass ||
23291              Res.second == &X86::FR32XRegClass ||
23292              Res.second == &X86::FR64XRegClass ||
23293              Res.second == &X86::VR128XRegClass ||
23294              Res.second == &X86::VR256XRegClass ||
23295              Res.second == &X86::VR512RegClass) {
23296     // Handle references to XMM physical registers that got mapped into the
23297     // wrong class.  This can happen with constraints like {xmm0} where the
23298     // target independent register mapper will just pick the first match it can
23299     // find, ignoring the required type.
23300
23301     if (VT == MVT::f32 || VT == MVT::i32)
23302       Res.second = &X86::FR32RegClass;
23303     else if (VT == MVT::f64 || VT == MVT::i64)
23304       Res.second = &X86::FR64RegClass;
23305     else if (X86::VR128RegClass.hasType(VT))
23306       Res.second = &X86::VR128RegClass;
23307     else if (X86::VR256RegClass.hasType(VT))
23308       Res.second = &X86::VR256RegClass;
23309     else if (X86::VR512RegClass.hasType(VT))
23310       Res.second = &X86::VR512RegClass;
23311   }
23312
23313   return Res;
23314 }
23315
23316 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23317                                             Type *Ty) const {
23318   // Scaling factors are not free at all.
23319   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23320   // will take 2 allocations in the out of order engine instead of 1
23321   // for plain addressing mode, i.e. inst (reg1).
23322   // E.g.,
23323   // vaddps (%rsi,%drx), %ymm0, %ymm1
23324   // Requires two allocations (one for the load, one for the computation)
23325   // whereas:
23326   // vaddps (%rsi), %ymm0, %ymm1
23327   // Requires just 1 allocation, i.e., freeing allocations for other operations
23328   // and having less micro operations to execute.
23329   //
23330   // For some X86 architectures, this is even worse because for instance for
23331   // stores, the complex addressing mode forces the instruction to use the
23332   // "load" ports instead of the dedicated "store" port.
23333   // E.g., on Haswell:
23334   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23335   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23336   if (isLegalAddressingMode(AM, Ty))
23337     // Scale represents reg2 * scale, thus account for 1
23338     // as soon as we use a second register.
23339     return AM.Scale != 0;
23340   return -1;
23341 }
23342
23343 bool X86TargetLowering::isTargetFTOL() const {
23344   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23345 }