Lower vselects into X86ISD::BLENDI when appropriate.
[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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183   bool is64Bit = Subtarget->is64Bit();
184
185   if (Subtarget->isTargetMacho()) {
186     if (is64Bit)
187       return new X86_64MachoTargetObjectFile();
188     return new TargetLoweringObjectFileMachO();
189   }
190
191   if (Subtarget->isTargetLinux())
192     return new X86LinuxTargetObjectFile();
193   if (Subtarget->isTargetELF())
194     return new TargetLoweringObjectFileELF();
195   if (Subtarget->isTargetKnownWindowsMSVC())
196     return new X86WindowsTargetObjectFile();
197   if (Subtarget->isTargetCOFF())
198     return new TargetLoweringObjectFileCOFF();
199   llvm_unreachable("unknown subtarget type");
200 }
201
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203   : TargetLowering(TM, createTLOF(TM)) {
204   Subtarget = &TM.getSubtarget<X86Subtarget>();
205   X86ScalarSSEf64 = Subtarget->hasSSE2();
206   X86ScalarSSEf32 = Subtarget->hasSSE1();
207   TD = getDataLayout();
208
209   resetOperationActions();
210 }
211
212 void X86TargetLowering::resetOperationActions() {
213   const TargetMachine &TM = getTargetMachine();
214   static bool FirstTimeThrough = true;
215
216   // If none of the target options have changed, then we don't need to reset the
217   // operation actions.
218   if (!FirstTimeThrough && TO == TM.Options) return;
219
220   if (!FirstTimeThrough) {
221     // Reinitialize the actions.
222     initActions();
223     FirstTimeThrough = false;
224   }
225
226   TO = TM.Options;
227
228   // Set up the TargetLowering object.
229   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230
231   // X86 is weird, it always uses i8 for shift amounts and setcc results.
232   setBooleanContents(ZeroOrOneBooleanContent);
233   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235
236   // For 64-bit since we have so many registers use the ILP scheduler, for
237   // 32-bit code use the register pressure specific scheduling.
238   // For Atom, always use ILP scheduling.
239   if (Subtarget->isAtom())
240     setSchedulingPreference(Sched::ILP);
241   else if (Subtarget->is64Bit())
242     setSchedulingPreference(Sched::ILP);
243   else
244     setSchedulingPreference(Sched::RegPressure);
245   const X86RegisterInfo *RegInfo =
246     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248
249   // Bypass expensive divides on Atom when compiling with O2
250   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251     addBypassSlowDiv(32, 8);
252     if (Subtarget->is64Bit())
253       addBypassSlowDiv(64, 16);
254   }
255
256   if (Subtarget->isTargetKnownWindowsMSVC()) {
257     // Setup Windows compiler runtime calls.
258     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260     setLibcallName(RTLIB::SREM_I64, "_allrem");
261     setLibcallName(RTLIB::UREM_I64, "_aullrem");
262     setLibcallName(RTLIB::MUL_I64, "_allmul");
263     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268
269     // The _ftol2 runtime function has an unusual calling conv, which
270     // is modeled by a special pseudo-instruction.
271     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275   }
276
277   if (Subtarget->isTargetDarwin()) {
278     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279     setUseUnderscoreSetJmp(false);
280     setUseUnderscoreLongJmp(false);
281   } else if (Subtarget->isTargetWindowsGNU()) {
282     // MS runtime is weird: it exports _setjmp, but longjmp!
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(false);
285   } else {
286     setUseUnderscoreSetJmp(true);
287     setUseUnderscoreLongJmp(true);
288   }
289
290   // Set up the register classes.
291   addRegisterClass(MVT::i8, &X86::GR8RegClass);
292   addRegisterClass(MVT::i16, &X86::GR16RegClass);
293   addRegisterClass(MVT::i32, &X86::GR32RegClass);
294   if (Subtarget->is64Bit())
295     addRegisterClass(MVT::i64, &X86::GR64RegClass);
296
297   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298
299   // We don't accept any truncstore of integer registers.
300   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
450   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
451   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
452   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
454   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
455   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
456   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
457
458   // Promote the i8 variants and force them on up to i32 which has a shorter
459   // encoding.
460   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
462   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
463   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
464   if (Subtarget->hasBMI()) {
465     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
466     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469   } else {
470     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
471     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
474   }
475
476   if (Subtarget->hasLZCNT()) {
477     // When promoting the i8 variants, force them to i32 for a shorter
478     // encoding.
479     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
482     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
483     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
494     if (Subtarget->is64Bit()) {
495       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
496       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497     }
498   }
499
500   if (Subtarget->hasPOPCNT()) {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
502   } else {
503     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
504     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
506     if (Subtarget->is64Bit())
507       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
508   }
509
510   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
511
512   if (!Subtarget->hasMOVBE())
513     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
514
515   // These should be promoted to a larger select which is supported.
516   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
517   // X86 wants to expand cmov itself.
518   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
519   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
530   if (Subtarget->is64Bit()) {
531     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
532     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
533   }
534   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543
544   // Darwin ABI issue.
545   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
546   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
547   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
549   if (Subtarget->is64Bit())
550     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
552   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
553   if (Subtarget->is64Bit()) {
554     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
555     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
556     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
557     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
558     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
559   }
560   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
562   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
566     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
568   }
569
570   if (Subtarget->hasSSE1())
571     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
572
573   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
574
575   // Expand certain atomics
576   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577     MVT VT = IntVTs[i];
578     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581   }
582
583   if (!Subtarget->is64Bit()) {
584     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596   }
597
598   if (Subtarget->hasCmpxchg16b()) {
599     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600   }
601
602   // FIXME - use subtarget debug flags
603   if (!Subtarget->isTargetDarwin() &&
604       !Subtarget->isTargetELF() &&
605       !Subtarget->isTargetCygMing()) {
606     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607   }
608
609   if (Subtarget->is64Bit()) {
610     setExceptionPointerRegister(X86::RAX);
611     setExceptionSelectorRegister(X86::RDX);
612   } else {
613     setExceptionPointerRegister(X86::EAX);
614     setExceptionSelectorRegister(X86::EDX);
615   }
616   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618
619   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621
622   setOperationAction(ISD::TRAP, MVT::Other, Legal);
623   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624
625   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
627   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
628   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629     // TargetInfo::X86_64ABIBuiltinVaList
630     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
631     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
632   } else {
633     // TargetInfo::CharPtrBuiltinVaList
634     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
635     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
636   }
637
638   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
639   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
640
641   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                      MVT::i64 : MVT::i32, Custom);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHS, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::MULHU, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
946     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
947     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
948     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
950     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
951     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
952     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
953     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
954     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
957     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
958     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
959     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
960     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
961
962     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
964     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
965     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
966
967     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
968     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
971     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
972
973     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975       MVT VT = (MVT::SimpleValueType)i;
976       // Do not attempt to custom lower non-power-of-2 vectors
977       if (!isPowerOf2_32(VT.getVectorNumElements()))
978         continue;
979       // Do not attempt to custom lower non-128-bit vectors
980       if (!VT.is128BitVector())
981         continue;
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985     }
986
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
988     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
990     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993
994     if (Subtarget->is64Bit()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997     }
998
999     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002
1003       // Do not attempt to promote non-128-bit vectors
1004       if (!VT.is128BitVector())
1005         continue;
1006
1007       setOperationAction(ISD::AND,    VT, Promote);
1008       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1009       setOperationAction(ISD::OR,     VT, Promote);
1010       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1011       setOperationAction(ISD::XOR,    VT, Promote);
1012       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1013       setOperationAction(ISD::LOAD,   VT, Promote);
1014       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1015       setOperationAction(ISD::SELECT, VT, Promote);
1016       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017     }
1018
1019     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020
1021     // Custom lower v2i64 and v2f64 selects.
1022     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1024     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1025     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1026
1027     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1028     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1029
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1031     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1032     // As there is no 64-bit GPR available, we need build a special custom
1033     // sequence to convert from v2i32 to v2f32.
1034     if (!Subtarget->is64Bit())
1035       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1036
1037     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1038     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1039
1040     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1041
1042     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1043   }
1044
1045   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1049     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1051     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1054     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1056
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1062     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1063     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1064     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1065     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1066     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1067
1068     // FIXME: Do we need to handle scalar-to-vector here?
1069     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1072     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1073     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1074     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1075     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1076     // There is no BLENDI for byte vectors. We don't need to custom lower
1077     // some vselects for now.
1078     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1079
1080     // i8 and i16 vectors are custom , because the source register and source
1081     // source memory operand types are not the same width.  f32 vectors are
1082     // custom since the immediate controlling the insert encodes additional
1083     // information.
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1085     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1087     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1088
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1090     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1091     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1092     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1093
1094     // FIXME: these should be Legal but thats only for the case where
1095     // the index is constant.  For now custom expand to deal with that.
1096     if (Subtarget->is64Bit()) {
1097       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1098       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1099     }
1100   }
1101
1102   if (Subtarget->hasSSE2()) {
1103     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1110     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1111
1112     // In the customized shift lowering, the legal cases in AVX2 will be
1113     // recognized.
1114     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1115     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1116
1117     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1118     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1121   }
1122
1123   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1124     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1125     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1126     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1127     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1128     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1129     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1130
1131     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1133     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1134
1135     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1137     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1139     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1140     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1141     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1142     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1143     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1144     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1145     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1146     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1147
1148     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1150     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1152     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1153     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1154     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1155     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1156     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1157     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1158     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1159     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1160
1161     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1162     // even though v8i16 is a legal type.
1163     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1164     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1165     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1166
1167     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1168     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1169     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1170
1171     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1172     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1173
1174     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1175
1176     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1177     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1178
1179     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1180     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1181
1182     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1183     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1184
1185     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1186     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1187     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1188     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1189
1190     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1191     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1192     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1193
1194     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1195     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1196     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1197     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1200     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1201     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1202     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1203     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1204     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1205     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1206     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1207     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1208     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1209     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1210     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1211
1212     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1213       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1214       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1215       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1216       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1217       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1218       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1219     }
1220
1221     if (Subtarget->hasInt256()) {
1222       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1223       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1224       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1225       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1226
1227       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1228       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1229       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1230       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1231
1232       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1234       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1235       // Don't lower v32i8 because there is no 128-bit byte mul
1236
1237       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1238       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1239       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1240       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1241
1242       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1243       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1244     } else {
1245       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1246       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1247       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1248       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1249
1250       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1251       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1252       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1253       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1254
1255       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1256       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1257       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1258       // Don't lower v32i8 because there is no 128-bit byte mul
1259     }
1260
1261     // In the customized shift lowering, the legal cases in AVX2 will be
1262     // recognized.
1263     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1264     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1265
1266     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1267     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1268
1269     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1270
1271     // Custom lower several nodes for 256-bit types.
1272     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1273              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1274       MVT VT = (MVT::SimpleValueType)i;
1275
1276       // Extract subvector is special because the value type
1277       // (result) is 128-bit but the source is 256-bit wide.
1278       if (VT.is128BitVector())
1279         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1280
1281       // Do not attempt to custom lower other non-256-bit vectors
1282       if (!VT.is256BitVector())
1283         continue;
1284
1285       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1286       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1287       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1288       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1289       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1290       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1291       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1292     }
1293
1294     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1296       MVT VT = (MVT::SimpleValueType)i;
1297
1298       // Do not attempt to promote non-256-bit vectors
1299       if (!VT.is256BitVector())
1300         continue;
1301
1302       setOperationAction(ISD::AND,    VT, Promote);
1303       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1304       setOperationAction(ISD::OR,     VT, Promote);
1305       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1306       setOperationAction(ISD::XOR,    VT, Promote);
1307       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1308       setOperationAction(ISD::LOAD,   VT, Promote);
1309       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1310       setOperationAction(ISD::SELECT, VT, Promote);
1311       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1312     }
1313   }
1314
1315   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1316     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1317     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1318     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1319     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1320
1321     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1322     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1323     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1324
1325     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1326     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1327     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1328     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1329     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1330     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1335     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1336
1337     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1341     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1342     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1343
1344     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1350     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1351     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1352
1353     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1357     if (Subtarget->is64Bit()) {
1358       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1359       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1360       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1361       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1362     }
1363     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1365     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1366     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1371     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1372     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1373
1374     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1376     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1377     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1378     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1380     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1381     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1383     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1384     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1385     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1386     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1387
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1390     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1391     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1392     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1393     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1394
1395     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1396     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1397
1398     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1399
1400     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1401     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1402     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1403     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1404     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1405     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1407     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1408     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1409
1410     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1411     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1412
1413     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1415
1416     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1417
1418     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1419     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1420
1421     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1422     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1423
1424     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1425     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1426
1427     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1428     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1429     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1430     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1431     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1432     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1433
1434     // Custom lower several nodes.
1435     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1436              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1437       MVT VT = (MVT::SimpleValueType)i;
1438
1439       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1440       // Extract subvector is special because the value type
1441       // (result) is 256/128-bit but the source is 512-bit wide.
1442       if (VT.is128BitVector() || VT.is256BitVector())
1443         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1444
1445       if (VT.getVectorElementType() == MVT::i1)
1446         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1447
1448       // Do not attempt to custom lower other non-512-bit vectors
1449       if (!VT.is512BitVector())
1450         continue;
1451
1452       if ( EltSize >= 32) {
1453         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1454         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1455         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1456         setOperationAction(ISD::VSELECT,             VT, Legal);
1457         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1458         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1459         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1460       }
1461     }
1462     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1463       MVT VT = (MVT::SimpleValueType)i;
1464
1465       // Do not attempt to promote non-256-bit vectors
1466       if (!VT.is512BitVector())
1467         continue;
1468
1469       setOperationAction(ISD::SELECT, VT, Promote);
1470       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1471     }
1472   }// has  AVX-512
1473
1474   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1475   // of this type with custom code.
1476   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1477            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1478     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1479                        Custom);
1480   }
1481
1482   // We want to custom lower some of our intrinsics.
1483   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1484   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1485   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1486   if (!Subtarget->is64Bit())
1487     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1488
1489   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1490   // handle type legalization for these operations here.
1491   //
1492   // FIXME: We really should do custom legalization for addition and
1493   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1494   // than generic legalization for 64-bit multiplication-with-overflow, though.
1495   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1496     // Add/Sub/Mul with overflow operations are custom lowered.
1497     MVT VT = IntVTs[i];
1498     setOperationAction(ISD::SADDO, VT, Custom);
1499     setOperationAction(ISD::UADDO, VT, Custom);
1500     setOperationAction(ISD::SSUBO, VT, Custom);
1501     setOperationAction(ISD::USUBO, VT, Custom);
1502     setOperationAction(ISD::SMULO, VT, Custom);
1503     setOperationAction(ISD::UMULO, VT, Custom);
1504   }
1505
1506   // There are no 8-bit 3-address imul/mul instructions
1507   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1508   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1509
1510   if (!Subtarget->is64Bit()) {
1511     // These libcalls are not available in 32-bit.
1512     setLibcallName(RTLIB::SHL_I128, nullptr);
1513     setLibcallName(RTLIB::SRL_I128, nullptr);
1514     setLibcallName(RTLIB::SRA_I128, nullptr);
1515   }
1516
1517   // Combine sin / cos into one node or libcall if possible.
1518   if (Subtarget->hasSinCos()) {
1519     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1520     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1521     if (Subtarget->isTargetDarwin()) {
1522       // For MacOSX, we don't want to the normal expansion of a libcall to
1523       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1524       // traffic.
1525       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1526       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1527     }
1528   }
1529
1530   if (Subtarget->isTargetWin64()) {
1531     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1532     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1533     setOperationAction(ISD::SREM, MVT::i128, Custom);
1534     setOperationAction(ISD::UREM, MVT::i128, Custom);
1535     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1536     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1537   }
1538
1539   // We have target-specific dag combine patterns for the following nodes:
1540   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1541   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1542   setTargetDAGCombine(ISD::VSELECT);
1543   setTargetDAGCombine(ISD::SELECT);
1544   setTargetDAGCombine(ISD::SHL);
1545   setTargetDAGCombine(ISD::SRA);
1546   setTargetDAGCombine(ISD::SRL);
1547   setTargetDAGCombine(ISD::OR);
1548   setTargetDAGCombine(ISD::AND);
1549   setTargetDAGCombine(ISD::ADD);
1550   setTargetDAGCombine(ISD::FADD);
1551   setTargetDAGCombine(ISD::FSUB);
1552   setTargetDAGCombine(ISD::FMA);
1553   setTargetDAGCombine(ISD::SUB);
1554   setTargetDAGCombine(ISD::LOAD);
1555   setTargetDAGCombine(ISD::STORE);
1556   setTargetDAGCombine(ISD::ZERO_EXTEND);
1557   setTargetDAGCombine(ISD::ANY_EXTEND);
1558   setTargetDAGCombine(ISD::SIGN_EXTEND);
1559   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1560   setTargetDAGCombine(ISD::TRUNCATE);
1561   setTargetDAGCombine(ISD::SINT_TO_FP);
1562   setTargetDAGCombine(ISD::SETCC);
1563   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1564   if (Subtarget->is64Bit())
1565     setTargetDAGCombine(ISD::MUL);
1566   setTargetDAGCombine(ISD::XOR);
1567
1568   computeRegisterProperties();
1569
1570   // On Darwin, -Os means optimize for size without hurting performance,
1571   // do not reduce the limit.
1572   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1573   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1574   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1575   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1576   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1577   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578   setPrefLoopAlignment(4); // 2^4 bytes.
1579
1580   // Predictable cmov don't hurt on atom because it's in-order.
1581   PredictableSelectIsExpensive = !Subtarget->isAtom();
1582
1583   setPrefFunctionAlignment(4); // 2^4 bytes.
1584 }
1585
1586 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1587   if (!VT.isVector())
1588     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1589
1590   if (Subtarget->hasAVX512())
1591     switch(VT.getVectorNumElements()) {
1592     case  8: return MVT::v8i1;
1593     case 16: return MVT::v16i1;
1594   }
1595
1596   return VT.changeVectorElementTypeToInteger();
1597 }
1598
1599 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1600 /// the desired ByVal argument alignment.
1601 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1602   if (MaxAlign == 16)
1603     return;
1604   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1605     if (VTy->getBitWidth() == 128)
1606       MaxAlign = 16;
1607   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1608     unsigned EltAlign = 0;
1609     getMaxByValAlign(ATy->getElementType(), EltAlign);
1610     if (EltAlign > MaxAlign)
1611       MaxAlign = EltAlign;
1612   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1613     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1614       unsigned EltAlign = 0;
1615       getMaxByValAlign(STy->getElementType(i), EltAlign);
1616       if (EltAlign > MaxAlign)
1617         MaxAlign = EltAlign;
1618       if (MaxAlign == 16)
1619         break;
1620     }
1621   }
1622 }
1623
1624 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1625 /// function arguments in the caller parameter area. For X86, aggregates
1626 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1627 /// are at 4-byte boundaries.
1628 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1629   if (Subtarget->is64Bit()) {
1630     // Max of 8 and alignment of type.
1631     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1632     if (TyAlign > 8)
1633       return TyAlign;
1634     return 8;
1635   }
1636
1637   unsigned Align = 4;
1638   if (Subtarget->hasSSE1())
1639     getMaxByValAlign(Ty, Align);
1640   return Align;
1641 }
1642
1643 /// getOptimalMemOpType - Returns the target specific optimal type for load
1644 /// and store operations as a result of memset, memcpy, and memmove
1645 /// lowering. If DstAlign is zero that means it's safe to destination
1646 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1647 /// means there isn't a need to check it against alignment requirement,
1648 /// probably because the source does not need to be loaded. If 'IsMemset' is
1649 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1650 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1651 /// source is constant so it does not need to be loaded.
1652 /// It returns EVT::Other if the type should be determined using generic
1653 /// target-independent logic.
1654 EVT
1655 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1656                                        unsigned DstAlign, unsigned SrcAlign,
1657                                        bool IsMemset, bool ZeroMemset,
1658                                        bool MemcpyStrSrc,
1659                                        MachineFunction &MF) const {
1660   const Function *F = MF.getFunction();
1661   if ((!IsMemset || ZeroMemset) &&
1662       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1663                                        Attribute::NoImplicitFloat)) {
1664     if (Size >= 16 &&
1665         (Subtarget->isUnalignedMemAccessFast() ||
1666          ((DstAlign == 0 || DstAlign >= 16) &&
1667           (SrcAlign == 0 || SrcAlign >= 16)))) {
1668       if (Size >= 32) {
1669         if (Subtarget->hasInt256())
1670           return MVT::v8i32;
1671         if (Subtarget->hasFp256())
1672           return MVT::v8f32;
1673       }
1674       if (Subtarget->hasSSE2())
1675         return MVT::v4i32;
1676       if (Subtarget->hasSSE1())
1677         return MVT::v4f32;
1678     } else if (!MemcpyStrSrc && Size >= 8 &&
1679                !Subtarget->is64Bit() &&
1680                Subtarget->hasSSE2()) {
1681       // Do not use f64 to lower memcpy if source is string constant. It's
1682       // better to use i32 to avoid the loads.
1683       return MVT::f64;
1684     }
1685   }
1686   if (Subtarget->is64Bit() && Size >= 8)
1687     return MVT::i64;
1688   return MVT::i32;
1689 }
1690
1691 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1692   if (VT == MVT::f32)
1693     return X86ScalarSSEf32;
1694   else if (VT == MVT::f64)
1695     return X86ScalarSSEf64;
1696   return true;
1697 }
1698
1699 bool
1700 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1701                                                  unsigned,
1702                                                  bool *Fast) const {
1703   if (Fast)
1704     *Fast = Subtarget->isUnalignedMemAccessFast();
1705   return true;
1706 }
1707
1708 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1709 /// current function.  The returned value is a member of the
1710 /// MachineJumpTableInfo::JTEntryKind enum.
1711 unsigned X86TargetLowering::getJumpTableEncoding() const {
1712   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1713   // symbol.
1714   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1715       Subtarget->isPICStyleGOT())
1716     return MachineJumpTableInfo::EK_Custom32;
1717
1718   // Otherwise, use the normal jump table encoding heuristics.
1719   return TargetLowering::getJumpTableEncoding();
1720 }
1721
1722 const MCExpr *
1723 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1724                                              const MachineBasicBlock *MBB,
1725                                              unsigned uid,MCContext &Ctx) const{
1726   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1727          Subtarget->isPICStyleGOT());
1728   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1729   // entries.
1730   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1731                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1732 }
1733
1734 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1735 /// jumptable.
1736 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1737                                                     SelectionDAG &DAG) const {
1738   if (!Subtarget->is64Bit())
1739     // This doesn't have SDLoc associated with it, but is not really the
1740     // same as a Register.
1741     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1742   return Table;
1743 }
1744
1745 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1746 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1747 /// MCExpr.
1748 const MCExpr *X86TargetLowering::
1749 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1750                              MCContext &Ctx) const {
1751   // X86-64 uses RIP relative addressing based on the jump table label.
1752   if (Subtarget->isPICStyleRIPRel())
1753     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1754
1755   // Otherwise, the reference is relative to the PIC base.
1756   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1757 }
1758
1759 // FIXME: Why this routine is here? Move to RegInfo!
1760 std::pair<const TargetRegisterClass*, uint8_t>
1761 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1762   const TargetRegisterClass *RRC = nullptr;
1763   uint8_t Cost = 1;
1764   switch (VT.SimpleTy) {
1765   default:
1766     return TargetLowering::findRepresentativeClass(VT);
1767   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1768     RRC = Subtarget->is64Bit() ?
1769       (const TargetRegisterClass*)&X86::GR64RegClass :
1770       (const TargetRegisterClass*)&X86::GR32RegClass;
1771     break;
1772   case MVT::x86mmx:
1773     RRC = &X86::VR64RegClass;
1774     break;
1775   case MVT::f32: case MVT::f64:
1776   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1777   case MVT::v4f32: case MVT::v2f64:
1778   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1779   case MVT::v4f64:
1780     RRC = &X86::VR128RegClass;
1781     break;
1782   }
1783   return std::make_pair(RRC, Cost);
1784 }
1785
1786 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1787                                                unsigned &Offset) const {
1788   if (!Subtarget->isTargetLinux())
1789     return false;
1790
1791   if (Subtarget->is64Bit()) {
1792     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1793     Offset = 0x28;
1794     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1795       AddressSpace = 256;
1796     else
1797       AddressSpace = 257;
1798   } else {
1799     // %gs:0x14 on i386
1800     Offset = 0x14;
1801     AddressSpace = 256;
1802   }
1803   return true;
1804 }
1805
1806 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1807                                             unsigned DestAS) const {
1808   assert(SrcAS != DestAS && "Expected different address spaces!");
1809
1810   return SrcAS < 256 && DestAS < 256;
1811 }
1812
1813 //===----------------------------------------------------------------------===//
1814 //               Return Value Calling Convention Implementation
1815 //===----------------------------------------------------------------------===//
1816
1817 #include "X86GenCallingConv.inc"
1818
1819 bool
1820 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1821                                   MachineFunction &MF, bool isVarArg,
1822                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1823                         LLVMContext &Context) const {
1824   SmallVector<CCValAssign, 16> RVLocs;
1825   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826                  RVLocs, Context);
1827   return CCInfo.CheckReturn(Outs, RetCC_X86);
1828 }
1829
1830 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1831   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1832   return ScratchRegs;
1833 }
1834
1835 SDValue
1836 X86TargetLowering::LowerReturn(SDValue Chain,
1837                                CallingConv::ID CallConv, bool isVarArg,
1838                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1839                                const SmallVectorImpl<SDValue> &OutVals,
1840                                SDLoc dl, SelectionDAG &DAG) const {
1841   MachineFunction &MF = DAG.getMachineFunction();
1842   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843
1844   SmallVector<CCValAssign, 16> RVLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846                  RVLocs, *DAG.getContext());
1847   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1848
1849   SDValue Flag;
1850   SmallVector<SDValue, 6> RetOps;
1851   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1852   // Operand #1 = Bytes To Pop
1853   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1854                    MVT::i16));
1855
1856   // Copy the result values into the output registers.
1857   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1858     CCValAssign &VA = RVLocs[i];
1859     assert(VA.isRegLoc() && "Can only return in registers!");
1860     SDValue ValToCopy = OutVals[i];
1861     EVT ValVT = ValToCopy.getValueType();
1862
1863     // Promote values to the appropriate types
1864     if (VA.getLocInfo() == CCValAssign::SExt)
1865       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866     else if (VA.getLocInfo() == CCValAssign::ZExt)
1867       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868     else if (VA.getLocInfo() == CCValAssign::AExt)
1869       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870     else if (VA.getLocInfo() == CCValAssign::BCvt)
1871       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1872
1873     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1874            "Unexpected FP-extend for return value.");  
1875
1876     // If this is x86-64, and we disabled SSE, we can't return FP values,
1877     // or SSE or MMX vectors.
1878     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1879          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1880           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1881       report_fatal_error("SSE register return with SSE disabled");
1882     }
1883     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1884     // llvm-gcc has never done it right and no one has noticed, so this
1885     // should be OK for now.
1886     if (ValVT == MVT::f64 &&
1887         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1888       report_fatal_error("SSE2 register return with SSE2 disabled");
1889
1890     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1891     // the RET instruction and handled by the FP Stackifier.
1892     if (VA.getLocReg() == X86::ST0 ||
1893         VA.getLocReg() == X86::ST1) {
1894       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1895       // change the value to the FP stack register class.
1896       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1897         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1898       RetOps.push_back(ValToCopy);
1899       // Don't emit a copytoreg.
1900       continue;
1901     }
1902
1903     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1904     // which is returned in RAX / RDX.
1905     if (Subtarget->is64Bit()) {
1906       if (ValVT == MVT::x86mmx) {
1907         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1908           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1909           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1910                                   ValToCopy);
1911           // If we don't have SSE2 available, convert to v4f32 so the generated
1912           // register is legal.
1913           if (!Subtarget->hasSSE2())
1914             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1915         }
1916       }
1917     }
1918
1919     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1920     Flag = Chain.getValue(1);
1921     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1922   }
1923
1924   // The x86-64 ABIs require that for returning structs by value we copy
1925   // the sret argument into %rax/%eax (depending on ABI) for the return.
1926   // Win32 requires us to put the sret argument to %eax as well.
1927   // We saved the argument into a virtual register in the entry block,
1928   // so now we copy the value out and into %rax/%eax.
1929   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1930       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1931     MachineFunction &MF = DAG.getMachineFunction();
1932     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1933     unsigned Reg = FuncInfo->getSRetReturnReg();
1934     assert(Reg &&
1935            "SRetReturnReg should have been set in LowerFormalArguments().");
1936     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1937
1938     unsigned RetValReg
1939         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1940           X86::RAX : X86::EAX;
1941     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1942     Flag = Chain.getValue(1);
1943
1944     // RAX/EAX now acts like a return value.
1945     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1946   }
1947
1948   RetOps[0] = Chain;  // Update chain.
1949
1950   // Add the flag if we have it.
1951   if (Flag.getNode())
1952     RetOps.push_back(Flag);
1953
1954   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1955 }
1956
1957 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1958   if (N->getNumValues() != 1)
1959     return false;
1960   if (!N->hasNUsesOfValue(1, 0))
1961     return false;
1962
1963   SDValue TCChain = Chain;
1964   SDNode *Copy = *N->use_begin();
1965   if (Copy->getOpcode() == ISD::CopyToReg) {
1966     // If the copy has a glue operand, we conservatively assume it isn't safe to
1967     // perform a tail call.
1968     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969       return false;
1970     TCChain = Copy->getOperand(0);
1971   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1972     return false;
1973
1974   bool HasRet = false;
1975   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1976        UI != UE; ++UI) {
1977     if (UI->getOpcode() != X86ISD::RET_FLAG)
1978       return false;
1979     HasRet = true;
1980   }
1981
1982   if (!HasRet)
1983     return false;
1984
1985   Chain = TCChain;
1986   return true;
1987 }
1988
1989 MVT
1990 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1991                                             ISD::NodeType ExtendKind) const {
1992   MVT ReturnMVT;
1993   // TODO: Is this also valid on 32-bit?
1994   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1995     ReturnMVT = MVT::i8;
1996   else
1997     ReturnMVT = MVT::i32;
1998
1999   MVT MinVT = getRegisterType(ReturnMVT);
2000   return VT.bitsLT(MinVT) ? MinVT : VT;
2001 }
2002
2003 /// LowerCallResult - Lower the result values of a call into the
2004 /// appropriate copies out of appropriate physical registers.
2005 ///
2006 SDValue
2007 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2008                                    CallingConv::ID CallConv, bool isVarArg,
2009                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2010                                    SDLoc dl, SelectionDAG &DAG,
2011                                    SmallVectorImpl<SDValue> &InVals) const {
2012
2013   // Assign locations to each value returned by this call.
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   bool Is64Bit = Subtarget->is64Bit();
2016   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2017                  getTargetMachine(), RVLocs, *DAG.getContext());
2018   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2019
2020   // Copy all of the result registers out of their specified physreg.
2021   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2022     CCValAssign &VA = RVLocs[i];
2023     EVT CopyVT = VA.getValVT();
2024
2025     // If this is x86-64, and we disabled SSE, we can't return FP values
2026     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2027         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2028       report_fatal_error("SSE register return with SSE disabled");
2029     }
2030
2031     SDValue Val;
2032
2033     // If this is a call to a function that returns an fp value on the floating
2034     // point stack, we must guarantee the value is popped from the stack, so
2035     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2036     // if the return value is not used. We use the FpPOP_RETVAL instruction
2037     // instead.
2038     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2039       // If we prefer to use the value in xmm registers, copy it out as f80 and
2040       // use a truncate to move it from fp stack reg to xmm reg.
2041       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2042       SDValue Ops[] = { Chain, InFlag };
2043       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2044                                          MVT::Other, MVT::Glue, Ops), 1);
2045       Val = Chain.getValue(0);
2046
2047       // Round the f80 to the right size, which also moves it to the appropriate
2048       // xmm register.
2049       if (CopyVT != VA.getValVT())
2050         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2051                           // This truncation won't change the value.
2052                           DAG.getIntPtrConstant(1));
2053     } else {
2054       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2055                                  CopyVT, InFlag).getValue(1);
2056       Val = Chain.getValue(0);
2057     }
2058     InFlag = Chain.getValue(2);
2059     InVals.push_back(Val);
2060   }
2061
2062   return Chain;
2063 }
2064
2065 //===----------------------------------------------------------------------===//
2066 //                C & StdCall & Fast Calling Convention implementation
2067 //===----------------------------------------------------------------------===//
2068 //  StdCall calling convention seems to be standard for many Windows' API
2069 //  routines and around. It differs from C calling convention just a little:
2070 //  callee should clean up the stack, not caller. Symbols should be also
2071 //  decorated in some fancy way :) It doesn't support any vector arguments.
2072 //  For info on fast calling convention see Fast Calling Convention (tail call)
2073 //  implementation LowerX86_32FastCCCallTo.
2074
2075 /// CallIsStructReturn - Determines whether a call uses struct return
2076 /// semantics.
2077 enum StructReturnType {
2078   NotStructReturn,
2079   RegStructReturn,
2080   StackStructReturn
2081 };
2082 static StructReturnType
2083 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2084   if (Outs.empty())
2085     return NotStructReturn;
2086
2087   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2088   if (!Flags.isSRet())
2089     return NotStructReturn;
2090   if (Flags.isInReg())
2091     return RegStructReturn;
2092   return StackStructReturn;
2093 }
2094
2095 /// ArgsAreStructReturn - Determines whether a function uses struct
2096 /// return semantics.
2097 static StructReturnType
2098 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2099   if (Ins.empty())
2100     return NotStructReturn;
2101
2102   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2103   if (!Flags.isSRet())
2104     return NotStructReturn;
2105   if (Flags.isInReg())
2106     return RegStructReturn;
2107   return StackStructReturn;
2108 }
2109
2110 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2111 /// by "Src" to address "Dst" with size and alignment information specified by
2112 /// the specific parameter attribute. The copy will be passed as a byval
2113 /// function parameter.
2114 static SDValue
2115 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2116                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2117                           SDLoc dl) {
2118   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2119
2120   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2121                        /*isVolatile*/false, /*AlwaysInline=*/true,
2122                        MachinePointerInfo(), MachinePointerInfo());
2123 }
2124
2125 /// IsTailCallConvention - Return true if the calling convention is one that
2126 /// supports tail call optimization.
2127 static bool IsTailCallConvention(CallingConv::ID CC) {
2128   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2129           CC == CallingConv::HiPE);
2130 }
2131
2132 /// \brief Return true if the calling convention is a C calling convention.
2133 static bool IsCCallConvention(CallingConv::ID CC) {
2134   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2135           CC == CallingConv::X86_64_SysV);
2136 }
2137
2138 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2139   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2140     return false;
2141
2142   CallSite CS(CI);
2143   CallingConv::ID CalleeCC = CS.getCallingConv();
2144   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2145     return false;
2146
2147   return true;
2148 }
2149
2150 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2151 /// a tailcall target by changing its ABI.
2152 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2153                                    bool GuaranteedTailCallOpt) {
2154   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2155 }
2156
2157 SDValue
2158 X86TargetLowering::LowerMemArgument(SDValue Chain,
2159                                     CallingConv::ID CallConv,
2160                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2161                                     SDLoc dl, SelectionDAG &DAG,
2162                                     const CCValAssign &VA,
2163                                     MachineFrameInfo *MFI,
2164                                     unsigned i) const {
2165   // Create the nodes corresponding to a load from this parameter slot.
2166   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2167   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2168                               getTargetMachine().Options.GuaranteedTailCallOpt);
2169   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2170   EVT ValVT;
2171
2172   // If value is passed by pointer we have address passed instead of the value
2173   // itself.
2174   if (VA.getLocInfo() == CCValAssign::Indirect)
2175     ValVT = VA.getLocVT();
2176   else
2177     ValVT = VA.getValVT();
2178
2179   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2180   // changed with more analysis.
2181   // In case of tail call optimization mark all arguments mutable. Since they
2182   // could be overwritten by lowering of arguments in case of a tail call.
2183   if (Flags.isByVal()) {
2184     unsigned Bytes = Flags.getByValSize();
2185     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2186     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2187     return DAG.getFrameIndex(FI, getPointerTy());
2188   } else {
2189     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2190                                     VA.getLocMemOffset(), isImmutable);
2191     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2192     return DAG.getLoad(ValVT, dl, Chain, FIN,
2193                        MachinePointerInfo::getFixedStack(FI),
2194                        false, false, false, 0);
2195   }
2196 }
2197
2198 SDValue
2199 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2200                                         CallingConv::ID CallConv,
2201                                         bool isVarArg,
2202                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2203                                         SDLoc dl,
2204                                         SelectionDAG &DAG,
2205                                         SmallVectorImpl<SDValue> &InVals)
2206                                           const {
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2209
2210   const Function* Fn = MF.getFunction();
2211   if (Fn->hasExternalLinkage() &&
2212       Subtarget->isTargetCygMing() &&
2213       Fn->getName() == "main")
2214     FuncInfo->setForceFramePointer(true);
2215
2216   MachineFrameInfo *MFI = MF.getFrameInfo();
2217   bool Is64Bit = Subtarget->is64Bit();
2218   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2219
2220   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2221          "Var args not supported with calling convention fastcc, ghc or hipe");
2222
2223   // Assign locations to all of the incoming arguments.
2224   SmallVector<CCValAssign, 16> ArgLocs;
2225   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2226                  ArgLocs, *DAG.getContext());
2227
2228   // Allocate shadow area for Win64
2229   if (IsWin64)
2230     CCInfo.AllocateStack(32, 8);
2231
2232   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2233
2234   unsigned LastVal = ~0U;
2235   SDValue ArgValue;
2236   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2237     CCValAssign &VA = ArgLocs[i];
2238     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2239     // places.
2240     assert(VA.getValNo() != LastVal &&
2241            "Don't support value assigned to multiple locs yet");
2242     (void)LastVal;
2243     LastVal = VA.getValNo();
2244
2245     if (VA.isRegLoc()) {
2246       EVT RegVT = VA.getLocVT();
2247       const TargetRegisterClass *RC;
2248       if (RegVT == MVT::i32)
2249         RC = &X86::GR32RegClass;
2250       else if (Is64Bit && RegVT == MVT::i64)
2251         RC = &X86::GR64RegClass;
2252       else if (RegVT == MVT::f32)
2253         RC = &X86::FR32RegClass;
2254       else if (RegVT == MVT::f64)
2255         RC = &X86::FR64RegClass;
2256       else if (RegVT.is512BitVector())
2257         RC = &X86::VR512RegClass;
2258       else if (RegVT.is256BitVector())
2259         RC = &X86::VR256RegClass;
2260       else if (RegVT.is128BitVector())
2261         RC = &X86::VR128RegClass;
2262       else if (RegVT == MVT::x86mmx)
2263         RC = &X86::VR64RegClass;
2264       else if (RegVT == MVT::i1)
2265         RC = &X86::VK1RegClass;
2266       else if (RegVT == MVT::v8i1)
2267         RC = &X86::VK8RegClass;
2268       else if (RegVT == MVT::v16i1)
2269         RC = &X86::VK16RegClass;
2270       else
2271         llvm_unreachable("Unknown argument type!");
2272
2273       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2274       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2275
2276       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2277       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2278       // right size.
2279       if (VA.getLocInfo() == CCValAssign::SExt)
2280         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2281                                DAG.getValueType(VA.getValVT()));
2282       else if (VA.getLocInfo() == CCValAssign::ZExt)
2283         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2284                                DAG.getValueType(VA.getValVT()));
2285       else if (VA.getLocInfo() == CCValAssign::BCvt)
2286         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2287
2288       if (VA.isExtInLoc()) {
2289         // Handle MMX values passed in XMM regs.
2290         if (RegVT.isVector())
2291           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2292         else
2293           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2294       }
2295     } else {
2296       assert(VA.isMemLoc());
2297       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2298     }
2299
2300     // If value is passed via pointer - do a load.
2301     if (VA.getLocInfo() == CCValAssign::Indirect)
2302       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2303                              MachinePointerInfo(), false, false, false, 0);
2304
2305     InVals.push_back(ArgValue);
2306   }
2307
2308   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2309     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310       // The x86-64 ABIs require that for returning structs by value we copy
2311       // the sret argument into %rax/%eax (depending on ABI) for the return.
2312       // Win32 requires us to put the sret argument to %eax as well.
2313       // Save the argument into a virtual register so that we can access it
2314       // from the return points.
2315       if (Ins[i].Flags.isSRet()) {
2316         unsigned Reg = FuncInfo->getSRetReturnReg();
2317         if (!Reg) {
2318           MVT PtrTy = getPointerTy();
2319           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2320           FuncInfo->setSRetReturnReg(Reg);
2321         }
2322         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2323         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2324         break;
2325       }
2326     }
2327   }
2328
2329   unsigned StackSize = CCInfo.getNextStackOffset();
2330   // Align stack specially for tail calls.
2331   if (FuncIsMadeTailCallSafe(CallConv,
2332                              MF.getTarget().Options.GuaranteedTailCallOpt))
2333     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2334
2335   // If the function takes variable number of arguments, make a frame index for
2336   // the start of the first vararg value... for expansion of llvm.va_start.
2337   if (isVarArg) {
2338     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2339                     CallConv != CallingConv::X86_ThisCall)) {
2340       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2341     }
2342     if (Is64Bit) {
2343       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2344
2345       // FIXME: We should really autogenerate these arrays
2346       static const MCPhysReg GPR64ArgRegsWin64[] = {
2347         X86::RCX, X86::RDX, X86::R8,  X86::R9
2348       };
2349       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2350         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2351       };
2352       static const MCPhysReg XMMArgRegs64Bit[] = {
2353         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2354         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2355       };
2356       const MCPhysReg *GPR64ArgRegs;
2357       unsigned NumXMMRegs = 0;
2358
2359       if (IsWin64) {
2360         // The XMM registers which might contain var arg parameters are shadowed
2361         // in their paired GPR.  So we only need to save the GPR to their home
2362         // slots.
2363         TotalNumIntRegs = 4;
2364         GPR64ArgRegs = GPR64ArgRegsWin64;
2365       } else {
2366         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2367         GPR64ArgRegs = GPR64ArgRegs64Bit;
2368
2369         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2370                                                 TotalNumXMMRegs);
2371       }
2372       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2373                                                        TotalNumIntRegs);
2374
2375       bool NoImplicitFloatOps = Fn->getAttributes().
2376         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2378              "SSE register cannot be used when SSE is disabled!");
2379       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2380                NoImplicitFloatOps) &&
2381              "SSE register cannot be used when SSE is disabled!");
2382       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2383           !Subtarget->hasSSE1())
2384         // Kernel mode asks for SSE to be disabled, so don't push them
2385         // on the stack.
2386         TotalNumXMMRegs = 0;
2387
2388       if (IsWin64) {
2389         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2390         // Get to the caller-allocated home save location.  Add 8 to account
2391         // for the return address.
2392         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2393         FuncInfo->setRegSaveFrameIndex(
2394           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2395         // Fixup to set vararg frame on shadow area (4 x i64).
2396         if (NumIntRegs < 4)
2397           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2398       } else {
2399         // For X86-64, if there are vararg parameters that are passed via
2400         // registers, then we must store them to their spots on the stack so
2401         // they may be loaded by deferencing the result of va_next.
2402         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2403         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2404         FuncInfo->setRegSaveFrameIndex(
2405           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2406                                false));
2407       }
2408
2409       // Store the integer parameter registers.
2410       SmallVector<SDValue, 8> MemOps;
2411       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2412                                         getPointerTy());
2413       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2414       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2415         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2416                                   DAG.getIntPtrConstant(Offset));
2417         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2418                                      &X86::GR64RegClass);
2419         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2420         SDValue Store =
2421           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2422                        MachinePointerInfo::getFixedStack(
2423                          FuncInfo->getRegSaveFrameIndex(), Offset),
2424                        false, false, 0);
2425         MemOps.push_back(Store);
2426         Offset += 8;
2427       }
2428
2429       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2430         // Now store the XMM (fp + vector) parameter registers.
2431         SmallVector<SDValue, 11> SaveXMMOps;
2432         SaveXMMOps.push_back(Chain);
2433
2434         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2435         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2436         SaveXMMOps.push_back(ALVal);
2437
2438         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2439                                FuncInfo->getRegSaveFrameIndex()));
2440         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441                                FuncInfo->getVarArgsFPOffset()));
2442
2443         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2444           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2445                                        &X86::VR128RegClass);
2446           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2447           SaveXMMOps.push_back(Val);
2448         }
2449         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2450                                      MVT::Other, SaveXMMOps));
2451       }
2452
2453       if (!MemOps.empty())
2454         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2455     }
2456   }
2457
2458   // Some CCs need callee pop.
2459   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2460                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2461     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2462   } else {
2463     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2464     // If this is an sret function, the return should pop the hidden pointer.
2465     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2466         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2467         argsAreStructReturn(Ins) == StackStructReturn)
2468       FuncInfo->setBytesToPopOnReturn(4);
2469   }
2470
2471   if (!Is64Bit) {
2472     // RegSaveFrameIndex is X86-64 only.
2473     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2474     if (CallConv == CallingConv::X86_FastCall ||
2475         CallConv == CallingConv::X86_ThisCall)
2476       // fastcc functions can't have varargs.
2477       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2478   }
2479
2480   FuncInfo->setArgumentStackSize(StackSize);
2481
2482   return Chain;
2483 }
2484
2485 SDValue
2486 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2487                                     SDValue StackPtr, SDValue Arg,
2488                                     SDLoc dl, SelectionDAG &DAG,
2489                                     const CCValAssign &VA,
2490                                     ISD::ArgFlagsTy Flags) const {
2491   unsigned LocMemOffset = VA.getLocMemOffset();
2492   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2493   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2494   if (Flags.isByVal())
2495     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2496
2497   return DAG.getStore(Chain, dl, Arg, PtrOff,
2498                       MachinePointerInfo::getStack(LocMemOffset),
2499                       false, false, 0);
2500 }
2501
2502 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2503 /// optimization is performed and it is required.
2504 SDValue
2505 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2506                                            SDValue &OutRetAddr, SDValue Chain,
2507                                            bool IsTailCall, bool Is64Bit,
2508                                            int FPDiff, SDLoc dl) const {
2509   // Adjust the Return address stack slot.
2510   EVT VT = getPointerTy();
2511   OutRetAddr = getReturnAddressFrameIndex(DAG);
2512
2513   // Load the "old" Return address.
2514   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2515                            false, false, false, 0);
2516   return SDValue(OutRetAddr.getNode(), 1);
2517 }
2518
2519 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2520 /// optimization is performed and it is required (FPDiff!=0).
2521 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2522                                         SDValue Chain, SDValue RetAddrFrIdx,
2523                                         EVT PtrVT, unsigned SlotSize,
2524                                         int FPDiff, SDLoc dl) {
2525   // Store the return address to the appropriate stack slot.
2526   if (!FPDiff) return Chain;
2527   // Calculate the new stack slot for the return address.
2528   int NewReturnAddrFI =
2529     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2530                                          false);
2531   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2532   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2533                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2534                        false, false, 0);
2535   return Chain;
2536 }
2537
2538 SDValue
2539 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2540                              SmallVectorImpl<SDValue> &InVals) const {
2541   SelectionDAG &DAG                     = CLI.DAG;
2542   SDLoc &dl                             = CLI.DL;
2543   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2544   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2545   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2546   SDValue Chain                         = CLI.Chain;
2547   SDValue Callee                        = CLI.Callee;
2548   CallingConv::ID CallConv              = CLI.CallConv;
2549   bool &isTailCall                      = CLI.IsTailCall;
2550   bool isVarArg                         = CLI.IsVarArg;
2551
2552   MachineFunction &MF = DAG.getMachineFunction();
2553   bool Is64Bit        = Subtarget->is64Bit();
2554   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2555   StructReturnType SR = callIsStructReturn(Outs);
2556   bool IsSibcall      = false;
2557
2558   if (MF.getTarget().Options.DisableTailCalls)
2559     isTailCall = false;
2560
2561   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2562   if (IsMustTail) {
2563     // Force this to be a tail call.  The verifier rules are enough to ensure
2564     // that we can lower this successfully without moving the return address
2565     // around.
2566     isTailCall = true;
2567   } else if (isTailCall) {
2568     // Check if it's really possible to do a tail call.
2569     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2570                     isVarArg, SR != NotStructReturn,
2571                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2572                     Outs, OutVals, Ins, DAG);
2573
2574     // Sibcalls are automatically detected tailcalls which do not require
2575     // ABI changes.
2576     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2577       IsSibcall = true;
2578
2579     if (isTailCall)
2580       ++NumTailCalls;
2581   }
2582
2583   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2584          "Var args not supported with calling convention fastcc, ghc or hipe");
2585
2586   // Analyze operands of the call, assigning locations to each operand.
2587   SmallVector<CCValAssign, 16> ArgLocs;
2588   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2589                  ArgLocs, *DAG.getContext());
2590
2591   // Allocate shadow area for Win64
2592   if (IsWin64)
2593     CCInfo.AllocateStack(32, 8);
2594
2595   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2596
2597   // Get a count of how many bytes are to be pushed on the stack.
2598   unsigned NumBytes = CCInfo.getNextStackOffset();
2599   if (IsSibcall)
2600     // This is a sibcall. The memory operands are available in caller's
2601     // own caller's stack.
2602     NumBytes = 0;
2603   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2604            IsTailCallConvention(CallConv))
2605     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2606
2607   int FPDiff = 0;
2608   if (isTailCall && !IsSibcall && !IsMustTail) {
2609     // Lower arguments at fp - stackoffset + fpdiff.
2610     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2611     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2612
2613     FPDiff = NumBytesCallerPushed - NumBytes;
2614
2615     // Set the delta of movement of the returnaddr stackslot.
2616     // But only set if delta is greater than previous delta.
2617     if (FPDiff < X86Info->getTCReturnAddrDelta())
2618       X86Info->setTCReturnAddrDelta(FPDiff);
2619   }
2620
2621   unsigned NumBytesToPush = NumBytes;
2622   unsigned NumBytesToPop = NumBytes;
2623
2624   // If we have an inalloca argument, all stack space has already been allocated
2625   // for us and be right at the top of the stack.  We don't support multiple
2626   // arguments passed in memory when using inalloca.
2627   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2628     NumBytesToPush = 0;
2629     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2630            "an inalloca argument must be the only memory argument");
2631   }
2632
2633   if (!IsSibcall)
2634     Chain = DAG.getCALLSEQ_START(
2635         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2636
2637   SDValue RetAddrFrIdx;
2638   // Load return address for tail calls.
2639   if (isTailCall && FPDiff)
2640     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2641                                     Is64Bit, FPDiff, dl);
2642
2643   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2644   SmallVector<SDValue, 8> MemOpChains;
2645   SDValue StackPtr;
2646
2647   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2648   // of tail call optimization arguments are handle later.
2649   const X86RegisterInfo *RegInfo =
2650     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2651   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652     // Skip inalloca arguments, they have already been written.
2653     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2654     if (Flags.isInAlloca())
2655       continue;
2656
2657     CCValAssign &VA = ArgLocs[i];
2658     EVT RegVT = VA.getLocVT();
2659     SDValue Arg = OutVals[i];
2660     bool isByVal = Flags.isByVal();
2661
2662     // Promote the value if needed.
2663     switch (VA.getLocInfo()) {
2664     default: llvm_unreachable("Unknown loc info!");
2665     case CCValAssign::Full: break;
2666     case CCValAssign::SExt:
2667       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2668       break;
2669     case CCValAssign::ZExt:
2670       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2671       break;
2672     case CCValAssign::AExt:
2673       if (RegVT.is128BitVector()) {
2674         // Special case: passing MMX values in XMM registers.
2675         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2676         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2677         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2678       } else
2679         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2680       break;
2681     case CCValAssign::BCvt:
2682       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2683       break;
2684     case CCValAssign::Indirect: {
2685       // Store the argument.
2686       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2687       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2688       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2689                            MachinePointerInfo::getFixedStack(FI),
2690                            false, false, 0);
2691       Arg = SpillSlot;
2692       break;
2693     }
2694     }
2695
2696     if (VA.isRegLoc()) {
2697       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2698       if (isVarArg && IsWin64) {
2699         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2700         // shadow reg if callee is a varargs function.
2701         unsigned ShadowReg = 0;
2702         switch (VA.getLocReg()) {
2703         case X86::XMM0: ShadowReg = X86::RCX; break;
2704         case X86::XMM1: ShadowReg = X86::RDX; break;
2705         case X86::XMM2: ShadowReg = X86::R8; break;
2706         case X86::XMM3: ShadowReg = X86::R9; break;
2707         }
2708         if (ShadowReg)
2709           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2710       }
2711     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2712       assert(VA.isMemLoc());
2713       if (!StackPtr.getNode())
2714         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2715                                       getPointerTy());
2716       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2717                                              dl, DAG, VA, Flags));
2718     }
2719   }
2720
2721   if (!MemOpChains.empty())
2722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2723
2724   if (Subtarget->isPICStyleGOT()) {
2725     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2726     // GOT pointer.
2727     if (!isTailCall) {
2728       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2729                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2730     } else {
2731       // If we are tail calling and generating PIC/GOT style code load the
2732       // address of the callee into ECX. The value in ecx is used as target of
2733       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2734       // for tail calls on PIC/GOT architectures. Normally we would just put the
2735       // address of GOT into ebx and then call target@PLT. But for tail calls
2736       // ebx would be restored (since ebx is callee saved) before jumping to the
2737       // target@PLT.
2738
2739       // Note: The actual moving to ECX is done further down.
2740       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2741       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2742           !G->getGlobal()->hasProtectedVisibility())
2743         Callee = LowerGlobalAddress(Callee, DAG);
2744       else if (isa<ExternalSymbolSDNode>(Callee))
2745         Callee = LowerExternalSymbol(Callee, DAG);
2746     }
2747   }
2748
2749   if (Is64Bit && isVarArg && !IsWin64) {
2750     // From AMD64 ABI document:
2751     // For calls that may call functions that use varargs or stdargs
2752     // (prototype-less calls or calls to functions containing ellipsis (...) in
2753     // the declaration) %al is used as hidden argument to specify the number
2754     // of SSE registers used. The contents of %al do not need to match exactly
2755     // the number of registers, but must be an ubound on the number of SSE
2756     // registers used and is in the range 0 - 8 inclusive.
2757
2758     // Count the number of XMM registers allocated.
2759     static const MCPhysReg XMMArgRegs[] = {
2760       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2761       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2762     };
2763     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2764     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2765            && "SSE registers cannot be used when SSE is disabled");
2766
2767     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2768                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2769   }
2770
2771   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2772   // don't need this because the eligibility check rejects calls that require
2773   // shuffling arguments passed in memory.
2774   if (!IsSibcall && isTailCall) {
2775     // Force all the incoming stack arguments to be loaded from the stack
2776     // before any new outgoing arguments are stored to the stack, because the
2777     // outgoing stack slots may alias the incoming argument stack slots, and
2778     // the alias isn't otherwise explicit. This is slightly more conservative
2779     // than necessary, because it means that each store effectively depends
2780     // on every argument instead of just those arguments it would clobber.
2781     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2782
2783     SmallVector<SDValue, 8> MemOpChains2;
2784     SDValue FIN;
2785     int FI = 0;
2786     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787       CCValAssign &VA = ArgLocs[i];
2788       if (VA.isRegLoc())
2789         continue;
2790       assert(VA.isMemLoc());
2791       SDValue Arg = OutVals[i];
2792       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2793       // Skip inalloca arguments.  They don't require any work.
2794       if (Flags.isInAlloca())
2795         continue;
2796       // Create frame index.
2797       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2798       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2799       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2800       FIN = DAG.getFrameIndex(FI, getPointerTy());
2801
2802       if (Flags.isByVal()) {
2803         // Copy relative to framepointer.
2804         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2805         if (!StackPtr.getNode())
2806           StackPtr = DAG.getCopyFromReg(Chain, dl,
2807                                         RegInfo->getStackRegister(),
2808                                         getPointerTy());
2809         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2810
2811         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2812                                                          ArgChain,
2813                                                          Flags, DAG, dl));
2814       } else {
2815         // Store relative to framepointer.
2816         MemOpChains2.push_back(
2817           DAG.getStore(ArgChain, dl, Arg, FIN,
2818                        MachinePointerInfo::getFixedStack(FI),
2819                        false, false, 0));
2820       }
2821     }
2822
2823     if (!MemOpChains2.empty())
2824       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2825
2826     // Store the return address to the appropriate stack slot.
2827     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2828                                      getPointerTy(), RegInfo->getSlotSize(),
2829                                      FPDiff, dl);
2830   }
2831
2832   // Build a sequence of copy-to-reg nodes chained together with token chain
2833   // and flag operands which copy the outgoing args into registers.
2834   SDValue InFlag;
2835   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2836     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2837                              RegsToPass[i].second, InFlag);
2838     InFlag = Chain.getValue(1);
2839   }
2840
2841   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2842     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2843     // In the 64-bit large code model, we have to make all calls
2844     // through a register, since the call instruction's 32-bit
2845     // pc-relative offset may not be large enough to hold the whole
2846     // address.
2847   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2848     // If the callee is a GlobalAddress node (quite common, every direct call
2849     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2850     // it.
2851
2852     // We should use extra load for direct calls to dllimported functions in
2853     // non-JIT mode.
2854     const GlobalValue *GV = G->getGlobal();
2855     if (!GV->hasDLLImportStorageClass()) {
2856       unsigned char OpFlags = 0;
2857       bool ExtraLoad = false;
2858       unsigned WrapperKind = ISD::DELETED_NODE;
2859
2860       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2861       // external symbols most go through the PLT in PIC mode.  If the symbol
2862       // has hidden or protected visibility, or if it is static or local, then
2863       // we don't need to use the PLT - we can directly call it.
2864       if (Subtarget->isTargetELF() &&
2865           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2866           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2867         OpFlags = X86II::MO_PLT;
2868       } else if (Subtarget->isPICStyleStubAny() &&
2869                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2870                  (!Subtarget->getTargetTriple().isMacOSX() ||
2871                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2872         // PC-relative references to external symbols should go through $stub,
2873         // unless we're building with the leopard linker or later, which
2874         // automatically synthesizes these stubs.
2875         OpFlags = X86II::MO_DARWIN_STUB;
2876       } else if (Subtarget->isPICStyleRIPRel() &&
2877                  isa<Function>(GV) &&
2878                  cast<Function>(GV)->getAttributes().
2879                    hasAttribute(AttributeSet::FunctionIndex,
2880                                 Attribute::NonLazyBind)) {
2881         // If the function is marked as non-lazy, generate an indirect call
2882         // which loads from the GOT directly. This avoids runtime overhead
2883         // at the cost of eager binding (and one extra byte of encoding).
2884         OpFlags = X86II::MO_GOTPCREL;
2885         WrapperKind = X86ISD::WrapperRIP;
2886         ExtraLoad = true;
2887       }
2888
2889       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2890                                           G->getOffset(), OpFlags);
2891
2892       // Add a wrapper if needed.
2893       if (WrapperKind != ISD::DELETED_NODE)
2894         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2895       // Add extra indirection if needed.
2896       if (ExtraLoad)
2897         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2898                              MachinePointerInfo::getGOT(),
2899                              false, false, false, 0);
2900     }
2901   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2902     unsigned char OpFlags = 0;
2903
2904     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2905     // external symbols should go through the PLT.
2906     if (Subtarget->isTargetELF() &&
2907         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2908       OpFlags = X86II::MO_PLT;
2909     } else if (Subtarget->isPICStyleStubAny() &&
2910                (!Subtarget->getTargetTriple().isMacOSX() ||
2911                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2912       // PC-relative references to external symbols should go through $stub,
2913       // unless we're building with the leopard linker or later, which
2914       // automatically synthesizes these stubs.
2915       OpFlags = X86II::MO_DARWIN_STUB;
2916     }
2917
2918     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2919                                          OpFlags);
2920   }
2921
2922   // Returns a chain & a flag for retval copy to use.
2923   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2924   SmallVector<SDValue, 8> Ops;
2925
2926   if (!IsSibcall && isTailCall) {
2927     Chain = DAG.getCALLSEQ_END(Chain,
2928                                DAG.getIntPtrConstant(NumBytesToPop, true),
2929                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2930     InFlag = Chain.getValue(1);
2931   }
2932
2933   Ops.push_back(Chain);
2934   Ops.push_back(Callee);
2935
2936   if (isTailCall)
2937     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2938
2939   // Add argument registers to the end of the list so that they are known live
2940   // into the call.
2941   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2942     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2943                                   RegsToPass[i].second.getValueType()));
2944
2945   // Add a register mask operand representing the call-preserved registers.
2946   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2947   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2948   assert(Mask && "Missing call preserved mask for calling convention");
2949   Ops.push_back(DAG.getRegisterMask(Mask));
2950
2951   if (InFlag.getNode())
2952     Ops.push_back(InFlag);
2953
2954   if (isTailCall) {
2955     // We used to do:
2956     //// If this is the first return lowered for this function, add the regs
2957     //// to the liveout set for the function.
2958     // This isn't right, although it's probably harmless on x86; liveouts
2959     // should be computed from returns not tail calls.  Consider a void
2960     // function making a tail call to a function returning int.
2961     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2962   }
2963
2964   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2965   InFlag = Chain.getValue(1);
2966
2967   // Create the CALLSEQ_END node.
2968   unsigned NumBytesForCalleeToPop;
2969   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2970                        getTargetMachine().Options.GuaranteedTailCallOpt))
2971     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2972   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2973            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2974            SR == StackStructReturn)
2975     // If this is a call to a struct-return function, the callee
2976     // pops the hidden struct pointer, so we have to push it back.
2977     // This is common for Darwin/X86, Linux & Mingw32 targets.
2978     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2979     NumBytesForCalleeToPop = 4;
2980   else
2981     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2982
2983   // Returns a flag for retval copy to use.
2984   if (!IsSibcall) {
2985     Chain = DAG.getCALLSEQ_END(Chain,
2986                                DAG.getIntPtrConstant(NumBytesToPop, true),
2987                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2988                                                      true),
2989                                InFlag, dl);
2990     InFlag = Chain.getValue(1);
2991   }
2992
2993   // Handle result values, copying them out of physregs into vregs that we
2994   // return.
2995   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2996                          Ins, dl, DAG, InVals);
2997 }
2998
2999 //===----------------------------------------------------------------------===//
3000 //                Fast Calling Convention (tail call) implementation
3001 //===----------------------------------------------------------------------===//
3002
3003 //  Like std call, callee cleans arguments, convention except that ECX is
3004 //  reserved for storing the tail called function address. Only 2 registers are
3005 //  free for argument passing (inreg). Tail call optimization is performed
3006 //  provided:
3007 //                * tailcallopt is enabled
3008 //                * caller/callee are fastcc
3009 //  On X86_64 architecture with GOT-style position independent code only local
3010 //  (within module) calls are supported at the moment.
3011 //  To keep the stack aligned according to platform abi the function
3012 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3013 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3014 //  If a tail called function callee has more arguments than the caller the
3015 //  caller needs to make sure that there is room to move the RETADDR to. This is
3016 //  achieved by reserving an area the size of the argument delta right after the
3017 //  original REtADDR, but before the saved framepointer or the spilled registers
3018 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3019 //  stack layout:
3020 //    arg1
3021 //    arg2
3022 //    RETADDR
3023 //    [ new RETADDR
3024 //      move area ]
3025 //    (possible EBP)
3026 //    ESI
3027 //    EDI
3028 //    local1 ..
3029
3030 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3031 /// for a 16 byte align requirement.
3032 unsigned
3033 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3034                                                SelectionDAG& DAG) const {
3035   MachineFunction &MF = DAG.getMachineFunction();
3036   const TargetMachine &TM = MF.getTarget();
3037   const X86RegisterInfo *RegInfo =
3038     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3039   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3040   unsigned StackAlignment = TFI.getStackAlignment();
3041   uint64_t AlignMask = StackAlignment - 1;
3042   int64_t Offset = StackSize;
3043   unsigned SlotSize = RegInfo->getSlotSize();
3044   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3045     // Number smaller than 12 so just add the difference.
3046     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3047   } else {
3048     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3049     Offset = ((~AlignMask) & Offset) + StackAlignment +
3050       (StackAlignment-SlotSize);
3051   }
3052   return Offset;
3053 }
3054
3055 /// MatchingStackOffset - Return true if the given stack call argument is
3056 /// already available in the same position (relatively) of the caller's
3057 /// incoming argument stack.
3058 static
3059 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3060                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3061                          const X86InstrInfo *TII) {
3062   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3063   int FI = INT_MAX;
3064   if (Arg.getOpcode() == ISD::CopyFromReg) {
3065     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3066     if (!TargetRegisterInfo::isVirtualRegister(VR))
3067       return false;
3068     MachineInstr *Def = MRI->getVRegDef(VR);
3069     if (!Def)
3070       return false;
3071     if (!Flags.isByVal()) {
3072       if (!TII->isLoadFromStackSlot(Def, FI))
3073         return false;
3074     } else {
3075       unsigned Opcode = Def->getOpcode();
3076       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3077           Def->getOperand(1).isFI()) {
3078         FI = Def->getOperand(1).getIndex();
3079         Bytes = Flags.getByValSize();
3080       } else
3081         return false;
3082     }
3083   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3084     if (Flags.isByVal())
3085       // ByVal argument is passed in as a pointer but it's now being
3086       // dereferenced. e.g.
3087       // define @foo(%struct.X* %A) {
3088       //   tail call @bar(%struct.X* byval %A)
3089       // }
3090       return false;
3091     SDValue Ptr = Ld->getBasePtr();
3092     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3093     if (!FINode)
3094       return false;
3095     FI = FINode->getIndex();
3096   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3097     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3098     FI = FINode->getIndex();
3099     Bytes = Flags.getByValSize();
3100   } else
3101     return false;
3102
3103   assert(FI != INT_MAX);
3104   if (!MFI->isFixedObjectIndex(FI))
3105     return false;
3106   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3107 }
3108
3109 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3110 /// for tail call optimization. Targets which want to do tail call
3111 /// optimization should implement this function.
3112 bool
3113 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3114                                                      CallingConv::ID CalleeCC,
3115                                                      bool isVarArg,
3116                                                      bool isCalleeStructRet,
3117                                                      bool isCallerStructRet,
3118                                                      Type *RetTy,
3119                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3120                                     const SmallVectorImpl<SDValue> &OutVals,
3121                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3122                                                      SelectionDAG &DAG) const {
3123   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3124     return false;
3125
3126   // If -tailcallopt is specified, make fastcc functions tail-callable.
3127   const MachineFunction &MF = DAG.getMachineFunction();
3128   const Function *CallerF = MF.getFunction();
3129
3130   // If the function return type is x86_fp80 and the callee return type is not,
3131   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3132   // perform a tailcall optimization here.
3133   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3134     return false;
3135
3136   CallingConv::ID CallerCC = CallerF->getCallingConv();
3137   bool CCMatch = CallerCC == CalleeCC;
3138   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3139   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3140
3141   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3142     if (IsTailCallConvention(CalleeCC) && CCMatch)
3143       return true;
3144     return false;
3145   }
3146
3147   // Look for obvious safe cases to perform tail call optimization that do not
3148   // require ABI changes. This is what gcc calls sibcall.
3149
3150   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3151   // emit a special epilogue.
3152   const X86RegisterInfo *RegInfo =
3153     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3154   if (RegInfo->needsStackRealignment(MF))
3155     return false;
3156
3157   // Also avoid sibcall optimization if either caller or callee uses struct
3158   // return semantics.
3159   if (isCalleeStructRet || isCallerStructRet)
3160     return false;
3161
3162   // An stdcall/thiscall caller is expected to clean up its arguments; the
3163   // callee isn't going to do that.
3164   // FIXME: this is more restrictive than needed. We could produce a tailcall
3165   // when the stack adjustment matches. For example, with a thiscall that takes
3166   // only one argument.
3167   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3168                    CallerCC == CallingConv::X86_ThisCall))
3169     return false;
3170
3171   // Do not sibcall optimize vararg calls unless all arguments are passed via
3172   // registers.
3173   if (isVarArg && !Outs.empty()) {
3174
3175     // Optimizing for varargs on Win64 is unlikely to be safe without
3176     // additional testing.
3177     if (IsCalleeWin64 || IsCallerWin64)
3178       return false;
3179
3180     SmallVector<CCValAssign, 16> ArgLocs;
3181     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3182                    getTargetMachine(), ArgLocs, *DAG.getContext());
3183
3184     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3185     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3186       if (!ArgLocs[i].isRegLoc())
3187         return false;
3188   }
3189
3190   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3191   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3192   // this into a sibcall.
3193   bool Unused = false;
3194   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3195     if (!Ins[i].Used) {
3196       Unused = true;
3197       break;
3198     }
3199   }
3200   if (Unused) {
3201     SmallVector<CCValAssign, 16> RVLocs;
3202     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3203                    getTargetMachine(), RVLocs, *DAG.getContext());
3204     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3205     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3206       CCValAssign &VA = RVLocs[i];
3207       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3208         return false;
3209     }
3210   }
3211
3212   // If the calling conventions do not match, then we'd better make sure the
3213   // results are returned in the same way as what the caller expects.
3214   if (!CCMatch) {
3215     SmallVector<CCValAssign, 16> RVLocs1;
3216     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3217                     getTargetMachine(), RVLocs1, *DAG.getContext());
3218     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3219
3220     SmallVector<CCValAssign, 16> RVLocs2;
3221     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3222                     getTargetMachine(), RVLocs2, *DAG.getContext());
3223     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3224
3225     if (RVLocs1.size() != RVLocs2.size())
3226       return false;
3227     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3228       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3229         return false;
3230       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3231         return false;
3232       if (RVLocs1[i].isRegLoc()) {
3233         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3234           return false;
3235       } else {
3236         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3237           return false;
3238       }
3239     }
3240   }
3241
3242   // If the callee takes no arguments then go on to check the results of the
3243   // call.
3244   if (!Outs.empty()) {
3245     // Check if stack adjustment is needed. For now, do not do this if any
3246     // argument is passed on the stack.
3247     SmallVector<CCValAssign, 16> ArgLocs;
3248     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3249                    getTargetMachine(), ArgLocs, *DAG.getContext());
3250
3251     // Allocate shadow area for Win64
3252     if (IsCalleeWin64)
3253       CCInfo.AllocateStack(32, 8);
3254
3255     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256     if (CCInfo.getNextStackOffset()) {
3257       MachineFunction &MF = DAG.getMachineFunction();
3258       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3259         return false;
3260
3261       // Check if the arguments are already laid out in the right way as
3262       // the caller's fixed stack objects.
3263       MachineFrameInfo *MFI = MF.getFrameInfo();
3264       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3265       const X86InstrInfo *TII =
3266         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3267       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3268         CCValAssign &VA = ArgLocs[i];
3269         SDValue Arg = OutVals[i];
3270         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3271         if (VA.getLocInfo() == CCValAssign::Indirect)
3272           return false;
3273         if (!VA.isRegLoc()) {
3274           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3275                                    MFI, MRI, TII))
3276             return false;
3277         }
3278       }
3279     }
3280
3281     // If the tailcall address may be in a register, then make sure it's
3282     // possible to register allocate for it. In 32-bit, the call address can
3283     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3284     // callee-saved registers are restored. These happen to be the same
3285     // registers used to pass 'inreg' arguments so watch out for those.
3286     if (!Subtarget->is64Bit() &&
3287         ((!isa<GlobalAddressSDNode>(Callee) &&
3288           !isa<ExternalSymbolSDNode>(Callee)) ||
3289          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3290       unsigned NumInRegs = 0;
3291       // In PIC we need an extra register to formulate the address computation
3292       // for the callee.
3293       unsigned MaxInRegs =
3294           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3295
3296       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297         CCValAssign &VA = ArgLocs[i];
3298         if (!VA.isRegLoc())
3299           continue;
3300         unsigned Reg = VA.getLocReg();
3301         switch (Reg) {
3302         default: break;
3303         case X86::EAX: case X86::EDX: case X86::ECX:
3304           if (++NumInRegs == MaxInRegs)
3305             return false;
3306           break;
3307         }
3308       }
3309     }
3310   }
3311
3312   return true;
3313 }
3314
3315 FastISel *
3316 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3317                                   const TargetLibraryInfo *libInfo) const {
3318   return X86::createFastISel(funcInfo, libInfo);
3319 }
3320
3321 //===----------------------------------------------------------------------===//
3322 //                           Other Lowering Hooks
3323 //===----------------------------------------------------------------------===//
3324
3325 static bool MayFoldLoad(SDValue Op) {
3326   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3327 }
3328
3329 static bool MayFoldIntoStore(SDValue Op) {
3330   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3331 }
3332
3333 static bool isTargetShuffle(unsigned Opcode) {
3334   switch(Opcode) {
3335   default: return false;
3336   case X86ISD::PSHUFD:
3337   case X86ISD::PSHUFHW:
3338   case X86ISD::PSHUFLW:
3339   case X86ISD::SHUFP:
3340   case X86ISD::PALIGNR:
3341   case X86ISD::MOVLHPS:
3342   case X86ISD::MOVLHPD:
3343   case X86ISD::MOVHLPS:
3344   case X86ISD::MOVLPS:
3345   case X86ISD::MOVLPD:
3346   case X86ISD::MOVSHDUP:
3347   case X86ISD::MOVSLDUP:
3348   case X86ISD::MOVDDUP:
3349   case X86ISD::MOVSS:
3350   case X86ISD::MOVSD:
3351   case X86ISD::UNPCKL:
3352   case X86ISD::UNPCKH:
3353   case X86ISD::VPERMILP:
3354   case X86ISD::VPERM2X128:
3355   case X86ISD::VPERMI:
3356     return true;
3357   }
3358 }
3359
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361                                     SDValue V1, SelectionDAG &DAG) {
3362   switch(Opc) {
3363   default: llvm_unreachable("Unknown x86 shuffle node");
3364   case X86ISD::MOVSHDUP:
3365   case X86ISD::MOVSLDUP:
3366   case X86ISD::MOVDDUP:
3367     return DAG.getNode(Opc, dl, VT, V1);
3368   }
3369 }
3370
3371 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3372                                     SDValue V1, unsigned TargetMask,
3373                                     SelectionDAG &DAG) {
3374   switch(Opc) {
3375   default: llvm_unreachable("Unknown x86 shuffle node");
3376   case X86ISD::PSHUFD:
3377   case X86ISD::PSHUFHW:
3378   case X86ISD::PSHUFLW:
3379   case X86ISD::VPERMILP:
3380   case X86ISD::VPERMI:
3381     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3382   }
3383 }
3384
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386                                     SDValue V1, SDValue V2, unsigned TargetMask,
3387                                     SelectionDAG &DAG) {
3388   switch(Opc) {
3389   default: llvm_unreachable("Unknown x86 shuffle node");
3390   case X86ISD::PALIGNR:
3391   case X86ISD::SHUFP:
3392   case X86ISD::VPERM2X128:
3393     return DAG.getNode(Opc, dl, VT, V1, V2,
3394                        DAG.getConstant(TargetMask, MVT::i8));
3395   }
3396 }
3397
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3400   switch(Opc) {
3401   default: llvm_unreachable("Unknown x86 shuffle node");
3402   case X86ISD::MOVLHPS:
3403   case X86ISD::MOVLHPD:
3404   case X86ISD::MOVHLPS:
3405   case X86ISD::MOVLPS:
3406   case X86ISD::MOVLPD:
3407   case X86ISD::MOVSS:
3408   case X86ISD::MOVSD:
3409   case X86ISD::UNPCKL:
3410   case X86ISD::UNPCKH:
3411     return DAG.getNode(Opc, dl, VT, V1, V2);
3412   }
3413 }
3414
3415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3416   MachineFunction &MF = DAG.getMachineFunction();
3417   const X86RegisterInfo *RegInfo =
3418     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3420   int ReturnAddrIndex = FuncInfo->getRAIndex();
3421
3422   if (ReturnAddrIndex == 0) {
3423     // Set up a frame object for the return address.
3424     unsigned SlotSize = RegInfo->getSlotSize();
3425     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3426                                                            -(int64_t)SlotSize,
3427                                                            false);
3428     FuncInfo->setRAIndex(ReturnAddrIndex);
3429   }
3430
3431   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3432 }
3433
3434 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3435                                        bool hasSymbolicDisplacement) {
3436   // Offset should fit into 32 bit immediate field.
3437   if (!isInt<32>(Offset))
3438     return false;
3439
3440   // If we don't have a symbolic displacement - we don't have any extra
3441   // restrictions.
3442   if (!hasSymbolicDisplacement)
3443     return true;
3444
3445   // FIXME: Some tweaks might be needed for medium code model.
3446   if (M != CodeModel::Small && M != CodeModel::Kernel)
3447     return false;
3448
3449   // For small code model we assume that latest object is 16MB before end of 31
3450   // bits boundary. We may also accept pretty large negative constants knowing
3451   // that all objects are in the positive half of address space.
3452   if (M == CodeModel::Small && Offset < 16*1024*1024)
3453     return true;
3454
3455   // For kernel code model we know that all object resist in the negative half
3456   // of 32bits address space. We may not accept negative offsets, since they may
3457   // be just off and we may accept pretty large positive ones.
3458   if (M == CodeModel::Kernel && Offset > 0)
3459     return true;
3460
3461   return false;
3462 }
3463
3464 /// isCalleePop - Determines whether the callee is required to pop its
3465 /// own arguments. Callee pop is necessary to support tail calls.
3466 bool X86::isCalleePop(CallingConv::ID CallingConv,
3467                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3468   if (IsVarArg)
3469     return false;
3470
3471   switch (CallingConv) {
3472   default:
3473     return false;
3474   case CallingConv::X86_StdCall:
3475     return !is64Bit;
3476   case CallingConv::X86_FastCall:
3477     return !is64Bit;
3478   case CallingConv::X86_ThisCall:
3479     return !is64Bit;
3480   case CallingConv::Fast:
3481     return TailCallOpt;
3482   case CallingConv::GHC:
3483     return TailCallOpt;
3484   case CallingConv::HiPE:
3485     return TailCallOpt;
3486   }
3487 }
3488
3489 /// \brief Return true if the condition is an unsigned comparison operation.
3490 static bool isX86CCUnsigned(unsigned X86CC) {
3491   switch (X86CC) {
3492   default: llvm_unreachable("Invalid integer condition!");
3493   case X86::COND_E:     return true;
3494   case X86::COND_G:     return false;
3495   case X86::COND_GE:    return false;
3496   case X86::COND_L:     return false;
3497   case X86::COND_LE:    return false;
3498   case X86::COND_NE:    return true;
3499   case X86::COND_B:     return true;
3500   case X86::COND_A:     return true;
3501   case X86::COND_BE:    return true;
3502   case X86::COND_AE:    return true;
3503   }
3504   llvm_unreachable("covered switch fell through?!");
3505 }
3506
3507 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3508 /// specific condition code, returning the condition code and the LHS/RHS of the
3509 /// comparison to make.
3510 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3511                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3512   if (!isFP) {
3513     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3514       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3515         // X > -1   -> X == 0, jump !sign.
3516         RHS = DAG.getConstant(0, RHS.getValueType());
3517         return X86::COND_NS;
3518       }
3519       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3520         // X < 0   -> X == 0, jump on sign.
3521         return X86::COND_S;
3522       }
3523       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3524         // X < 1   -> X <= 0
3525         RHS = DAG.getConstant(0, RHS.getValueType());
3526         return X86::COND_LE;
3527       }
3528     }
3529
3530     switch (SetCCOpcode) {
3531     default: llvm_unreachable("Invalid integer condition!");
3532     case ISD::SETEQ:  return X86::COND_E;
3533     case ISD::SETGT:  return X86::COND_G;
3534     case ISD::SETGE:  return X86::COND_GE;
3535     case ISD::SETLT:  return X86::COND_L;
3536     case ISD::SETLE:  return X86::COND_LE;
3537     case ISD::SETNE:  return X86::COND_NE;
3538     case ISD::SETULT: return X86::COND_B;
3539     case ISD::SETUGT: return X86::COND_A;
3540     case ISD::SETULE: return X86::COND_BE;
3541     case ISD::SETUGE: return X86::COND_AE;
3542     }
3543   }
3544
3545   // First determine if it is required or is profitable to flip the operands.
3546
3547   // If LHS is a foldable load, but RHS is not, flip the condition.
3548   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3549       !ISD::isNON_EXTLoad(RHS.getNode())) {
3550     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3551     std::swap(LHS, RHS);
3552   }
3553
3554   switch (SetCCOpcode) {
3555   default: break;
3556   case ISD::SETOLT:
3557   case ISD::SETOLE:
3558   case ISD::SETUGT:
3559   case ISD::SETUGE:
3560     std::swap(LHS, RHS);
3561     break;
3562   }
3563
3564   // On a floating point condition, the flags are set as follows:
3565   // ZF  PF  CF   op
3566   //  0 | 0 | 0 | X > Y
3567   //  0 | 0 | 1 | X < Y
3568   //  1 | 0 | 0 | X == Y
3569   //  1 | 1 | 1 | unordered
3570   switch (SetCCOpcode) {
3571   default: llvm_unreachable("Condcode should be pre-legalized away");
3572   case ISD::SETUEQ:
3573   case ISD::SETEQ:   return X86::COND_E;
3574   case ISD::SETOLT:              // flipped
3575   case ISD::SETOGT:
3576   case ISD::SETGT:   return X86::COND_A;
3577   case ISD::SETOLE:              // flipped
3578   case ISD::SETOGE:
3579   case ISD::SETGE:   return X86::COND_AE;
3580   case ISD::SETUGT:              // flipped
3581   case ISD::SETULT:
3582   case ISD::SETLT:   return X86::COND_B;
3583   case ISD::SETUGE:              // flipped
3584   case ISD::SETULE:
3585   case ISD::SETLE:   return X86::COND_BE;
3586   case ISD::SETONE:
3587   case ISD::SETNE:   return X86::COND_NE;
3588   case ISD::SETUO:   return X86::COND_P;
3589   case ISD::SETO:    return X86::COND_NP;
3590   case ISD::SETOEQ:
3591   case ISD::SETUNE:  return X86::COND_INVALID;
3592   }
3593 }
3594
3595 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3596 /// code. Current x86 isa includes the following FP cmov instructions:
3597 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3598 static bool hasFPCMov(unsigned X86CC) {
3599   switch (X86CC) {
3600   default:
3601     return false;
3602   case X86::COND_B:
3603   case X86::COND_BE:
3604   case X86::COND_E:
3605   case X86::COND_P:
3606   case X86::COND_A:
3607   case X86::COND_AE:
3608   case X86::COND_NE:
3609   case X86::COND_NP:
3610     return true;
3611   }
3612 }
3613
3614 /// isFPImmLegal - Returns true if the target can instruction select the
3615 /// specified FP immediate natively. If false, the legalizer will
3616 /// materialize the FP immediate as a load from a constant pool.
3617 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3618   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3619     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3620       return true;
3621   }
3622   return false;
3623 }
3624
3625 /// \brief Returns true if it is beneficial to convert a load of a constant
3626 /// to just the constant itself.
3627 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3628                                                           Type *Ty) const {
3629   assert(Ty->isIntegerTy());
3630
3631   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3632   if (BitSize == 0 || BitSize > 64)
3633     return false;
3634   return true;
3635 }
3636
3637 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3638 /// the specified range (L, H].
3639 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3640   return (Val < 0) || (Val >= Low && Val < Hi);
3641 }
3642
3643 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3644 /// specified value.
3645 static bool isUndefOrEqual(int Val, int CmpVal) {
3646   return (Val < 0 || Val == CmpVal);
3647 }
3648
3649 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3650 /// from position Pos and ending in Pos+Size, falls within the specified
3651 /// sequential range (L, L+Pos]. or is undef.
3652 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3653                                        unsigned Pos, unsigned Size, int Low) {
3654   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3655     if (!isUndefOrEqual(Mask[i], Low))
3656       return false;
3657   return true;
3658 }
3659
3660 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3661 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3662 /// the second operand.
3663 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3664   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3665     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3666   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3667     return (Mask[0] < 2 && Mask[1] < 2);
3668   return false;
3669 }
3670
3671 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3672 /// is suitable for input to PSHUFHW.
3673 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3674   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3675     return false;
3676
3677   // Lower quadword copied in order or undef.
3678   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3679     return false;
3680
3681   // Upper quadword shuffled.
3682   for (unsigned i = 4; i != 8; ++i)
3683     if (!isUndefOrInRange(Mask[i], 4, 8))
3684       return false;
3685
3686   if (VT == MVT::v16i16) {
3687     // Lower quadword copied in order or undef.
3688     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3689       return false;
3690
3691     // Upper quadword shuffled.
3692     for (unsigned i = 12; i != 16; ++i)
3693       if (!isUndefOrInRange(Mask[i], 12, 16))
3694         return false;
3695   }
3696
3697   return true;
3698 }
3699
3700 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFLW.
3702 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3704     return false;
3705
3706   // Upper quadword copied in order.
3707   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3708     return false;
3709
3710   // Lower quadword shuffled.
3711   for (unsigned i = 0; i != 4; ++i)
3712     if (!isUndefOrInRange(Mask[i], 0, 4))
3713       return false;
3714
3715   if (VT == MVT::v16i16) {
3716     // Upper quadword copied in order.
3717     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3718       return false;
3719
3720     // Lower quadword shuffled.
3721     for (unsigned i = 8; i != 12; ++i)
3722       if (!isUndefOrInRange(Mask[i], 8, 12))
3723         return false;
3724   }
3725
3726   return true;
3727 }
3728
3729 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PALIGNR.
3731 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3732                           const X86Subtarget *Subtarget) {
3733   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3734       (VT.is256BitVector() && !Subtarget->hasInt256()))
3735     return false;
3736
3737   unsigned NumElts = VT.getVectorNumElements();
3738   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3739   unsigned NumLaneElts = NumElts/NumLanes;
3740
3741   // Do not handle 64-bit element shuffles with palignr.
3742   if (NumLaneElts == 2)
3743     return false;
3744
3745   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3746     unsigned i;
3747     for (i = 0; i != NumLaneElts; ++i) {
3748       if (Mask[i+l] >= 0)
3749         break;
3750     }
3751
3752     // Lane is all undef, go to next lane
3753     if (i == NumLaneElts)
3754       continue;
3755
3756     int Start = Mask[i+l];
3757
3758     // Make sure its in this lane in one of the sources
3759     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3760         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3761       return false;
3762
3763     // If not lane 0, then we must match lane 0
3764     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3765       return false;
3766
3767     // Correct second source to be contiguous with first source
3768     if (Start >= (int)NumElts)
3769       Start -= NumElts - NumLaneElts;
3770
3771     // Make sure we're shifting in the right direction.
3772     if (Start <= (int)(i+l))
3773       return false;
3774
3775     Start -= i;
3776
3777     // Check the rest of the elements to see if they are consecutive.
3778     for (++i; i != NumLaneElts; ++i) {
3779       int Idx = Mask[i+l];
3780
3781       // Make sure its in this lane
3782       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3783           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3784         return false;
3785
3786       // If not lane 0, then we must match lane 0
3787       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3788         return false;
3789
3790       if (Idx >= (int)NumElts)
3791         Idx -= NumElts - NumLaneElts;
3792
3793       if (!isUndefOrEqual(Idx, Start+i))
3794         return false;
3795
3796     }
3797   }
3798
3799   return true;
3800 }
3801
3802 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3803 /// the two vector operands have swapped position.
3804 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3805                                      unsigned NumElems) {
3806   for (unsigned i = 0; i != NumElems; ++i) {
3807     int idx = Mask[i];
3808     if (idx < 0)
3809       continue;
3810     else if (idx < (int)NumElems)
3811       Mask[i] = idx + NumElems;
3812     else
3813       Mask[i] = idx - NumElems;
3814   }
3815 }
3816
3817 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3819 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3820 /// reverse of what x86 shuffles want.
3821 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3822
3823   unsigned NumElems = VT.getVectorNumElements();
3824   unsigned NumLanes = VT.getSizeInBits()/128;
3825   unsigned NumLaneElems = NumElems/NumLanes;
3826
3827   if (NumLaneElems != 2 && NumLaneElems != 4)
3828     return false;
3829
3830   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3831   bool symetricMaskRequired =
3832     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3833
3834   // VSHUFPSY divides the resulting vector into 4 chunks.
3835   // The sources are also splitted into 4 chunks, and each destination
3836   // chunk must come from a different source chunk.
3837   //
3838   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3839   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3840   //
3841   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3842   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3843   //
3844   // VSHUFPDY divides the resulting vector into 4 chunks.
3845   // The sources are also splitted into 4 chunks, and each destination
3846   // chunk must come from a different source chunk.
3847   //
3848   //  SRC1 =>      X3       X2       X1       X0
3849   //  SRC2 =>      Y3       Y2       Y1       Y0
3850   //
3851   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3852   //
3853   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3854   unsigned HalfLaneElems = NumLaneElems/2;
3855   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3856     for (unsigned i = 0; i != NumLaneElems; ++i) {
3857       int Idx = Mask[i+l];
3858       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3859       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3860         return false;
3861       // For VSHUFPSY, the mask of the second half must be the same as the
3862       // first but with the appropriate offsets. This works in the same way as
3863       // VPERMILPS works with masks.
3864       if (!symetricMaskRequired || Idx < 0)
3865         continue;
3866       if (MaskVal[i] < 0) {
3867         MaskVal[i] = Idx - l;
3868         continue;
3869       }
3870       if ((signed)(Idx - l) != MaskVal[i])
3871         return false;
3872     }
3873   }
3874
3875   return true;
3876 }
3877
3878 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3880 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3881   if (!VT.is128BitVector())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if (NumElems != 4)
3887     return false;
3888
3889   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3890   return isUndefOrEqual(Mask[0], 6) &&
3891          isUndefOrEqual(Mask[1], 7) &&
3892          isUndefOrEqual(Mask[2], 2) &&
3893          isUndefOrEqual(Mask[3], 3);
3894 }
3895
3896 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3897 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3898 /// <2, 3, 2, 3>
3899 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3900   if (!VT.is128BitVector())
3901     return false;
3902
3903   unsigned NumElems = VT.getVectorNumElements();
3904
3905   if (NumElems != 4)
3906     return false;
3907
3908   return isUndefOrEqual(Mask[0], 2) &&
3909          isUndefOrEqual(Mask[1], 3) &&
3910          isUndefOrEqual(Mask[2], 2) &&
3911          isUndefOrEqual(Mask[3], 3);
3912 }
3913
3914 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3915 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3916 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3917   if (!VT.is128BitVector())
3918     return false;
3919
3920   unsigned NumElems = VT.getVectorNumElements();
3921
3922   if (NumElems != 2 && NumElems != 4)
3923     return false;
3924
3925   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926     if (!isUndefOrEqual(Mask[i], i + NumElems))
3927       return false;
3928
3929   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3930     if (!isUndefOrEqual(Mask[i], i))
3931       return false;
3932
3933   return true;
3934 }
3935
3936 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3938 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3939   if (!VT.is128BitVector())
3940     return false;
3941
3942   unsigned NumElems = VT.getVectorNumElements();
3943
3944   if (NumElems != 2 && NumElems != 4)
3945     return false;
3946
3947   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3948     if (!isUndefOrEqual(Mask[i], i))
3949       return false;
3950
3951   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3952     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3953       return false;
3954
3955   return true;
3956 }
3957
3958 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3959 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3960 /// i. e: If all but one element come from the same vector.
3961 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3962   // TODO: Deal with AVX's VINSERTPS
3963   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3964     return false;
3965
3966   unsigned CorrectPosV1 = 0;
3967   unsigned CorrectPosV2 = 0;
3968   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3969     if (Mask[i] == i)
3970       ++CorrectPosV1;
3971     else if (Mask[i] == i + 4)
3972       ++CorrectPosV2;
3973
3974   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3975     // We have 3 elements from one vector, and one from another.
3976     return true;
3977
3978   return false;
3979 }
3980
3981 //
3982 // Some special combinations that can be optimized.
3983 //
3984 static
3985 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3986                                SelectionDAG &DAG) {
3987   MVT VT = SVOp->getSimpleValueType(0);
3988   SDLoc dl(SVOp);
3989
3990   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3991     return SDValue();
3992
3993   ArrayRef<int> Mask = SVOp->getMask();
3994
3995   // These are the special masks that may be optimized.
3996   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3997   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3998   bool MatchEvenMask = true;
3999   bool MatchOddMask  = true;
4000   for (int i=0; i<8; ++i) {
4001     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4002       MatchEvenMask = false;
4003     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4004       MatchOddMask = false;
4005   }
4006
4007   if (!MatchEvenMask && !MatchOddMask)
4008     return SDValue();
4009
4010   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4011
4012   SDValue Op0 = SVOp->getOperand(0);
4013   SDValue Op1 = SVOp->getOperand(1);
4014
4015   if (MatchEvenMask) {
4016     // Shift the second operand right to 32 bits.
4017     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4018     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4019   } else {
4020     // Shift the first operand left to 32 bits.
4021     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4022     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4023   }
4024   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4025   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4026 }
4027
4028 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4030 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4031                          bool HasInt256, bool V2IsSplat = false) {
4032
4033   assert(VT.getSizeInBits() >= 128 &&
4034          "Unsupported vector type for unpckl");
4035
4036   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4037   unsigned NumLanes;
4038   unsigned NumOf256BitLanes;
4039   unsigned NumElts = VT.getVectorNumElements();
4040   if (VT.is256BitVector()) {
4041     if (NumElts != 4 && NumElts != 8 &&
4042         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4043     return false;
4044     NumLanes = 2;
4045     NumOf256BitLanes = 1;
4046   } else if (VT.is512BitVector()) {
4047     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4048            "Unsupported vector type for unpckh");
4049     NumLanes = 2;
4050     NumOf256BitLanes = 2;
4051   } else {
4052     NumLanes = 1;
4053     NumOf256BitLanes = 1;
4054   }
4055
4056   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4057   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4058
4059   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4060     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4061       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4062         int BitI  = Mask[l256*NumEltsInStride+l+i];
4063         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4064         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4065           return false;
4066         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4067           return false;
4068         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4069           return false;
4070       }
4071     }
4072   }
4073   return true;
4074 }
4075
4076 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4077 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4078 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4079                          bool HasInt256, bool V2IsSplat = false) {
4080   assert(VT.getSizeInBits() >= 128 &&
4081          "Unsupported vector type for unpckh");
4082
4083   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4084   unsigned NumLanes;
4085   unsigned NumOf256BitLanes;
4086   unsigned NumElts = VT.getVectorNumElements();
4087   if (VT.is256BitVector()) {
4088     if (NumElts != 4 && NumElts != 8 &&
4089         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4090     return false;
4091     NumLanes = 2;
4092     NumOf256BitLanes = 1;
4093   } else if (VT.is512BitVector()) {
4094     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4095            "Unsupported vector type for unpckh");
4096     NumLanes = 2;
4097     NumOf256BitLanes = 2;
4098   } else {
4099     NumLanes = 1;
4100     NumOf256BitLanes = 1;
4101   }
4102
4103   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4104   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4105
4106   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4107     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4108       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4109         int BitI  = Mask[l256*NumEltsInStride+l+i];
4110         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4111         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4112           return false;
4113         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4114           return false;
4115         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4116           return false;
4117       }
4118     }
4119   }
4120   return true;
4121 }
4122
4123 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4124 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4125 /// <0, 0, 1, 1>
4126 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4127   unsigned NumElts = VT.getVectorNumElements();
4128   bool Is256BitVec = VT.is256BitVector();
4129
4130   if (VT.is512BitVector())
4131     return false;
4132   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4133          "Unsupported vector type for unpckh");
4134
4135   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4136       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4137     return false;
4138
4139   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4140   // FIXME: Need a better way to get rid of this, there's no latency difference
4141   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4142   // the former later. We should also remove the "_undef" special mask.
4143   if (NumElts == 4 && Is256BitVec)
4144     return false;
4145
4146   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4147   // independently on 128-bit lanes.
4148   unsigned NumLanes = VT.getSizeInBits()/128;
4149   unsigned NumLaneElts = NumElts/NumLanes;
4150
4151   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4152     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4153       int BitI  = Mask[l+i];
4154       int BitI1 = Mask[l+i+1];
4155
4156       if (!isUndefOrEqual(BitI, j))
4157         return false;
4158       if (!isUndefOrEqual(BitI1, j))
4159         return false;
4160     }
4161   }
4162
4163   return true;
4164 }
4165
4166 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4167 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4168 /// <2, 2, 3, 3>
4169 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4170   unsigned NumElts = VT.getVectorNumElements();
4171
4172   if (VT.is512BitVector())
4173     return false;
4174
4175   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4176          "Unsupported vector type for unpckh");
4177
4178   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4179       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4180     return false;
4181
4182   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4183   // independently on 128-bit lanes.
4184   unsigned NumLanes = VT.getSizeInBits()/128;
4185   unsigned NumLaneElts = NumElts/NumLanes;
4186
4187   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4188     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4189       int BitI  = Mask[l+i];
4190       int BitI1 = Mask[l+i+1];
4191       if (!isUndefOrEqual(BitI, j))
4192         return false;
4193       if (!isUndefOrEqual(BitI1, j))
4194         return false;
4195     }
4196   }
4197   return true;
4198 }
4199
4200 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4201 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4202 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4203   if (!VT.is512BitVector())
4204     return false;
4205
4206   unsigned NumElts = VT.getVectorNumElements();
4207   unsigned HalfSize = NumElts/2;
4208   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4209     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4210       *Imm = 1;
4211       return true;
4212     }
4213   }
4214   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4215     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4216       *Imm = 0;
4217       return true;
4218     }
4219   }
4220   return false;
4221 }
4222
4223 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4224 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4225 /// MOVSD, and MOVD, i.e. setting the lowest element.
4226 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4227   if (VT.getVectorElementType().getSizeInBits() < 32)
4228     return false;
4229   if (!VT.is128BitVector())
4230     return false;
4231
4232   unsigned NumElts = VT.getVectorNumElements();
4233
4234   if (!isUndefOrEqual(Mask[0], NumElts))
4235     return false;
4236
4237   for (unsigned i = 1; i != NumElts; ++i)
4238     if (!isUndefOrEqual(Mask[i], i))
4239       return false;
4240
4241   return true;
4242 }
4243
4244 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4245 /// as permutations between 128-bit chunks or halves. As an example: this
4246 /// shuffle bellow:
4247 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4248 /// The first half comes from the second half of V1 and the second half from the
4249 /// the second half of V2.
4250 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4251   if (!HasFp256 || !VT.is256BitVector())
4252     return false;
4253
4254   // The shuffle result is divided into half A and half B. In total the two
4255   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4256   // B must come from C, D, E or F.
4257   unsigned HalfSize = VT.getVectorNumElements()/2;
4258   bool MatchA = false, MatchB = false;
4259
4260   // Check if A comes from one of C, D, E, F.
4261   for (unsigned Half = 0; Half != 4; ++Half) {
4262     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4263       MatchA = true;
4264       break;
4265     }
4266   }
4267
4268   // Check if B comes from one of C, D, E, F.
4269   for (unsigned Half = 0; Half != 4; ++Half) {
4270     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4271       MatchB = true;
4272       break;
4273     }
4274   }
4275
4276   return MatchA && MatchB;
4277 }
4278
4279 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4280 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4281 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4282   MVT VT = SVOp->getSimpleValueType(0);
4283
4284   unsigned HalfSize = VT.getVectorNumElements()/2;
4285
4286   unsigned FstHalf = 0, SndHalf = 0;
4287   for (unsigned i = 0; i < HalfSize; ++i) {
4288     if (SVOp->getMaskElt(i) > 0) {
4289       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4290       break;
4291     }
4292   }
4293   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4294     if (SVOp->getMaskElt(i) > 0) {
4295       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4296       break;
4297     }
4298   }
4299
4300   return (FstHalf | (SndHalf << 4));
4301 }
4302
4303 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4304 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4305   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4306   if (EltSize < 32)
4307     return false;
4308
4309   unsigned NumElts = VT.getVectorNumElements();
4310   Imm8 = 0;
4311   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4312     for (unsigned i = 0; i != NumElts; ++i) {
4313       if (Mask[i] < 0)
4314         continue;
4315       Imm8 |= Mask[i] << (i*2);
4316     }
4317     return true;
4318   }
4319
4320   unsigned LaneSize = 4;
4321   SmallVector<int, 4> MaskVal(LaneSize, -1);
4322
4323   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4324     for (unsigned i = 0; i != LaneSize; ++i) {
4325       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4326         return false;
4327       if (Mask[i+l] < 0)
4328         continue;
4329       if (MaskVal[i] < 0) {
4330         MaskVal[i] = Mask[i+l] - l;
4331         Imm8 |= MaskVal[i] << (i*2);
4332         continue;
4333       }
4334       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4335         return false;
4336     }
4337   }
4338   return true;
4339 }
4340
4341 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4342 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4343 /// Note that VPERMIL mask matching is different depending whether theunderlying
4344 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4345 /// to the same elements of the low, but to the higher half of the source.
4346 /// In VPERMILPD the two lanes could be shuffled independently of each other
4347 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4348 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4349   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4350   if (VT.getSizeInBits() < 256 || EltSize < 32)
4351     return false;
4352   bool symetricMaskRequired = (EltSize == 32);
4353   unsigned NumElts = VT.getVectorNumElements();
4354
4355   unsigned NumLanes = VT.getSizeInBits()/128;
4356   unsigned LaneSize = NumElts/NumLanes;
4357   // 2 or 4 elements in one lane
4358
4359   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4360   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4361     for (unsigned i = 0; i != LaneSize; ++i) {
4362       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4363         return false;
4364       if (symetricMaskRequired) {
4365         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4366           ExpectedMaskVal[i] = Mask[i+l] - l;
4367           continue;
4368         }
4369         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4370           return false;
4371       }
4372     }
4373   }
4374   return true;
4375 }
4376
4377 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4378 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4379 /// element of vector 2 and the other elements to come from vector 1 in order.
4380 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4381                                bool V2IsSplat = false, bool V2IsUndef = false) {
4382   if (!VT.is128BitVector())
4383     return false;
4384
4385   unsigned NumOps = VT.getVectorNumElements();
4386   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4387     return false;
4388
4389   if (!isUndefOrEqual(Mask[0], 0))
4390     return false;
4391
4392   for (unsigned i = 1; i != NumOps; ++i)
4393     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4394           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4395           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4396       return false;
4397
4398   return true;
4399 }
4400
4401 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4402 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4403 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4404 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4405                            const X86Subtarget *Subtarget) {
4406   if (!Subtarget->hasSSE3())
4407     return false;
4408
4409   unsigned NumElems = VT.getVectorNumElements();
4410
4411   if ((VT.is128BitVector() && NumElems != 4) ||
4412       (VT.is256BitVector() && NumElems != 8) ||
4413       (VT.is512BitVector() && NumElems != 16))
4414     return false;
4415
4416   // "i+1" is the value the indexed mask element must have
4417   for (unsigned i = 0; i != NumElems; i += 2)
4418     if (!isUndefOrEqual(Mask[i], i+1) ||
4419         !isUndefOrEqual(Mask[i+1], i+1))
4420       return false;
4421
4422   return true;
4423 }
4424
4425 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4427 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4428 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4429                            const X86Subtarget *Subtarget) {
4430   if (!Subtarget->hasSSE3())
4431     return false;
4432
4433   unsigned NumElems = VT.getVectorNumElements();
4434
4435   if ((VT.is128BitVector() && NumElems != 4) ||
4436       (VT.is256BitVector() && NumElems != 8) ||
4437       (VT.is512BitVector() && NumElems != 16))
4438     return false;
4439
4440   // "i" is the value the indexed mask element must have
4441   for (unsigned i = 0; i != NumElems; i += 2)
4442     if (!isUndefOrEqual(Mask[i], i) ||
4443         !isUndefOrEqual(Mask[i+1], i))
4444       return false;
4445
4446   return true;
4447 }
4448
4449 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to 256-bit
4451 /// version of MOVDDUP.
4452 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4453   if (!HasFp256 || !VT.is256BitVector())
4454     return false;
4455
4456   unsigned NumElts = VT.getVectorNumElements();
4457   if (NumElts != 4)
4458     return false;
4459
4460   for (unsigned i = 0; i != NumElts/2; ++i)
4461     if (!isUndefOrEqual(Mask[i], 0))
4462       return false;
4463   for (unsigned i = NumElts/2; i != NumElts; ++i)
4464     if (!isUndefOrEqual(Mask[i], NumElts/2))
4465       return false;
4466   return true;
4467 }
4468
4469 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4470 /// specifies a shuffle of elements that is suitable for input to 128-bit
4471 /// version of MOVDDUP.
4472 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4473   if (!VT.is128BitVector())
4474     return false;
4475
4476   unsigned e = VT.getVectorNumElements() / 2;
4477   for (unsigned i = 0; i != e; ++i)
4478     if (!isUndefOrEqual(Mask[i], i))
4479       return false;
4480   for (unsigned i = 0; i != e; ++i)
4481     if (!isUndefOrEqual(Mask[e+i], i))
4482       return false;
4483   return true;
4484 }
4485
4486 /// isVEXTRACTIndex - Return true if the specified
4487 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4488 /// suitable for instruction that extract 128 or 256 bit vectors
4489 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4490   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4491   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4492     return false;
4493
4494   // The index should be aligned on a vecWidth-bit boundary.
4495   uint64_t Index =
4496     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4497
4498   MVT VT = N->getSimpleValueType(0);
4499   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4500   bool Result = (Index * ElSize) % vecWidth == 0;
4501
4502   return Result;
4503 }
4504
4505 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4506 /// operand specifies a subvector insert that is suitable for input to
4507 /// insertion of 128 or 256-bit subvectors
4508 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4509   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4510   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4511     return false;
4512   // The index should be aligned on a vecWidth-bit boundary.
4513   uint64_t Index =
4514     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4515
4516   MVT VT = N->getSimpleValueType(0);
4517   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4518   bool Result = (Index * ElSize) % vecWidth == 0;
4519
4520   return Result;
4521 }
4522
4523 bool X86::isVINSERT128Index(SDNode *N) {
4524   return isVINSERTIndex(N, 128);
4525 }
4526
4527 bool X86::isVINSERT256Index(SDNode *N) {
4528   return isVINSERTIndex(N, 256);
4529 }
4530
4531 bool X86::isVEXTRACT128Index(SDNode *N) {
4532   return isVEXTRACTIndex(N, 128);
4533 }
4534
4535 bool X86::isVEXTRACT256Index(SDNode *N) {
4536   return isVEXTRACTIndex(N, 256);
4537 }
4538
4539 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4540 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4541 /// Handles 128-bit and 256-bit.
4542 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4543   MVT VT = N->getSimpleValueType(0);
4544
4545   assert((VT.getSizeInBits() >= 128) &&
4546          "Unsupported vector type for PSHUF/SHUFP");
4547
4548   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4549   // independently on 128-bit lanes.
4550   unsigned NumElts = VT.getVectorNumElements();
4551   unsigned NumLanes = VT.getSizeInBits()/128;
4552   unsigned NumLaneElts = NumElts/NumLanes;
4553
4554   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4555          "Only supports 2, 4 or 8 elements per lane");
4556
4557   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4558   unsigned Mask = 0;
4559   for (unsigned i = 0; i != NumElts; ++i) {
4560     int Elt = N->getMaskElt(i);
4561     if (Elt < 0) continue;
4562     Elt &= NumLaneElts - 1;
4563     unsigned ShAmt = (i << Shift) % 8;
4564     Mask |= Elt << ShAmt;
4565   }
4566
4567   return Mask;
4568 }
4569
4570 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4571 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4572 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4573   MVT VT = N->getSimpleValueType(0);
4574
4575   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4576          "Unsupported vector type for PSHUFHW");
4577
4578   unsigned NumElts = VT.getVectorNumElements();
4579
4580   unsigned Mask = 0;
4581   for (unsigned l = 0; l != NumElts; l += 8) {
4582     // 8 nodes per lane, but we only care about the last 4.
4583     for (unsigned i = 0; i < 4; ++i) {
4584       int Elt = N->getMaskElt(l+i+4);
4585       if (Elt < 0) continue;
4586       Elt &= 0x3; // only 2-bits.
4587       Mask |= Elt << (i * 2);
4588     }
4589   }
4590
4591   return Mask;
4592 }
4593
4594 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4595 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4596 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4597   MVT VT = N->getSimpleValueType(0);
4598
4599   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4600          "Unsupported vector type for PSHUFHW");
4601
4602   unsigned NumElts = VT.getVectorNumElements();
4603
4604   unsigned Mask = 0;
4605   for (unsigned l = 0; l != NumElts; l += 8) {
4606     // 8 nodes per lane, but we only care about the first 4.
4607     for (unsigned i = 0; i < 4; ++i) {
4608       int Elt = N->getMaskElt(l+i);
4609       if (Elt < 0) continue;
4610       Elt &= 0x3; // only 2-bits
4611       Mask |= Elt << (i * 2);
4612     }
4613   }
4614
4615   return Mask;
4616 }
4617
4618 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4619 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4620 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4621   MVT VT = SVOp->getSimpleValueType(0);
4622   unsigned EltSize = VT.is512BitVector() ? 1 :
4623     VT.getVectorElementType().getSizeInBits() >> 3;
4624
4625   unsigned NumElts = VT.getVectorNumElements();
4626   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4627   unsigned NumLaneElts = NumElts/NumLanes;
4628
4629   int Val = 0;
4630   unsigned i;
4631   for (i = 0; i != NumElts; ++i) {
4632     Val = SVOp->getMaskElt(i);
4633     if (Val >= 0)
4634       break;
4635   }
4636   if (Val >= (int)NumElts)
4637     Val -= NumElts - NumLaneElts;
4638
4639   assert(Val - i > 0 && "PALIGNR imm should be positive");
4640   return (Val - i) * EltSize;
4641 }
4642
4643 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4644   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4645   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4646     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4647
4648   uint64_t Index =
4649     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4650
4651   MVT VecVT = N->getOperand(0).getSimpleValueType();
4652   MVT ElVT = VecVT.getVectorElementType();
4653
4654   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4655   return Index / NumElemsPerChunk;
4656 }
4657
4658 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4659   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4660   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4661     llvm_unreachable("Illegal insert subvector for VINSERT");
4662
4663   uint64_t Index =
4664     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4665
4666   MVT VecVT = N->getSimpleValueType(0);
4667   MVT ElVT = VecVT.getVectorElementType();
4668
4669   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4670   return Index / NumElemsPerChunk;
4671 }
4672
4673 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4675 /// and VINSERTI128 instructions.
4676 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4677   return getExtractVEXTRACTImmediate(N, 128);
4678 }
4679
4680 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4681 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4682 /// and VINSERTI64x4 instructions.
4683 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4684   return getExtractVEXTRACTImmediate(N, 256);
4685 }
4686
4687 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4688 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4689 /// and VINSERTI128 instructions.
4690 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4691   return getInsertVINSERTImmediate(N, 128);
4692 }
4693
4694 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4695 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4696 /// and VINSERTI64x4 instructions.
4697 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4698   return getInsertVINSERTImmediate(N, 256);
4699 }
4700
4701 /// isZero - Returns true if Elt is a constant integer zero
4702 static bool isZero(SDValue V) {
4703   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4704   return C && C->isNullValue();
4705 }
4706
4707 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4708 /// constant +0.0.
4709 bool X86::isZeroNode(SDValue Elt) {
4710   if (isZero(Elt))
4711     return true;
4712   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4713     return CFP->getValueAPF().isPosZero();
4714   return false;
4715 }
4716
4717 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4718 /// their permute mask.
4719 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4720                                     SelectionDAG &DAG) {
4721   MVT VT = SVOp->getSimpleValueType(0);
4722   unsigned NumElems = VT.getVectorNumElements();
4723   SmallVector<int, 8> MaskVec;
4724
4725   for (unsigned i = 0; i != NumElems; ++i) {
4726     int Idx = SVOp->getMaskElt(i);
4727     if (Idx >= 0) {
4728       if (Idx < (int)NumElems)
4729         Idx += NumElems;
4730       else
4731         Idx -= NumElems;
4732     }
4733     MaskVec.push_back(Idx);
4734   }
4735   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4736                               SVOp->getOperand(0), &MaskVec[0]);
4737 }
4738
4739 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4740 /// match movhlps. The lower half elements should come from upper half of
4741 /// V1 (and in order), and the upper half elements should come from the upper
4742 /// half of V2 (and in order).
4743 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4744   if (!VT.is128BitVector())
4745     return false;
4746   if (VT.getVectorNumElements() != 4)
4747     return false;
4748   for (unsigned i = 0, e = 2; i != e; ++i)
4749     if (!isUndefOrEqual(Mask[i], i+2))
4750       return false;
4751   for (unsigned i = 2; i != 4; ++i)
4752     if (!isUndefOrEqual(Mask[i], i+4))
4753       return false;
4754   return true;
4755 }
4756
4757 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4758 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4759 /// required.
4760 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4761   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4762     return false;
4763   N = N->getOperand(0).getNode();
4764   if (!ISD::isNON_EXTLoad(N))
4765     return false;
4766   if (LD)
4767     *LD = cast<LoadSDNode>(N);
4768   return true;
4769 }
4770
4771 // Test whether the given value is a vector value which will be legalized
4772 // into a load.
4773 static bool WillBeConstantPoolLoad(SDNode *N) {
4774   if (N->getOpcode() != ISD::BUILD_VECTOR)
4775     return false;
4776
4777   // Check for any non-constant elements.
4778   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4779     switch (N->getOperand(i).getNode()->getOpcode()) {
4780     case ISD::UNDEF:
4781     case ISD::ConstantFP:
4782     case ISD::Constant:
4783       break;
4784     default:
4785       return false;
4786     }
4787
4788   // Vectors of all-zeros and all-ones are materialized with special
4789   // instructions rather than being loaded.
4790   return !ISD::isBuildVectorAllZeros(N) &&
4791          !ISD::isBuildVectorAllOnes(N);
4792 }
4793
4794 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4795 /// match movlp{s|d}. The lower half elements should come from lower half of
4796 /// V1 (and in order), and the upper half elements should come from the upper
4797 /// half of V2 (and in order). And since V1 will become the source of the
4798 /// MOVLP, it must be either a vector load or a scalar load to vector.
4799 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4800                                ArrayRef<int> Mask, MVT VT) {
4801   if (!VT.is128BitVector())
4802     return false;
4803
4804   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4805     return false;
4806   // Is V2 is a vector load, don't do this transformation. We will try to use
4807   // load folding shufps op.
4808   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4809     return false;
4810
4811   unsigned NumElems = VT.getVectorNumElements();
4812
4813   if (NumElems != 2 && NumElems != 4)
4814     return false;
4815   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4816     if (!isUndefOrEqual(Mask[i], i))
4817       return false;
4818   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4819     if (!isUndefOrEqual(Mask[i], i+NumElems))
4820       return false;
4821   return true;
4822 }
4823
4824 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4825 /// all the same.
4826 static bool isSplatVector(SDNode *N) {
4827   if (N->getOpcode() != ISD::BUILD_VECTOR)
4828     return false;
4829
4830   SDValue SplatValue = N->getOperand(0);
4831   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4832     if (N->getOperand(i) != SplatValue)
4833       return false;
4834   return true;
4835 }
4836
4837 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4838 /// to an zero vector.
4839 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4840 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4841   SDValue V1 = N->getOperand(0);
4842   SDValue V2 = N->getOperand(1);
4843   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4844   for (unsigned i = 0; i != NumElems; ++i) {
4845     int Idx = N->getMaskElt(i);
4846     if (Idx >= (int)NumElems) {
4847       unsigned Opc = V2.getOpcode();
4848       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4849         continue;
4850       if (Opc != ISD::BUILD_VECTOR ||
4851           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4852         return false;
4853     } else if (Idx >= 0) {
4854       unsigned Opc = V1.getOpcode();
4855       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4856         continue;
4857       if (Opc != ISD::BUILD_VECTOR ||
4858           !X86::isZeroNode(V1.getOperand(Idx)))
4859         return false;
4860     }
4861   }
4862   return true;
4863 }
4864
4865 /// getZeroVector - Returns a vector of specified type with all zero elements.
4866 ///
4867 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4868                              SelectionDAG &DAG, SDLoc dl) {
4869   assert(VT.isVector() && "Expected a vector type");
4870
4871   // Always build SSE zero vectors as <4 x i32> bitcasted
4872   // to their dest type. This ensures they get CSE'd.
4873   SDValue Vec;
4874   if (VT.is128BitVector()) {  // SSE
4875     if (Subtarget->hasSSE2()) {  // SSE2
4876       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4877       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4878     } else { // SSE1
4879       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4880       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4881     }
4882   } else if (VT.is256BitVector()) { // AVX
4883     if (Subtarget->hasInt256()) { // AVX2
4884       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4885       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4886       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4887     } else {
4888       // 256-bit logic and arithmetic instructions in AVX are all
4889       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4890       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4891       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4892       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4893     }
4894   } else if (VT.is512BitVector()) { // AVX-512
4895       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4896       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4897                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4898       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4899   } else if (VT.getScalarType() == MVT::i1) {
4900     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4901     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4902     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4903     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4904   } else
4905     llvm_unreachable("Unexpected vector type");
4906
4907   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4908 }
4909
4910 /// getOnesVector - Returns a vector of specified type with all bits set.
4911 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4912 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4913 /// Then bitcast to their original type, ensuring they get CSE'd.
4914 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4915                              SDLoc dl) {
4916   assert(VT.isVector() && "Expected a vector type");
4917
4918   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4919   SDValue Vec;
4920   if (VT.is256BitVector()) {
4921     if (HasInt256) { // AVX2
4922       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4923       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4924     } else { // AVX
4925       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4926       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4927     }
4928   } else if (VT.is128BitVector()) {
4929     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4930   } else
4931     llvm_unreachable("Unexpected vector type");
4932
4933   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4934 }
4935
4936 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4937 /// that point to V2 points to its first element.
4938 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4939   for (unsigned i = 0; i != NumElems; ++i) {
4940     if (Mask[i] > (int)NumElems) {
4941       Mask[i] = NumElems;
4942     }
4943   }
4944 }
4945
4946 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4947 /// operation of specified width.
4948 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4949                        SDValue V2) {
4950   unsigned NumElems = VT.getVectorNumElements();
4951   SmallVector<int, 8> Mask;
4952   Mask.push_back(NumElems);
4953   for (unsigned i = 1; i != NumElems; ++i)
4954     Mask.push_back(i);
4955   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4956 }
4957
4958 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4959 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4960                           SDValue V2) {
4961   unsigned NumElems = VT.getVectorNumElements();
4962   SmallVector<int, 8> Mask;
4963   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4964     Mask.push_back(i);
4965     Mask.push_back(i + NumElems);
4966   }
4967   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4968 }
4969
4970 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4971 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4972                           SDValue V2) {
4973   unsigned NumElems = VT.getVectorNumElements();
4974   SmallVector<int, 8> Mask;
4975   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4976     Mask.push_back(i + Half);
4977     Mask.push_back(i + NumElems + Half);
4978   }
4979   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4980 }
4981
4982 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4983 // a generic shuffle instruction because the target has no such instructions.
4984 // Generate shuffles which repeat i16 and i8 several times until they can be
4985 // represented by v4f32 and then be manipulated by target suported shuffles.
4986 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4987   MVT VT = V.getSimpleValueType();
4988   int NumElems = VT.getVectorNumElements();
4989   SDLoc dl(V);
4990
4991   while (NumElems > 4) {
4992     if (EltNo < NumElems/2) {
4993       V = getUnpackl(DAG, dl, VT, V, V);
4994     } else {
4995       V = getUnpackh(DAG, dl, VT, V, V);
4996       EltNo -= NumElems/2;
4997     }
4998     NumElems >>= 1;
4999   }
5000   return V;
5001 }
5002
5003 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5004 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5005   MVT VT = V.getSimpleValueType();
5006   SDLoc dl(V);
5007
5008   if (VT.is128BitVector()) {
5009     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5010     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5011     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5012                              &SplatMask[0]);
5013   } else if (VT.is256BitVector()) {
5014     // To use VPERMILPS to splat scalars, the second half of indicies must
5015     // refer to the higher part, which is a duplication of the lower one,
5016     // because VPERMILPS can only handle in-lane permutations.
5017     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5018                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5019
5020     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5021     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5022                              &SplatMask[0]);
5023   } else
5024     llvm_unreachable("Vector size not supported");
5025
5026   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5027 }
5028
5029 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5030 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5031   MVT SrcVT = SV->getSimpleValueType(0);
5032   SDValue V1 = SV->getOperand(0);
5033   SDLoc dl(SV);
5034
5035   int EltNo = SV->getSplatIndex();
5036   int NumElems = SrcVT.getVectorNumElements();
5037   bool Is256BitVec = SrcVT.is256BitVector();
5038
5039   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5040          "Unknown how to promote splat for type");
5041
5042   // Extract the 128-bit part containing the splat element and update
5043   // the splat element index when it refers to the higher register.
5044   if (Is256BitVec) {
5045     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5046     if (EltNo >= NumElems/2)
5047       EltNo -= NumElems/2;
5048   }
5049
5050   // All i16 and i8 vector types can't be used directly by a generic shuffle
5051   // instruction because the target has no such instruction. Generate shuffles
5052   // which repeat i16 and i8 several times until they fit in i32, and then can
5053   // be manipulated by target suported shuffles.
5054   MVT EltVT = SrcVT.getVectorElementType();
5055   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5056     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5057
5058   // Recreate the 256-bit vector and place the same 128-bit vector
5059   // into the low and high part. This is necessary because we want
5060   // to use VPERM* to shuffle the vectors
5061   if (Is256BitVec) {
5062     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5063   }
5064
5065   return getLegalSplat(DAG, V1, EltNo);
5066 }
5067
5068 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5069 /// vector of zero or undef vector.  This produces a shuffle where the low
5070 /// element of V2 is swizzled into the zero/undef vector, landing at element
5071 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5072 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5073                                            bool IsZero,
5074                                            const X86Subtarget *Subtarget,
5075                                            SelectionDAG &DAG) {
5076   MVT VT = V2.getSimpleValueType();
5077   SDValue V1 = IsZero
5078     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5079   unsigned NumElems = VT.getVectorNumElements();
5080   SmallVector<int, 16> MaskVec;
5081   for (unsigned i = 0; i != NumElems; ++i)
5082     // If this is the insertion idx, put the low elt of V2 here.
5083     MaskVec.push_back(i == Idx ? NumElems : i);
5084   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5085 }
5086
5087 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5088 /// target specific opcode. Returns true if the Mask could be calculated.
5089 /// Sets IsUnary to true if only uses one source.
5090 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5091                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5092   unsigned NumElems = VT.getVectorNumElements();
5093   SDValue ImmN;
5094
5095   IsUnary = false;
5096   switch(N->getOpcode()) {
5097   case X86ISD::SHUFP:
5098     ImmN = N->getOperand(N->getNumOperands()-1);
5099     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5100     break;
5101   case X86ISD::UNPCKH:
5102     DecodeUNPCKHMask(VT, Mask);
5103     break;
5104   case X86ISD::UNPCKL:
5105     DecodeUNPCKLMask(VT, Mask);
5106     break;
5107   case X86ISD::MOVHLPS:
5108     DecodeMOVHLPSMask(NumElems, Mask);
5109     break;
5110   case X86ISD::MOVLHPS:
5111     DecodeMOVLHPSMask(NumElems, Mask);
5112     break;
5113   case X86ISD::PALIGNR:
5114     ImmN = N->getOperand(N->getNumOperands()-1);
5115     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5116     break;
5117   case X86ISD::PSHUFD:
5118   case X86ISD::VPERMILP:
5119     ImmN = N->getOperand(N->getNumOperands()-1);
5120     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5121     IsUnary = true;
5122     break;
5123   case X86ISD::PSHUFHW:
5124     ImmN = N->getOperand(N->getNumOperands()-1);
5125     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5126     IsUnary = true;
5127     break;
5128   case X86ISD::PSHUFLW:
5129     ImmN = N->getOperand(N->getNumOperands()-1);
5130     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5131     IsUnary = true;
5132     break;
5133   case X86ISD::VPERMI:
5134     ImmN = N->getOperand(N->getNumOperands()-1);
5135     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5136     IsUnary = true;
5137     break;
5138   case X86ISD::MOVSS:
5139   case X86ISD::MOVSD: {
5140     // The index 0 always comes from the first element of the second source,
5141     // this is why MOVSS and MOVSD are used in the first place. The other
5142     // elements come from the other positions of the first source vector
5143     Mask.push_back(NumElems);
5144     for (unsigned i = 1; i != NumElems; ++i) {
5145       Mask.push_back(i);
5146     }
5147     break;
5148   }
5149   case X86ISD::VPERM2X128:
5150     ImmN = N->getOperand(N->getNumOperands()-1);
5151     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152     if (Mask.empty()) return false;
5153     break;
5154   case X86ISD::MOVDDUP:
5155   case X86ISD::MOVLHPD:
5156   case X86ISD::MOVLPD:
5157   case X86ISD::MOVLPS:
5158   case X86ISD::MOVSHDUP:
5159   case X86ISD::MOVSLDUP:
5160     // Not yet implemented
5161     return false;
5162   default: llvm_unreachable("unknown target shuffle node");
5163   }
5164
5165   return true;
5166 }
5167
5168 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5169 /// element of the result of the vector shuffle.
5170 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5171                                    unsigned Depth) {
5172   if (Depth == 6)
5173     return SDValue();  // Limit search depth.
5174
5175   SDValue V = SDValue(N, 0);
5176   EVT VT = V.getValueType();
5177   unsigned Opcode = V.getOpcode();
5178
5179   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5180   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5181     int Elt = SV->getMaskElt(Index);
5182
5183     if (Elt < 0)
5184       return DAG.getUNDEF(VT.getVectorElementType());
5185
5186     unsigned NumElems = VT.getVectorNumElements();
5187     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5188                                          : SV->getOperand(1);
5189     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5190   }
5191
5192   // Recurse into target specific vector shuffles to find scalars.
5193   if (isTargetShuffle(Opcode)) {
5194     MVT ShufVT = V.getSimpleValueType();
5195     unsigned NumElems = ShufVT.getVectorNumElements();
5196     SmallVector<int, 16> ShuffleMask;
5197     bool IsUnary;
5198
5199     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5200       return SDValue();
5201
5202     int Elt = ShuffleMask[Index];
5203     if (Elt < 0)
5204       return DAG.getUNDEF(ShufVT.getVectorElementType());
5205
5206     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5207                                          : N->getOperand(1);
5208     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5209                                Depth+1);
5210   }
5211
5212   // Actual nodes that may contain scalar elements
5213   if (Opcode == ISD::BITCAST) {
5214     V = V.getOperand(0);
5215     EVT SrcVT = V.getValueType();
5216     unsigned NumElems = VT.getVectorNumElements();
5217
5218     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5219       return SDValue();
5220   }
5221
5222   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5223     return (Index == 0) ? V.getOperand(0)
5224                         : DAG.getUNDEF(VT.getVectorElementType());
5225
5226   if (V.getOpcode() == ISD::BUILD_VECTOR)
5227     return V.getOperand(Index);
5228
5229   return SDValue();
5230 }
5231
5232 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5233 /// shuffle operation which come from a consecutively from a zero. The
5234 /// search can start in two different directions, from left or right.
5235 /// We count undefs as zeros until PreferredNum is reached.
5236 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5237                                          unsigned NumElems, bool ZerosFromLeft,
5238                                          SelectionDAG &DAG,
5239                                          unsigned PreferredNum = -1U) {
5240   unsigned NumZeros = 0;
5241   for (unsigned i = 0; i != NumElems; ++i) {
5242     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5243     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5244     if (!Elt.getNode())
5245       break;
5246
5247     if (X86::isZeroNode(Elt))
5248       ++NumZeros;
5249     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5250       NumZeros = std::min(NumZeros + 1, PreferredNum);
5251     else
5252       break;
5253   }
5254
5255   return NumZeros;
5256 }
5257
5258 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5259 /// correspond consecutively to elements from one of the vector operands,
5260 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5261 static
5262 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5263                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5264                               unsigned NumElems, unsigned &OpNum) {
5265   bool SeenV1 = false;
5266   bool SeenV2 = false;
5267
5268   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5269     int Idx = SVOp->getMaskElt(i);
5270     // Ignore undef indicies
5271     if (Idx < 0)
5272       continue;
5273
5274     if (Idx < (int)NumElems)
5275       SeenV1 = true;
5276     else
5277       SeenV2 = true;
5278
5279     // Only accept consecutive elements from the same vector
5280     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5281       return false;
5282   }
5283
5284   OpNum = SeenV1 ? 0 : 1;
5285   return true;
5286 }
5287
5288 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5289 /// logical left shift of a vector.
5290 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5291                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5292   unsigned NumElems =
5293     SVOp->getSimpleValueType(0).getVectorNumElements();
5294   unsigned NumZeros = getNumOfConsecutiveZeros(
5295       SVOp, NumElems, false /* check zeros from right */, DAG,
5296       SVOp->getMaskElt(0));
5297   unsigned OpSrc;
5298
5299   if (!NumZeros)
5300     return false;
5301
5302   // Considering the elements in the mask that are not consecutive zeros,
5303   // check if they consecutively come from only one of the source vectors.
5304   //
5305   //               V1 = {X, A, B, C}     0
5306   //                         \  \  \    /
5307   //   vector_shuffle V1, V2 <1, 2, 3, X>
5308   //
5309   if (!isShuffleMaskConsecutive(SVOp,
5310             0,                   // Mask Start Index
5311             NumElems-NumZeros,   // Mask End Index(exclusive)
5312             NumZeros,            // Where to start looking in the src vector
5313             NumElems,            // Number of elements in vector
5314             OpSrc))              // Which source operand ?
5315     return false;
5316
5317   isLeft = false;
5318   ShAmt = NumZeros;
5319   ShVal = SVOp->getOperand(OpSrc);
5320   return true;
5321 }
5322
5323 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5324 /// logical left shift of a vector.
5325 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5326                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5327   unsigned NumElems =
5328     SVOp->getSimpleValueType(0).getVectorNumElements();
5329   unsigned NumZeros = getNumOfConsecutiveZeros(
5330       SVOp, NumElems, true /* check zeros from left */, DAG,
5331       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5332   unsigned OpSrc;
5333
5334   if (!NumZeros)
5335     return false;
5336
5337   // Considering the elements in the mask that are not consecutive zeros,
5338   // check if they consecutively come from only one of the source vectors.
5339   //
5340   //                           0    { A, B, X, X } = V2
5341   //                          / \    /  /
5342   //   vector_shuffle V1, V2 <X, X, 4, 5>
5343   //
5344   if (!isShuffleMaskConsecutive(SVOp,
5345             NumZeros,     // Mask Start Index
5346             NumElems,     // Mask End Index(exclusive)
5347             0,            // Where to start looking in the src vector
5348             NumElems,     // Number of elements in vector
5349             OpSrc))       // Which source operand ?
5350     return false;
5351
5352   isLeft = true;
5353   ShAmt = NumZeros;
5354   ShVal = SVOp->getOperand(OpSrc);
5355   return true;
5356 }
5357
5358 /// isVectorShift - Returns true if the shuffle can be implemented as a
5359 /// logical left or right shift of a vector.
5360 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5361                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5362   // Although the logic below support any bitwidth size, there are no
5363   // shift instructions which handle more than 128-bit vectors.
5364   if (!SVOp->getSimpleValueType(0).is128BitVector())
5365     return false;
5366
5367   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5368       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5369     return true;
5370
5371   return false;
5372 }
5373
5374 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5375 ///
5376 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5377                                        unsigned NumNonZero, unsigned NumZero,
5378                                        SelectionDAG &DAG,
5379                                        const X86Subtarget* Subtarget,
5380                                        const TargetLowering &TLI) {
5381   if (NumNonZero > 8)
5382     return SDValue();
5383
5384   SDLoc dl(Op);
5385   SDValue V;
5386   bool First = true;
5387   for (unsigned i = 0; i < 16; ++i) {
5388     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5389     if (ThisIsNonZero && First) {
5390       if (NumZero)
5391         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5392       else
5393         V = DAG.getUNDEF(MVT::v8i16);
5394       First = false;
5395     }
5396
5397     if ((i & 1) != 0) {
5398       SDValue ThisElt, LastElt;
5399       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5400       if (LastIsNonZero) {
5401         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5402                               MVT::i16, Op.getOperand(i-1));
5403       }
5404       if (ThisIsNonZero) {
5405         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5406         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5407                               ThisElt, DAG.getConstant(8, MVT::i8));
5408         if (LastIsNonZero)
5409           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5410       } else
5411         ThisElt = LastElt;
5412
5413       if (ThisElt.getNode())
5414         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5415                         DAG.getIntPtrConstant(i/2));
5416     }
5417   }
5418
5419   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5420 }
5421
5422 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5423 ///
5424 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5425                                      unsigned NumNonZero, unsigned NumZero,
5426                                      SelectionDAG &DAG,
5427                                      const X86Subtarget* Subtarget,
5428                                      const TargetLowering &TLI) {
5429   if (NumNonZero > 4)
5430     return SDValue();
5431
5432   SDLoc dl(Op);
5433   SDValue V;
5434   bool First = true;
5435   for (unsigned i = 0; i < 8; ++i) {
5436     bool isNonZero = (NonZeros & (1 << i)) != 0;
5437     if (isNonZero) {
5438       if (First) {
5439         if (NumZero)
5440           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5441         else
5442           V = DAG.getUNDEF(MVT::v8i16);
5443         First = false;
5444       }
5445       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5446                       MVT::v8i16, V, Op.getOperand(i),
5447                       DAG.getIntPtrConstant(i));
5448     }
5449   }
5450
5451   return V;
5452 }
5453
5454 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5455 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5456                                      unsigned NonZeros, unsigned NumNonZero,
5457                                      unsigned NumZero, SelectionDAG &DAG,
5458                                      const X86Subtarget *Subtarget,
5459                                      const TargetLowering &TLI) {
5460   // We know there's at least one non-zero element
5461   unsigned FirstNonZeroIdx = 0;
5462   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5463   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5464          X86::isZeroNode(FirstNonZero)) {
5465     ++FirstNonZeroIdx;
5466     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5467   }
5468
5469   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5470       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5471     return SDValue();
5472
5473   SDValue V = FirstNonZero.getOperand(0);
5474   MVT VVT = V.getSimpleValueType();
5475   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5476     return SDValue();
5477
5478   unsigned FirstNonZeroDst =
5479       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5480   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5481   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5482   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5483
5484   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5485     SDValue Elem = Op.getOperand(Idx);
5486     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5487       continue;
5488
5489     // TODO: What else can be here? Deal with it.
5490     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5491       return SDValue();
5492
5493     // TODO: Some optimizations are still possible here
5494     // ex: Getting one element from a vector, and the rest from another.
5495     if (Elem.getOperand(0) != V)
5496       return SDValue();
5497
5498     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5499     if (Dst == Idx)
5500       ++CorrectIdx;
5501     else if (IncorrectIdx == -1U) {
5502       IncorrectIdx = Idx;
5503       IncorrectDst = Dst;
5504     } else
5505       // There was already one element with an incorrect index.
5506       // We can't optimize this case to an insertps.
5507       return SDValue();
5508   }
5509
5510   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5511     SDLoc dl(Op);
5512     EVT VT = Op.getSimpleValueType();
5513     unsigned ElementMoveMask = 0;
5514     if (IncorrectIdx == -1U)
5515       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5516     else
5517       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5518
5519     SDValue InsertpsMask =
5520         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5521     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5522   }
5523
5524   return SDValue();
5525 }
5526
5527 /// getVShift - Return a vector logical shift node.
5528 ///
5529 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5530                          unsigned NumBits, SelectionDAG &DAG,
5531                          const TargetLowering &TLI, SDLoc dl) {
5532   assert(VT.is128BitVector() && "Unknown type for VShift");
5533   EVT ShVT = MVT::v2i64;
5534   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5535   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5536   return DAG.getNode(ISD::BITCAST, dl, VT,
5537                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5538                              DAG.getConstant(NumBits,
5539                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5540 }
5541
5542 static SDValue
5543 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5544
5545   // Check if the scalar load can be widened into a vector load. And if
5546   // the address is "base + cst" see if the cst can be "absorbed" into
5547   // the shuffle mask.
5548   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5549     SDValue Ptr = LD->getBasePtr();
5550     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5551       return SDValue();
5552     EVT PVT = LD->getValueType(0);
5553     if (PVT != MVT::i32 && PVT != MVT::f32)
5554       return SDValue();
5555
5556     int FI = -1;
5557     int64_t Offset = 0;
5558     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5559       FI = FINode->getIndex();
5560       Offset = 0;
5561     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5562                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5563       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5564       Offset = Ptr.getConstantOperandVal(1);
5565       Ptr = Ptr.getOperand(0);
5566     } else {
5567       return SDValue();
5568     }
5569
5570     // FIXME: 256-bit vector instructions don't require a strict alignment,
5571     // improve this code to support it better.
5572     unsigned RequiredAlign = VT.getSizeInBits()/8;
5573     SDValue Chain = LD->getChain();
5574     // Make sure the stack object alignment is at least 16 or 32.
5575     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5576     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5577       if (MFI->isFixedObjectIndex(FI)) {
5578         // Can't change the alignment. FIXME: It's possible to compute
5579         // the exact stack offset and reference FI + adjust offset instead.
5580         // If someone *really* cares about this. That's the way to implement it.
5581         return SDValue();
5582       } else {
5583         MFI->setObjectAlignment(FI, RequiredAlign);
5584       }
5585     }
5586
5587     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5588     // Ptr + (Offset & ~15).
5589     if (Offset < 0)
5590       return SDValue();
5591     if ((Offset % RequiredAlign) & 3)
5592       return SDValue();
5593     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5594     if (StartOffset)
5595       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5596                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5597
5598     int EltNo = (Offset - StartOffset) >> 2;
5599     unsigned NumElems = VT.getVectorNumElements();
5600
5601     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5602     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5603                              LD->getPointerInfo().getWithOffset(StartOffset),
5604                              false, false, false, 0);
5605
5606     SmallVector<int, 8> Mask;
5607     for (unsigned i = 0; i != NumElems; ++i)
5608       Mask.push_back(EltNo);
5609
5610     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5611   }
5612
5613   return SDValue();
5614 }
5615
5616 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5617 /// vector of type 'VT', see if the elements can be replaced by a single large
5618 /// load which has the same value as a build_vector whose operands are 'elts'.
5619 ///
5620 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5621 ///
5622 /// FIXME: we'd also like to handle the case where the last elements are zero
5623 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5624 /// There's even a handy isZeroNode for that purpose.
5625 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5626                                         SDLoc &DL, SelectionDAG &DAG,
5627                                         bool isAfterLegalize) {
5628   EVT EltVT = VT.getVectorElementType();
5629   unsigned NumElems = Elts.size();
5630
5631   LoadSDNode *LDBase = nullptr;
5632   unsigned LastLoadedElt = -1U;
5633
5634   // For each element in the initializer, see if we've found a load or an undef.
5635   // If we don't find an initial load element, or later load elements are
5636   // non-consecutive, bail out.
5637   for (unsigned i = 0; i < NumElems; ++i) {
5638     SDValue Elt = Elts[i];
5639
5640     if (!Elt.getNode() ||
5641         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5642       return SDValue();
5643     if (!LDBase) {
5644       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5645         return SDValue();
5646       LDBase = cast<LoadSDNode>(Elt.getNode());
5647       LastLoadedElt = i;
5648       continue;
5649     }
5650     if (Elt.getOpcode() == ISD::UNDEF)
5651       continue;
5652
5653     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5654     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5655       return SDValue();
5656     LastLoadedElt = i;
5657   }
5658
5659   // If we have found an entire vector of loads and undefs, then return a large
5660   // load of the entire vector width starting at the base pointer.  If we found
5661   // consecutive loads for the low half, generate a vzext_load node.
5662   if (LastLoadedElt == NumElems - 1) {
5663
5664     if (isAfterLegalize &&
5665         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5666       return SDValue();
5667
5668     SDValue NewLd = SDValue();
5669
5670     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5671       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5672                           LDBase->getPointerInfo(),
5673                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5674                           LDBase->isInvariant(), 0);
5675     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5676                         LDBase->getPointerInfo(),
5677                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5678                         LDBase->isInvariant(), LDBase->getAlignment());
5679
5680     if (LDBase->hasAnyUseOfValue(1)) {
5681       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5682                                      SDValue(LDBase, 1),
5683                                      SDValue(NewLd.getNode(), 1));
5684       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5685       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5686                              SDValue(NewLd.getNode(), 1));
5687     }
5688
5689     return NewLd;
5690   }
5691   if (NumElems == 4 && LastLoadedElt == 1 &&
5692       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5693     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5694     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5695     SDValue ResNode =
5696         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5697                                 LDBase->getPointerInfo(),
5698                                 LDBase->getAlignment(),
5699                                 false/*isVolatile*/, true/*ReadMem*/,
5700                                 false/*WriteMem*/);
5701
5702     // Make sure the newly-created LOAD is in the same position as LDBase in
5703     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5704     // update uses of LDBase's output chain to use the TokenFactor.
5705     if (LDBase->hasAnyUseOfValue(1)) {
5706       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5707                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5708       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5709       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5710                              SDValue(ResNode.getNode(), 1));
5711     }
5712
5713     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5714   }
5715   return SDValue();
5716 }
5717
5718 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5719 /// to generate a splat value for the following cases:
5720 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5721 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5722 /// a scalar load, or a constant.
5723 /// The VBROADCAST node is returned when a pattern is found,
5724 /// or SDValue() otherwise.
5725 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5726                                     SelectionDAG &DAG) {
5727   if (!Subtarget->hasFp256())
5728     return SDValue();
5729
5730   MVT VT = Op.getSimpleValueType();
5731   SDLoc dl(Op);
5732
5733   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5734          "Unsupported vector type for broadcast.");
5735
5736   SDValue Ld;
5737   bool ConstSplatVal;
5738
5739   switch (Op.getOpcode()) {
5740     default:
5741       // Unknown pattern found.
5742       return SDValue();
5743
5744     case ISD::BUILD_VECTOR: {
5745       // The BUILD_VECTOR node must be a splat.
5746       if (!isSplatVector(Op.getNode()))
5747         return SDValue();
5748
5749       Ld = Op.getOperand(0);
5750       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5751                      Ld.getOpcode() == ISD::ConstantFP);
5752
5753       // The suspected load node has several users. Make sure that all
5754       // of its users are from the BUILD_VECTOR node.
5755       // Constants may have multiple users.
5756       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5757         return SDValue();
5758       break;
5759     }
5760
5761     case ISD::VECTOR_SHUFFLE: {
5762       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5763
5764       // Shuffles must have a splat mask where the first element is
5765       // broadcasted.
5766       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5767         return SDValue();
5768
5769       SDValue Sc = Op.getOperand(0);
5770       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5771           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5772
5773         if (!Subtarget->hasInt256())
5774           return SDValue();
5775
5776         // Use the register form of the broadcast instruction available on AVX2.
5777         if (VT.getSizeInBits() >= 256)
5778           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5779         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5780       }
5781
5782       Ld = Sc.getOperand(0);
5783       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5784                        Ld.getOpcode() == ISD::ConstantFP);
5785
5786       // The scalar_to_vector node and the suspected
5787       // load node must have exactly one user.
5788       // Constants may have multiple users.
5789
5790       // AVX-512 has register version of the broadcast
5791       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5792         Ld.getValueType().getSizeInBits() >= 32;
5793       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5794           !hasRegVer))
5795         return SDValue();
5796       break;
5797     }
5798   }
5799
5800   bool IsGE256 = (VT.getSizeInBits() >= 256);
5801
5802   // Handle the broadcasting a single constant scalar from the constant pool
5803   // into a vector. On Sandybridge it is still better to load a constant vector
5804   // from the constant pool and not to broadcast it from a scalar.
5805   if (ConstSplatVal && Subtarget->hasInt256()) {
5806     EVT CVT = Ld.getValueType();
5807     assert(!CVT.isVector() && "Must not broadcast a vector type");
5808     unsigned ScalarSize = CVT.getSizeInBits();
5809
5810     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5811       const Constant *C = nullptr;
5812       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5813         C = CI->getConstantIntValue();
5814       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5815         C = CF->getConstantFPValue();
5816
5817       assert(C && "Invalid constant type");
5818
5819       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5820       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5821       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5822       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5823                        MachinePointerInfo::getConstantPool(),
5824                        false, false, false, Alignment);
5825
5826       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5827     }
5828   }
5829
5830   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5831   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5832
5833   // Handle AVX2 in-register broadcasts.
5834   if (!IsLoad && Subtarget->hasInt256() &&
5835       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5836     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5837
5838   // The scalar source must be a normal load.
5839   if (!IsLoad)
5840     return SDValue();
5841
5842   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5843     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5844
5845   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5846   // double since there is no vbroadcastsd xmm
5847   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5848     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5849       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5850   }
5851
5852   // Unsupported broadcast.
5853   return SDValue();
5854 }
5855
5856 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5857 /// underlying vector and index.
5858 ///
5859 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5860 /// index.
5861 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5862                                          SDValue ExtIdx) {
5863   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5864   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5865     return Idx;
5866
5867   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5868   // lowered this:
5869   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5870   // to:
5871   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5872   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5873   //                           undef)
5874   //                       Constant<0>)
5875   // In this case the vector is the extract_subvector expression and the index
5876   // is 2, as specified by the shuffle.
5877   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5878   SDValue ShuffleVec = SVOp->getOperand(0);
5879   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5880   assert(ShuffleVecVT.getVectorElementType() ==
5881          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5882
5883   int ShuffleIdx = SVOp->getMaskElt(Idx);
5884   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5885     ExtractedFromVec = ShuffleVec;
5886     return ShuffleIdx;
5887   }
5888   return Idx;
5889 }
5890
5891 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5892   MVT VT = Op.getSimpleValueType();
5893
5894   // Skip if insert_vec_elt is not supported.
5895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5896   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5897     return SDValue();
5898
5899   SDLoc DL(Op);
5900   unsigned NumElems = Op.getNumOperands();
5901
5902   SDValue VecIn1;
5903   SDValue VecIn2;
5904   SmallVector<unsigned, 4> InsertIndices;
5905   SmallVector<int, 8> Mask(NumElems, -1);
5906
5907   for (unsigned i = 0; i != NumElems; ++i) {
5908     unsigned Opc = Op.getOperand(i).getOpcode();
5909
5910     if (Opc == ISD::UNDEF)
5911       continue;
5912
5913     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5914       // Quit if more than 1 elements need inserting.
5915       if (InsertIndices.size() > 1)
5916         return SDValue();
5917
5918       InsertIndices.push_back(i);
5919       continue;
5920     }
5921
5922     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5923     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5924     // Quit if non-constant index.
5925     if (!isa<ConstantSDNode>(ExtIdx))
5926       return SDValue();
5927     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5928
5929     // Quit if extracted from vector of different type.
5930     if (ExtractedFromVec.getValueType() != VT)
5931       return SDValue();
5932
5933     if (!VecIn1.getNode())
5934       VecIn1 = ExtractedFromVec;
5935     else if (VecIn1 != ExtractedFromVec) {
5936       if (!VecIn2.getNode())
5937         VecIn2 = ExtractedFromVec;
5938       else if (VecIn2 != ExtractedFromVec)
5939         // Quit if more than 2 vectors to shuffle
5940         return SDValue();
5941     }
5942
5943     if (ExtractedFromVec == VecIn1)
5944       Mask[i] = Idx;
5945     else if (ExtractedFromVec == VecIn2)
5946       Mask[i] = Idx + NumElems;
5947   }
5948
5949   if (!VecIn1.getNode())
5950     return SDValue();
5951
5952   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5953   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5954   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5955     unsigned Idx = InsertIndices[i];
5956     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5957                      DAG.getIntPtrConstant(Idx));
5958   }
5959
5960   return NV;
5961 }
5962
5963 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5964 SDValue
5965 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5966
5967   MVT VT = Op.getSimpleValueType();
5968   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5969          "Unexpected type in LowerBUILD_VECTORvXi1!");
5970
5971   SDLoc dl(Op);
5972   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5973     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5974     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5975     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5976   }
5977
5978   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5979     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5980     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5981     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5982   }
5983
5984   bool AllContants = true;
5985   uint64_t Immediate = 0;
5986   int NonConstIdx = -1;
5987   bool IsSplat = true;
5988   unsigned NumNonConsts = 0;
5989   unsigned NumConsts = 0;
5990   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5991     SDValue In = Op.getOperand(idx);
5992     if (In.getOpcode() == ISD::UNDEF)
5993       continue;
5994     if (!isa<ConstantSDNode>(In)) {
5995       AllContants = false;
5996       NonConstIdx = idx;
5997       NumNonConsts++;
5998     }
5999     else {
6000       NumConsts++;
6001       if (cast<ConstantSDNode>(In)->getZExtValue())
6002       Immediate |= (1ULL << idx);
6003     }
6004     if (In != Op.getOperand(0))
6005       IsSplat = false;
6006   }
6007
6008   if (AllContants) {
6009     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6010       DAG.getConstant(Immediate, MVT::i16));
6011     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6012                        DAG.getIntPtrConstant(0));
6013   }
6014
6015   if (NumNonConsts == 1 && NonConstIdx != 0) {
6016     SDValue DstVec;
6017     if (NumConsts) {
6018       SDValue VecAsImm = DAG.getConstant(Immediate,
6019                                          MVT::getIntegerVT(VT.getSizeInBits()));
6020       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6021     }
6022     else 
6023       DstVec = DAG.getUNDEF(VT);
6024     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6025                        Op.getOperand(NonConstIdx),
6026                        DAG.getIntPtrConstant(NonConstIdx));
6027   }
6028   if (!IsSplat && (NonConstIdx != 0))
6029     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6030   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6031   SDValue Select;
6032   if (IsSplat)
6033     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6034                           DAG.getConstant(-1, SelectVT),
6035                           DAG.getConstant(0, SelectVT));
6036   else
6037     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6038                          DAG.getConstant((Immediate | 1), SelectVT),
6039                          DAG.getConstant(Immediate, SelectVT));
6040   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6041 }
6042
6043 SDValue
6044 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6045   SDLoc dl(Op);
6046
6047   MVT VT = Op.getSimpleValueType();
6048   MVT ExtVT = VT.getVectorElementType();
6049   unsigned NumElems = Op.getNumOperands();
6050
6051   // Generate vectors for predicate vectors.
6052   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6053     return LowerBUILD_VECTORvXi1(Op, DAG);
6054
6055   // Vectors containing all zeros can be matched by pxor and xorps later
6056   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6057     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6058     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6059     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6060       return Op;
6061
6062     return getZeroVector(VT, Subtarget, DAG, dl);
6063   }
6064
6065   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6066   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6067   // vpcmpeqd on 256-bit vectors.
6068   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6069     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6070       return Op;
6071
6072     if (!VT.is512BitVector())
6073       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6074   }
6075
6076   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6077   if (Broadcast.getNode())
6078     return Broadcast;
6079
6080   unsigned EVTBits = ExtVT.getSizeInBits();
6081
6082   unsigned NumZero  = 0;
6083   unsigned NumNonZero = 0;
6084   unsigned NonZeros = 0;
6085   bool IsAllConstants = true;
6086   SmallSet<SDValue, 8> Values;
6087   for (unsigned i = 0; i < NumElems; ++i) {
6088     SDValue Elt = Op.getOperand(i);
6089     if (Elt.getOpcode() == ISD::UNDEF)
6090       continue;
6091     Values.insert(Elt);
6092     if (Elt.getOpcode() != ISD::Constant &&
6093         Elt.getOpcode() != ISD::ConstantFP)
6094       IsAllConstants = false;
6095     if (X86::isZeroNode(Elt))
6096       NumZero++;
6097     else {
6098       NonZeros |= (1 << i);
6099       NumNonZero++;
6100     }
6101   }
6102
6103   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6104   if (NumNonZero == 0)
6105     return DAG.getUNDEF(VT);
6106
6107   // Special case for single non-zero, non-undef, element.
6108   if (NumNonZero == 1) {
6109     unsigned Idx = countTrailingZeros(NonZeros);
6110     SDValue Item = Op.getOperand(Idx);
6111
6112     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6113     // the value are obviously zero, truncate the value to i32 and do the
6114     // insertion that way.  Only do this if the value is non-constant or if the
6115     // value is a constant being inserted into element 0.  It is cheaper to do
6116     // a constant pool load than it is to do a movd + shuffle.
6117     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6118         (!IsAllConstants || Idx == 0)) {
6119       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6120         // Handle SSE only.
6121         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6122         EVT VecVT = MVT::v4i32;
6123         unsigned VecElts = 4;
6124
6125         // Truncate the value (which may itself be a constant) to i32, and
6126         // convert it to a vector with movd (S2V+shuffle to zero extend).
6127         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6128         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6129         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6130
6131         // Now we have our 32-bit value zero extended in the low element of
6132         // a vector.  If Idx != 0, swizzle it into place.
6133         if (Idx != 0) {
6134           SmallVector<int, 4> Mask;
6135           Mask.push_back(Idx);
6136           for (unsigned i = 1; i != VecElts; ++i)
6137             Mask.push_back(i);
6138           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6139                                       &Mask[0]);
6140         }
6141         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6142       }
6143     }
6144
6145     // If we have a constant or non-constant insertion into the low element of
6146     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6147     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6148     // depending on what the source datatype is.
6149     if (Idx == 0) {
6150       if (NumZero == 0)
6151         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6152
6153       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6154           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6155         if (VT.is256BitVector() || VT.is512BitVector()) {
6156           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6157           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6158                              Item, DAG.getIntPtrConstant(0));
6159         }
6160         assert(VT.is128BitVector() && "Expected an SSE value type!");
6161         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6162         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6163         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6164       }
6165
6166       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6167         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6168         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6169         if (VT.is256BitVector()) {
6170           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6171           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6172         } else {
6173           assert(VT.is128BitVector() && "Expected an SSE value type!");
6174           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6175         }
6176         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6177       }
6178     }
6179
6180     // Is it a vector logical left shift?
6181     if (NumElems == 2 && Idx == 1 &&
6182         X86::isZeroNode(Op.getOperand(0)) &&
6183         !X86::isZeroNode(Op.getOperand(1))) {
6184       unsigned NumBits = VT.getSizeInBits();
6185       return getVShift(true, VT,
6186                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6187                                    VT, Op.getOperand(1)),
6188                        NumBits/2, DAG, *this, dl);
6189     }
6190
6191     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6192       return SDValue();
6193
6194     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6195     // is a non-constant being inserted into an element other than the low one,
6196     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6197     // movd/movss) to move this into the low element, then shuffle it into
6198     // place.
6199     if (EVTBits == 32) {
6200       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6201
6202       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6203       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6204       SmallVector<int, 8> MaskVec;
6205       for (unsigned i = 0; i != NumElems; ++i)
6206         MaskVec.push_back(i == Idx ? 0 : 1);
6207       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6208     }
6209   }
6210
6211   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6212   if (Values.size() == 1) {
6213     if (EVTBits == 32) {
6214       // Instead of a shuffle like this:
6215       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6216       // Check if it's possible to issue this instead.
6217       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6218       unsigned Idx = countTrailingZeros(NonZeros);
6219       SDValue Item = Op.getOperand(Idx);
6220       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6221         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6222     }
6223     return SDValue();
6224   }
6225
6226   // A vector full of immediates; various special cases are already
6227   // handled, so this is best done with a single constant-pool load.
6228   if (IsAllConstants)
6229     return SDValue();
6230
6231   // For AVX-length vectors, build the individual 128-bit pieces and use
6232   // shuffles to put them in place.
6233   if (VT.is256BitVector() || VT.is512BitVector()) {
6234     SmallVector<SDValue, 64> V;
6235     for (unsigned i = 0; i != NumElems; ++i)
6236       V.push_back(Op.getOperand(i));
6237
6238     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6239
6240     // Build both the lower and upper subvector.
6241     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6242                                 makeArrayRef(&V[0], NumElems/2));
6243     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6245
6246     // Recreate the wider vector with the lower and upper part.
6247     if (VT.is256BitVector())
6248       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6250   }
6251
6252   // Let legalizer expand 2-wide build_vectors.
6253   if (EVTBits == 64) {
6254     if (NumNonZero == 1) {
6255       // One half is zero or undef.
6256       unsigned Idx = countTrailingZeros(NonZeros);
6257       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6258                                  Op.getOperand(Idx));
6259       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6260     }
6261     return SDValue();
6262   }
6263
6264   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6265   if (EVTBits == 8 && NumElems == 16) {
6266     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6267                                         Subtarget, *this);
6268     if (V.getNode()) return V;
6269   }
6270
6271   if (EVTBits == 16 && NumElems == 8) {
6272     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6273                                       Subtarget, *this);
6274     if (V.getNode()) return V;
6275   }
6276
6277   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6278   if (EVTBits == 32 && NumElems == 4) {
6279     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6280                                       NumZero, DAG, Subtarget, *this);
6281     if (V.getNode())
6282       return V;
6283   }
6284
6285   // If element VT is == 32 bits, turn it into a number of shuffles.
6286   SmallVector<SDValue, 8> V(NumElems);
6287   if (NumElems == 4 && NumZero > 0) {
6288     for (unsigned i = 0; i < 4; ++i) {
6289       bool isZero = !(NonZeros & (1 << i));
6290       if (isZero)
6291         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6292       else
6293         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6294     }
6295
6296     for (unsigned i = 0; i < 2; ++i) {
6297       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6298         default: break;
6299         case 0:
6300           V[i] = V[i*2];  // Must be a zero vector.
6301           break;
6302         case 1:
6303           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6304           break;
6305         case 2:
6306           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6307           break;
6308         case 3:
6309           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6310           break;
6311       }
6312     }
6313
6314     bool Reverse1 = (NonZeros & 0x3) == 2;
6315     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6316     int MaskVec[] = {
6317       Reverse1 ? 1 : 0,
6318       Reverse1 ? 0 : 1,
6319       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6320       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6321     };
6322     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6323   }
6324
6325   if (Values.size() > 1 && VT.is128BitVector()) {
6326     // Check for a build vector of consecutive loads.
6327     for (unsigned i = 0; i < NumElems; ++i)
6328       V[i] = Op.getOperand(i);
6329
6330     // Check for elements which are consecutive loads.
6331     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6332     if (LD.getNode())
6333       return LD;
6334
6335     // Check for a build vector from mostly shuffle plus few inserting.
6336     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6337     if (Sh.getNode())
6338       return Sh;
6339
6340     // For SSE 4.1, use insertps to put the high elements into the low element.
6341     if (getSubtarget()->hasSSE41()) {
6342       SDValue Result;
6343       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6344         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6345       else
6346         Result = DAG.getUNDEF(VT);
6347
6348       for (unsigned i = 1; i < NumElems; ++i) {
6349         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6350         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6351                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6352       }
6353       return Result;
6354     }
6355
6356     // Otherwise, expand into a number of unpckl*, start by extending each of
6357     // our (non-undef) elements to the full vector width with the element in the
6358     // bottom slot of the vector (which generates no code for SSE).
6359     for (unsigned i = 0; i < NumElems; ++i) {
6360       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6361         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6362       else
6363         V[i] = DAG.getUNDEF(VT);
6364     }
6365
6366     // Next, we iteratively mix elements, e.g. for v4f32:
6367     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6368     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6369     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6370     unsigned EltStride = NumElems >> 1;
6371     while (EltStride != 0) {
6372       for (unsigned i = 0; i < EltStride; ++i) {
6373         // If V[i+EltStride] is undef and this is the first round of mixing,
6374         // then it is safe to just drop this shuffle: V[i] is already in the
6375         // right place, the one element (since it's the first round) being
6376         // inserted as undef can be dropped.  This isn't safe for successive
6377         // rounds because they will permute elements within both vectors.
6378         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6379             EltStride == NumElems/2)
6380           continue;
6381
6382         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6383       }
6384       EltStride >>= 1;
6385     }
6386     return V[0];
6387   }
6388   return SDValue();
6389 }
6390
6391 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6392 // to create 256-bit vectors from two other 128-bit ones.
6393 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6394   SDLoc dl(Op);
6395   MVT ResVT = Op.getSimpleValueType();
6396
6397   assert((ResVT.is256BitVector() ||
6398           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6399
6400   SDValue V1 = Op.getOperand(0);
6401   SDValue V2 = Op.getOperand(1);
6402   unsigned NumElems = ResVT.getVectorNumElements();
6403   if(ResVT.is256BitVector())
6404     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6405
6406   if (Op.getNumOperands() == 4) {
6407     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6408                                 ResVT.getVectorNumElements()/2);
6409     SDValue V3 = Op.getOperand(2);
6410     SDValue V4 = Op.getOperand(3);
6411     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6412       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6413   }
6414   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6415 }
6416
6417 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6418   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6419   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6420          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6421           Op.getNumOperands() == 4)));
6422
6423   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6424   // from two other 128-bit ones.
6425
6426   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6427   return LowerAVXCONCAT_VECTORS(Op, DAG);
6428 }
6429
6430 // Try to lower a shuffle node into a simple blend instruction.
6431 static SDValue
6432 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6433                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6434   SDValue V1 = SVOp->getOperand(0);
6435   SDValue V2 = SVOp->getOperand(1);
6436   SDLoc dl(SVOp);
6437   MVT VT = SVOp->getSimpleValueType(0);
6438   MVT EltVT = VT.getVectorElementType();
6439   unsigned NumElems = VT.getVectorNumElements();
6440
6441   // There is no blend with immediate in AVX-512.
6442   if (VT.is512BitVector())
6443     return SDValue();
6444
6445   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6446     return SDValue();
6447   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6448     return SDValue();
6449
6450   // Check the mask for BLEND and build the value.
6451   unsigned MaskValue = 0;
6452   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6453   unsigned NumLanes = (NumElems-1)/8 + 1;
6454   unsigned NumElemsInLane = NumElems / NumLanes;
6455
6456   // Blend for v16i16 should be symetric for the both lanes.
6457   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6458
6459     int SndLaneEltIdx = (NumLanes == 2) ?
6460       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6461     int EltIdx = SVOp->getMaskElt(i);
6462
6463     if ((EltIdx < 0 || EltIdx == (int)i) &&
6464         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6465       continue;
6466
6467     if (((unsigned)EltIdx == (i + NumElems)) &&
6468         (SndLaneEltIdx < 0 ||
6469          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6470       MaskValue |= (1<<i);
6471     else
6472       return SDValue();
6473   }
6474
6475   // Convert i32 vectors to floating point if it is not AVX2.
6476   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6477   MVT BlendVT = VT;
6478   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6479     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6480                                NumElems);
6481     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6482     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6483   }
6484
6485   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6486                             DAG.getConstant(MaskValue, MVT::i32));
6487   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6488 }
6489
6490 /// In vector type \p VT, return true if the element at index \p InputIdx
6491 /// falls on a different 128-bit lane than \p OutputIdx.
6492 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6493                                      unsigned OutputIdx) {
6494   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6495   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6496 }
6497
6498 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6499 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6500 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6501 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6502 /// zero.
6503 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6504                          SelectionDAG &DAG) {
6505   MVT VT = V1.getSimpleValueType();
6506   assert(VT.is128BitVector() || VT.is256BitVector());
6507
6508   MVT EltVT = VT.getVectorElementType();
6509   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6510   unsigned NumElts = VT.getVectorNumElements();
6511
6512   SmallVector<SDValue, 32> PshufbMask;
6513   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6514     int InputIdx = MaskVals[OutputIdx];
6515     unsigned InputByteIdx;
6516
6517     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6518       InputByteIdx = 0x80;
6519     else {
6520       // Cross lane is not allowed.
6521       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6522         return SDValue();
6523       InputByteIdx = InputIdx * EltSizeInBytes;
6524       // Index is an byte offset within the 128-bit lane.
6525       InputByteIdx &= 0xf;
6526     }
6527
6528     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6529       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6530       if (InputByteIdx != 0x80)
6531         ++InputByteIdx;
6532     }
6533   }
6534
6535   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6536   if (ShufVT != VT)
6537     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6538   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6539                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6540 }
6541
6542 // v8i16 shuffles - Prefer shuffles in the following order:
6543 // 1. [all]   pshuflw, pshufhw, optional move
6544 // 2. [ssse3] 1 x pshufb
6545 // 3. [ssse3] 2 x pshufb + 1 x por
6546 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6547 static SDValue
6548 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6549                          SelectionDAG &DAG) {
6550   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6551   SDValue V1 = SVOp->getOperand(0);
6552   SDValue V2 = SVOp->getOperand(1);
6553   SDLoc dl(SVOp);
6554   SmallVector<int, 8> MaskVals;
6555
6556   // Determine if more than 1 of the words in each of the low and high quadwords
6557   // of the result come from the same quadword of one of the two inputs.  Undef
6558   // mask values count as coming from any quadword, for better codegen.
6559   //
6560   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6561   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6562   unsigned LoQuad[] = { 0, 0, 0, 0 };
6563   unsigned HiQuad[] = { 0, 0, 0, 0 };
6564   // Indices of quads used.
6565   std::bitset<4> InputQuads;
6566   for (unsigned i = 0; i < 8; ++i) {
6567     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6568     int EltIdx = SVOp->getMaskElt(i);
6569     MaskVals.push_back(EltIdx);
6570     if (EltIdx < 0) {
6571       ++Quad[0];
6572       ++Quad[1];
6573       ++Quad[2];
6574       ++Quad[3];
6575       continue;
6576     }
6577     ++Quad[EltIdx / 4];
6578     InputQuads.set(EltIdx / 4);
6579   }
6580
6581   int BestLoQuad = -1;
6582   unsigned MaxQuad = 1;
6583   for (unsigned i = 0; i < 4; ++i) {
6584     if (LoQuad[i] > MaxQuad) {
6585       BestLoQuad = i;
6586       MaxQuad = LoQuad[i];
6587     }
6588   }
6589
6590   int BestHiQuad = -1;
6591   MaxQuad = 1;
6592   for (unsigned i = 0; i < 4; ++i) {
6593     if (HiQuad[i] > MaxQuad) {
6594       BestHiQuad = i;
6595       MaxQuad = HiQuad[i];
6596     }
6597   }
6598
6599   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6600   // of the two input vectors, shuffle them into one input vector so only a
6601   // single pshufb instruction is necessary. If there are more than 2 input
6602   // quads, disable the next transformation since it does not help SSSE3.
6603   bool V1Used = InputQuads[0] || InputQuads[1];
6604   bool V2Used = InputQuads[2] || InputQuads[3];
6605   if (Subtarget->hasSSSE3()) {
6606     if (InputQuads.count() == 2 && V1Used && V2Used) {
6607       BestLoQuad = InputQuads[0] ? 0 : 1;
6608       BestHiQuad = InputQuads[2] ? 2 : 3;
6609     }
6610     if (InputQuads.count() > 2) {
6611       BestLoQuad = -1;
6612       BestHiQuad = -1;
6613     }
6614   }
6615
6616   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6617   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6618   // words from all 4 input quadwords.
6619   SDValue NewV;
6620   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6621     int MaskV[] = {
6622       BestLoQuad < 0 ? 0 : BestLoQuad,
6623       BestHiQuad < 0 ? 1 : BestHiQuad
6624     };
6625     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6626                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6627                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6628     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6629
6630     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6631     // source words for the shuffle, to aid later transformations.
6632     bool AllWordsInNewV = true;
6633     bool InOrder[2] = { true, true };
6634     for (unsigned i = 0; i != 8; ++i) {
6635       int idx = MaskVals[i];
6636       if (idx != (int)i)
6637         InOrder[i/4] = false;
6638       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6639         continue;
6640       AllWordsInNewV = false;
6641       break;
6642     }
6643
6644     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6645     if (AllWordsInNewV) {
6646       for (int i = 0; i != 8; ++i) {
6647         int idx = MaskVals[i];
6648         if (idx < 0)
6649           continue;
6650         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6651         if ((idx != i) && idx < 4)
6652           pshufhw = false;
6653         if ((idx != i) && idx > 3)
6654           pshuflw = false;
6655       }
6656       V1 = NewV;
6657       V2Used = false;
6658       BestLoQuad = 0;
6659       BestHiQuad = 1;
6660     }
6661
6662     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6663     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6664     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6665       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6666       unsigned TargetMask = 0;
6667       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6668                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6669       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6670       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6671                              getShufflePSHUFLWImmediate(SVOp);
6672       V1 = NewV.getOperand(0);
6673       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6674     }
6675   }
6676
6677   // Promote splats to a larger type which usually leads to more efficient code.
6678   // FIXME: Is this true if pshufb is available?
6679   if (SVOp->isSplat())
6680     return PromoteSplat(SVOp, DAG);
6681
6682   // If we have SSSE3, and all words of the result are from 1 input vector,
6683   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6684   // is present, fall back to case 4.
6685   if (Subtarget->hasSSSE3()) {
6686     SmallVector<SDValue,16> pshufbMask;
6687
6688     // If we have elements from both input vectors, set the high bit of the
6689     // shuffle mask element to zero out elements that come from V2 in the V1
6690     // mask, and elements that come from V1 in the V2 mask, so that the two
6691     // results can be OR'd together.
6692     bool TwoInputs = V1Used && V2Used;
6693     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6694     if (!TwoInputs)
6695       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6696
6697     // Calculate the shuffle mask for the second input, shuffle it, and
6698     // OR it with the first shuffled input.
6699     CommuteVectorShuffleMask(MaskVals, 8);
6700     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6701     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6702     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6703   }
6704
6705   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6706   // and update MaskVals with new element order.
6707   std::bitset<8> InOrder;
6708   if (BestLoQuad >= 0) {
6709     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6710     for (int i = 0; i != 4; ++i) {
6711       int idx = MaskVals[i];
6712       if (idx < 0) {
6713         InOrder.set(i);
6714       } else if ((idx / 4) == BestLoQuad) {
6715         MaskV[i] = idx & 3;
6716         InOrder.set(i);
6717       }
6718     }
6719     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6720                                 &MaskV[0]);
6721
6722     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6723       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6724       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6725                                   NewV.getOperand(0),
6726                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6727     }
6728   }
6729
6730   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6731   // and update MaskVals with the new element order.
6732   if (BestHiQuad >= 0) {
6733     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6734     for (unsigned i = 4; i != 8; ++i) {
6735       int idx = MaskVals[i];
6736       if (idx < 0) {
6737         InOrder.set(i);
6738       } else if ((idx / 4) == BestHiQuad) {
6739         MaskV[i] = (idx & 3) + 4;
6740         InOrder.set(i);
6741       }
6742     }
6743     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6744                                 &MaskV[0]);
6745
6746     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6747       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6748       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6749                                   NewV.getOperand(0),
6750                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6751     }
6752   }
6753
6754   // In case BestHi & BestLo were both -1, which means each quadword has a word
6755   // from each of the four input quadwords, calculate the InOrder bitvector now
6756   // before falling through to the insert/extract cleanup.
6757   if (BestLoQuad == -1 && BestHiQuad == -1) {
6758     NewV = V1;
6759     for (int i = 0; i != 8; ++i)
6760       if (MaskVals[i] < 0 || MaskVals[i] == i)
6761         InOrder.set(i);
6762   }
6763
6764   // The other elements are put in the right place using pextrw and pinsrw.
6765   for (unsigned i = 0; i != 8; ++i) {
6766     if (InOrder[i])
6767       continue;
6768     int EltIdx = MaskVals[i];
6769     if (EltIdx < 0)
6770       continue;
6771     SDValue ExtOp = (EltIdx < 8) ?
6772       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6773                   DAG.getIntPtrConstant(EltIdx)) :
6774       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6775                   DAG.getIntPtrConstant(EltIdx - 8));
6776     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6777                        DAG.getIntPtrConstant(i));
6778   }
6779   return NewV;
6780 }
6781
6782 /// \brief v16i16 shuffles
6783 ///
6784 /// FIXME: We only support generation of a single pshufb currently.  We can
6785 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6786 /// well (e.g 2 x pshufb + 1 x por).
6787 static SDValue
6788 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6789   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6790   SDValue V1 = SVOp->getOperand(0);
6791   SDValue V2 = SVOp->getOperand(1);
6792   SDLoc dl(SVOp);
6793
6794   if (V2.getOpcode() != ISD::UNDEF)
6795     return SDValue();
6796
6797   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6798   return getPSHUFB(MaskVals, V1, dl, DAG);
6799 }
6800
6801 // v16i8 shuffles - Prefer shuffles in the following order:
6802 // 1. [ssse3] 1 x pshufb
6803 // 2. [ssse3] 2 x pshufb + 1 x por
6804 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6805 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6806                                         const X86Subtarget* Subtarget,
6807                                         SelectionDAG &DAG) {
6808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6809   SDValue V1 = SVOp->getOperand(0);
6810   SDValue V2 = SVOp->getOperand(1);
6811   SDLoc dl(SVOp);
6812   ArrayRef<int> MaskVals = SVOp->getMask();
6813
6814   // Promote splats to a larger type which usually leads to more efficient code.
6815   // FIXME: Is this true if pshufb is available?
6816   if (SVOp->isSplat())
6817     return PromoteSplat(SVOp, DAG);
6818
6819   // If we have SSSE3, case 1 is generated when all result bytes come from
6820   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6821   // present, fall back to case 3.
6822
6823   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6824   if (Subtarget->hasSSSE3()) {
6825     SmallVector<SDValue,16> pshufbMask;
6826
6827     // If all result elements are from one input vector, then only translate
6828     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6829     //
6830     // Otherwise, we have elements from both input vectors, and must zero out
6831     // elements that come from V2 in the first mask, and V1 in the second mask
6832     // so that we can OR them together.
6833     for (unsigned i = 0; i != 16; ++i) {
6834       int EltIdx = MaskVals[i];
6835       if (EltIdx < 0 || EltIdx >= 16)
6836         EltIdx = 0x80;
6837       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6838     }
6839     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6840                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6841                                  MVT::v16i8, pshufbMask));
6842
6843     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6844     // the 2nd operand if it's undefined or zero.
6845     if (V2.getOpcode() == ISD::UNDEF ||
6846         ISD::isBuildVectorAllZeros(V2.getNode()))
6847       return V1;
6848
6849     // Calculate the shuffle mask for the second input, shuffle it, and
6850     // OR it with the first shuffled input.
6851     pshufbMask.clear();
6852     for (unsigned i = 0; i != 16; ++i) {
6853       int EltIdx = MaskVals[i];
6854       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6855       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6856     }
6857     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6858                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6859                                  MVT::v16i8, pshufbMask));
6860     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6861   }
6862
6863   // No SSSE3 - Calculate in place words and then fix all out of place words
6864   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6865   // the 16 different words that comprise the two doublequadword input vectors.
6866   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6867   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6868   SDValue NewV = V1;
6869   for (int i = 0; i != 8; ++i) {
6870     int Elt0 = MaskVals[i*2];
6871     int Elt1 = MaskVals[i*2+1];
6872
6873     // This word of the result is all undef, skip it.
6874     if (Elt0 < 0 && Elt1 < 0)
6875       continue;
6876
6877     // This word of the result is already in the correct place, skip it.
6878     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6879       continue;
6880
6881     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6882     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6883     SDValue InsElt;
6884
6885     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6886     // using a single extract together, load it and store it.
6887     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6888       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6889                            DAG.getIntPtrConstant(Elt1 / 2));
6890       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6891                         DAG.getIntPtrConstant(i));
6892       continue;
6893     }
6894
6895     // If Elt1 is defined, extract it from the appropriate source.  If the
6896     // source byte is not also odd, shift the extracted word left 8 bits
6897     // otherwise clear the bottom 8 bits if we need to do an or.
6898     if (Elt1 >= 0) {
6899       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6900                            DAG.getIntPtrConstant(Elt1 / 2));
6901       if ((Elt1 & 1) == 0)
6902         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6903                              DAG.getConstant(8,
6904                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6905       else if (Elt0 >= 0)
6906         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6907                              DAG.getConstant(0xFF00, MVT::i16));
6908     }
6909     // If Elt0 is defined, extract it from the appropriate source.  If the
6910     // source byte is not also even, shift the extracted word right 8 bits. If
6911     // Elt1 was also defined, OR the extracted values together before
6912     // inserting them in the result.
6913     if (Elt0 >= 0) {
6914       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6915                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6916       if ((Elt0 & 1) != 0)
6917         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6918                               DAG.getConstant(8,
6919                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6920       else if (Elt1 >= 0)
6921         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6922                              DAG.getConstant(0x00FF, MVT::i16));
6923       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6924                          : InsElt0;
6925     }
6926     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6927                        DAG.getIntPtrConstant(i));
6928   }
6929   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6930 }
6931
6932 // v32i8 shuffles - Translate to VPSHUFB if possible.
6933 static
6934 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6935                                  const X86Subtarget *Subtarget,
6936                                  SelectionDAG &DAG) {
6937   MVT VT = SVOp->getSimpleValueType(0);
6938   SDValue V1 = SVOp->getOperand(0);
6939   SDValue V2 = SVOp->getOperand(1);
6940   SDLoc dl(SVOp);
6941   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6942
6943   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6944   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6945   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6946
6947   // VPSHUFB may be generated if
6948   // (1) one of input vector is undefined or zeroinitializer.
6949   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6950   // And (2) the mask indexes don't cross the 128-bit lane.
6951   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6952       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6953     return SDValue();
6954
6955   if (V1IsAllZero && !V2IsAllZero) {
6956     CommuteVectorShuffleMask(MaskVals, 32);
6957     V1 = V2;
6958   }
6959   return getPSHUFB(MaskVals, V1, dl, DAG);
6960 }
6961
6962 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6963 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6964 /// done when every pair / quad of shuffle mask elements point to elements in
6965 /// the right sequence. e.g.
6966 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6967 static
6968 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6969                                  SelectionDAG &DAG) {
6970   MVT VT = SVOp->getSimpleValueType(0);
6971   SDLoc dl(SVOp);
6972   unsigned NumElems = VT.getVectorNumElements();
6973   MVT NewVT;
6974   unsigned Scale;
6975   switch (VT.SimpleTy) {
6976   default: llvm_unreachable("Unexpected!");
6977   case MVT::v2i64:
6978   case MVT::v2f64:
6979            return SDValue(SVOp, 0);
6980   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6981   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6982   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6983   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6984   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6985   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6986   }
6987
6988   SmallVector<int, 8> MaskVec;
6989   for (unsigned i = 0; i != NumElems; i += Scale) {
6990     int StartIdx = -1;
6991     for (unsigned j = 0; j != Scale; ++j) {
6992       int EltIdx = SVOp->getMaskElt(i+j);
6993       if (EltIdx < 0)
6994         continue;
6995       if (StartIdx < 0)
6996         StartIdx = (EltIdx / Scale);
6997       if (EltIdx != (int)(StartIdx*Scale + j))
6998         return SDValue();
6999     }
7000     MaskVec.push_back(StartIdx);
7001   }
7002
7003   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7004   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7005   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7006 }
7007
7008 /// getVZextMovL - Return a zero-extending vector move low node.
7009 ///
7010 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7011                             SDValue SrcOp, SelectionDAG &DAG,
7012                             const X86Subtarget *Subtarget, SDLoc dl) {
7013   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7014     LoadSDNode *LD = nullptr;
7015     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7016       LD = dyn_cast<LoadSDNode>(SrcOp);
7017     if (!LD) {
7018       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7019       // instead.
7020       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7021       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7022           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7023           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7024           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7025         // PR2108
7026         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7027         return DAG.getNode(ISD::BITCAST, dl, VT,
7028                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7029                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7030                                                    OpVT,
7031                                                    SrcOp.getOperand(0)
7032                                                           .getOperand(0))));
7033       }
7034     }
7035   }
7036
7037   return DAG.getNode(ISD::BITCAST, dl, VT,
7038                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7039                                  DAG.getNode(ISD::BITCAST, dl,
7040                                              OpVT, SrcOp)));
7041 }
7042
7043 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7044 /// which could not be matched by any known target speficic shuffle
7045 static SDValue
7046 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7047
7048   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7049   if (NewOp.getNode())
7050     return NewOp;
7051
7052   MVT VT = SVOp->getSimpleValueType(0);
7053
7054   unsigned NumElems = VT.getVectorNumElements();
7055   unsigned NumLaneElems = NumElems / 2;
7056
7057   SDLoc dl(SVOp);
7058   MVT EltVT = VT.getVectorElementType();
7059   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7060   SDValue Output[2];
7061
7062   SmallVector<int, 16> Mask;
7063   for (unsigned l = 0; l < 2; ++l) {
7064     // Build a shuffle mask for the output, discovering on the fly which
7065     // input vectors to use as shuffle operands (recorded in InputUsed).
7066     // If building a suitable shuffle vector proves too hard, then bail
7067     // out with UseBuildVector set.
7068     bool UseBuildVector = false;
7069     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7070     unsigned LaneStart = l * NumLaneElems;
7071     for (unsigned i = 0; i != NumLaneElems; ++i) {
7072       // The mask element.  This indexes into the input.
7073       int Idx = SVOp->getMaskElt(i+LaneStart);
7074       if (Idx < 0) {
7075         // the mask element does not index into any input vector.
7076         Mask.push_back(-1);
7077         continue;
7078       }
7079
7080       // The input vector this mask element indexes into.
7081       int Input = Idx / NumLaneElems;
7082
7083       // Turn the index into an offset from the start of the input vector.
7084       Idx -= Input * NumLaneElems;
7085
7086       // Find or create a shuffle vector operand to hold this input.
7087       unsigned OpNo;
7088       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7089         if (InputUsed[OpNo] == Input)
7090           // This input vector is already an operand.
7091           break;
7092         if (InputUsed[OpNo] < 0) {
7093           // Create a new operand for this input vector.
7094           InputUsed[OpNo] = Input;
7095           break;
7096         }
7097       }
7098
7099       if (OpNo >= array_lengthof(InputUsed)) {
7100         // More than two input vectors used!  Give up on trying to create a
7101         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7102         UseBuildVector = true;
7103         break;
7104       }
7105
7106       // Add the mask index for the new shuffle vector.
7107       Mask.push_back(Idx + OpNo * NumLaneElems);
7108     }
7109
7110     if (UseBuildVector) {
7111       SmallVector<SDValue, 16> SVOps;
7112       for (unsigned i = 0; i != NumLaneElems; ++i) {
7113         // The mask element.  This indexes into the input.
7114         int Idx = SVOp->getMaskElt(i+LaneStart);
7115         if (Idx < 0) {
7116           SVOps.push_back(DAG.getUNDEF(EltVT));
7117           continue;
7118         }
7119
7120         // The input vector this mask element indexes into.
7121         int Input = Idx / NumElems;
7122
7123         // Turn the index into an offset from the start of the input vector.
7124         Idx -= Input * NumElems;
7125
7126         // Extract the vector element by hand.
7127         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7128                                     SVOp->getOperand(Input),
7129                                     DAG.getIntPtrConstant(Idx)));
7130       }
7131
7132       // Construct the output using a BUILD_VECTOR.
7133       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7134     } else if (InputUsed[0] < 0) {
7135       // No input vectors were used! The result is undefined.
7136       Output[l] = DAG.getUNDEF(NVT);
7137     } else {
7138       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7139                                         (InputUsed[0] % 2) * NumLaneElems,
7140                                         DAG, dl);
7141       // If only one input was used, use an undefined vector for the other.
7142       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7143         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7144                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7145       // At least one input vector was used. Create a new shuffle vector.
7146       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7147     }
7148
7149     Mask.clear();
7150   }
7151
7152   // Concatenate the result back
7153   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7154 }
7155
7156 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7157 /// 4 elements, and match them with several different shuffle types.
7158 static SDValue
7159 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7160   SDValue V1 = SVOp->getOperand(0);
7161   SDValue V2 = SVOp->getOperand(1);
7162   SDLoc dl(SVOp);
7163   MVT VT = SVOp->getSimpleValueType(0);
7164
7165   assert(VT.is128BitVector() && "Unsupported vector size");
7166
7167   std::pair<int, int> Locs[4];
7168   int Mask1[] = { -1, -1, -1, -1 };
7169   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7170
7171   unsigned NumHi = 0;
7172   unsigned NumLo = 0;
7173   for (unsigned i = 0; i != 4; ++i) {
7174     int Idx = PermMask[i];
7175     if (Idx < 0) {
7176       Locs[i] = std::make_pair(-1, -1);
7177     } else {
7178       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7179       if (Idx < 4) {
7180         Locs[i] = std::make_pair(0, NumLo);
7181         Mask1[NumLo] = Idx;
7182         NumLo++;
7183       } else {
7184         Locs[i] = std::make_pair(1, NumHi);
7185         if (2+NumHi < 4)
7186           Mask1[2+NumHi] = Idx;
7187         NumHi++;
7188       }
7189     }
7190   }
7191
7192   if (NumLo <= 2 && NumHi <= 2) {
7193     // If no more than two elements come from either vector. This can be
7194     // implemented with two shuffles. First shuffle gather the elements.
7195     // The second shuffle, which takes the first shuffle as both of its
7196     // vector operands, put the elements into the right order.
7197     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7198
7199     int Mask2[] = { -1, -1, -1, -1 };
7200
7201     for (unsigned i = 0; i != 4; ++i)
7202       if (Locs[i].first != -1) {
7203         unsigned Idx = (i < 2) ? 0 : 4;
7204         Idx += Locs[i].first * 2 + Locs[i].second;
7205         Mask2[i] = Idx;
7206       }
7207
7208     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7209   }
7210
7211   if (NumLo == 3 || NumHi == 3) {
7212     // Otherwise, we must have three elements from one vector, call it X, and
7213     // one element from the other, call it Y.  First, use a shufps to build an
7214     // intermediate vector with the one element from Y and the element from X
7215     // that will be in the same half in the final destination (the indexes don't
7216     // matter). Then, use a shufps to build the final vector, taking the half
7217     // containing the element from Y from the intermediate, and the other half
7218     // from X.
7219     if (NumHi == 3) {
7220       // Normalize it so the 3 elements come from V1.
7221       CommuteVectorShuffleMask(PermMask, 4);
7222       std::swap(V1, V2);
7223     }
7224
7225     // Find the element from V2.
7226     unsigned HiIndex;
7227     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7228       int Val = PermMask[HiIndex];
7229       if (Val < 0)
7230         continue;
7231       if (Val >= 4)
7232         break;
7233     }
7234
7235     Mask1[0] = PermMask[HiIndex];
7236     Mask1[1] = -1;
7237     Mask1[2] = PermMask[HiIndex^1];
7238     Mask1[3] = -1;
7239     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7240
7241     if (HiIndex >= 2) {
7242       Mask1[0] = PermMask[0];
7243       Mask1[1] = PermMask[1];
7244       Mask1[2] = HiIndex & 1 ? 6 : 4;
7245       Mask1[3] = HiIndex & 1 ? 4 : 6;
7246       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7247     }
7248
7249     Mask1[0] = HiIndex & 1 ? 2 : 0;
7250     Mask1[1] = HiIndex & 1 ? 0 : 2;
7251     Mask1[2] = PermMask[2];
7252     Mask1[3] = PermMask[3];
7253     if (Mask1[2] >= 0)
7254       Mask1[2] += 4;
7255     if (Mask1[3] >= 0)
7256       Mask1[3] += 4;
7257     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7258   }
7259
7260   // Break it into (shuffle shuffle_hi, shuffle_lo).
7261   int LoMask[] = { -1, -1, -1, -1 };
7262   int HiMask[] = { -1, -1, -1, -1 };
7263
7264   int *MaskPtr = LoMask;
7265   unsigned MaskIdx = 0;
7266   unsigned LoIdx = 0;
7267   unsigned HiIdx = 2;
7268   for (unsigned i = 0; i != 4; ++i) {
7269     if (i == 2) {
7270       MaskPtr = HiMask;
7271       MaskIdx = 1;
7272       LoIdx = 0;
7273       HiIdx = 2;
7274     }
7275     int Idx = PermMask[i];
7276     if (Idx < 0) {
7277       Locs[i] = std::make_pair(-1, -1);
7278     } else if (Idx < 4) {
7279       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7280       MaskPtr[LoIdx] = Idx;
7281       LoIdx++;
7282     } else {
7283       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7284       MaskPtr[HiIdx] = Idx;
7285       HiIdx++;
7286     }
7287   }
7288
7289   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7290   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7291   int MaskOps[] = { -1, -1, -1, -1 };
7292   for (unsigned i = 0; i != 4; ++i)
7293     if (Locs[i].first != -1)
7294       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7295   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7296 }
7297
7298 static bool MayFoldVectorLoad(SDValue V) {
7299   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7300     V = V.getOperand(0);
7301
7302   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7303     V = V.getOperand(0);
7304   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7305       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7306     // BUILD_VECTOR (load), undef
7307     V = V.getOperand(0);
7308
7309   return MayFoldLoad(V);
7310 }
7311
7312 static
7313 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7314   MVT VT = Op.getSimpleValueType();
7315
7316   // Canonizalize to v2f64.
7317   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7318   return DAG.getNode(ISD::BITCAST, dl, VT,
7319                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7320                                           V1, DAG));
7321 }
7322
7323 static
7324 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7325                         bool HasSSE2) {
7326   SDValue V1 = Op.getOperand(0);
7327   SDValue V2 = Op.getOperand(1);
7328   MVT VT = Op.getSimpleValueType();
7329
7330   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7331
7332   if (HasSSE2 && VT == MVT::v2f64)
7333     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7334
7335   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7336   return DAG.getNode(ISD::BITCAST, dl, VT,
7337                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7338                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7339                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7340 }
7341
7342 static
7343 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7344   SDValue V1 = Op.getOperand(0);
7345   SDValue V2 = Op.getOperand(1);
7346   MVT VT = Op.getSimpleValueType();
7347
7348   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7349          "unsupported shuffle type");
7350
7351   if (V2.getOpcode() == ISD::UNDEF)
7352     V2 = V1;
7353
7354   // v4i32 or v4f32
7355   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7356 }
7357
7358 static
7359 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7360   SDValue V1 = Op.getOperand(0);
7361   SDValue V2 = Op.getOperand(1);
7362   MVT VT = Op.getSimpleValueType();
7363   unsigned NumElems = VT.getVectorNumElements();
7364
7365   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7366   // operand of these instructions is only memory, so check if there's a
7367   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7368   // same masks.
7369   bool CanFoldLoad = false;
7370
7371   // Trivial case, when V2 comes from a load.
7372   if (MayFoldVectorLoad(V2))
7373     CanFoldLoad = true;
7374
7375   // When V1 is a load, it can be folded later into a store in isel, example:
7376   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7377   //    turns into:
7378   //  (MOVLPSmr addr:$src1, VR128:$src2)
7379   // So, recognize this potential and also use MOVLPS or MOVLPD
7380   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7381     CanFoldLoad = true;
7382
7383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7384   if (CanFoldLoad) {
7385     if (HasSSE2 && NumElems == 2)
7386       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7387
7388     if (NumElems == 4)
7389       // If we don't care about the second element, proceed to use movss.
7390       if (SVOp->getMaskElt(1) != -1)
7391         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7392   }
7393
7394   // movl and movlp will both match v2i64, but v2i64 is never matched by
7395   // movl earlier because we make it strict to avoid messing with the movlp load
7396   // folding logic (see the code above getMOVLP call). Match it here then,
7397   // this is horrible, but will stay like this until we move all shuffle
7398   // matching to x86 specific nodes. Note that for the 1st condition all
7399   // types are matched with movsd.
7400   if (HasSSE2) {
7401     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7402     // as to remove this logic from here, as much as possible
7403     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7404       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7405     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7406   }
7407
7408   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7409
7410   // Invert the operand order and use SHUFPS to match it.
7411   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7412                               getShuffleSHUFImmediate(SVOp), DAG);
7413 }
7414
7415 // It is only safe to call this function if isINSERTPSMask is true for
7416 // this shufflevector mask.
7417 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7418                            SelectionDAG &DAG) {
7419   // Generate an insertps instruction when inserting an f32 from memory onto a
7420   // v4f32 or when copying a member from one v4f32 to another.
7421   // We also use it for transferring i32 from one register to another,
7422   // since it simply copies the same bits.
7423   // If we're transferring an i32 from memory to a specific element in a
7424   // register, we output a generic DAG that will match the PINSRD
7425   // instruction.
7426   // TODO: Optimize for AVX cases too (VINSERTPS)
7427   MVT VT = SVOp->getSimpleValueType(0);
7428   MVT EVT = VT.getVectorElementType();
7429   SDValue V1 = SVOp->getOperand(0);
7430   SDValue V2 = SVOp->getOperand(1);
7431   auto Mask = SVOp->getMask();
7432   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7433          "unsupported vector type for insertps/pinsrd");
7434
7435   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7436                              [](const int &i) { return i < 4; });
7437
7438   SDValue From;
7439   SDValue To;
7440   unsigned DestIndex;
7441   if (FromV1 == 1) {
7442     From = V1;
7443     To = V2;
7444     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7445                              [](const int &i) { return i < 4; }) -
7446                 Mask.begin();
7447   } else {
7448     From = V2;
7449     To = V1;
7450     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7451                              [](const int &i) { return i >= 4; }) -
7452                 Mask.begin();
7453   }
7454
7455   if (MayFoldLoad(From)) {
7456     // Trivial case, when From comes from a load and is only used by the
7457     // shuffle. Make it use insertps from the vector that we need from that
7458     // load.
7459     SDValue Addr = From.getOperand(1);
7460     SDValue NewAddr =
7461         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7462                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7463                                     Addr.getSimpleValueType()));
7464
7465     LoadSDNode *Load = cast<LoadSDNode>(From);
7466     SDValue NewLoad =
7467         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7468                     DAG.getMachineFunction().getMachineMemOperand(
7469                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7470
7471     if (EVT == MVT::f32) {
7472       // Create this as a scalar to vector to match the instruction pattern.
7473       SDValue LoadScalarToVector =
7474           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7475       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7476       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7477                          InsertpsMask);
7478     } else { // EVT == MVT::i32
7479       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7480       // instruction, to match the PINSRD instruction, which loads an i32 to a
7481       // certain vector element.
7482       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7483                          DAG.getConstant(DestIndex, MVT::i32));
7484     }
7485   }
7486
7487   // Vector-element-to-vector
7488   unsigned SrcIndex = Mask[DestIndex] % 4;
7489   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7490   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7491 }
7492
7493 // Reduce a vector shuffle to zext.
7494 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7495                                     SelectionDAG &DAG) {
7496   // PMOVZX is only available from SSE41.
7497   if (!Subtarget->hasSSE41())
7498     return SDValue();
7499
7500   MVT VT = Op.getSimpleValueType();
7501
7502   // Only AVX2 support 256-bit vector integer extending.
7503   if (!Subtarget->hasInt256() && VT.is256BitVector())
7504     return SDValue();
7505
7506   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7507   SDLoc DL(Op);
7508   SDValue V1 = Op.getOperand(0);
7509   SDValue V2 = Op.getOperand(1);
7510   unsigned NumElems = VT.getVectorNumElements();
7511
7512   // Extending is an unary operation and the element type of the source vector
7513   // won't be equal to or larger than i64.
7514   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7515       VT.getVectorElementType() == MVT::i64)
7516     return SDValue();
7517
7518   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7519   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7520   while ((1U << Shift) < NumElems) {
7521     if (SVOp->getMaskElt(1U << Shift) == 1)
7522       break;
7523     Shift += 1;
7524     // The maximal ratio is 8, i.e. from i8 to i64.
7525     if (Shift > 3)
7526       return SDValue();
7527   }
7528
7529   // Check the shuffle mask.
7530   unsigned Mask = (1U << Shift) - 1;
7531   for (unsigned i = 0; i != NumElems; ++i) {
7532     int EltIdx = SVOp->getMaskElt(i);
7533     if ((i & Mask) != 0 && EltIdx != -1)
7534       return SDValue();
7535     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7536       return SDValue();
7537   }
7538
7539   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7540   MVT NeVT = MVT::getIntegerVT(NBits);
7541   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7542
7543   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7544     return SDValue();
7545
7546   // Simplify the operand as it's prepared to be fed into shuffle.
7547   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7548   if (V1.getOpcode() == ISD::BITCAST &&
7549       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7550       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7551       V1.getOperand(0).getOperand(0)
7552         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7553     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7554     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7555     ConstantSDNode *CIdx =
7556       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7557     // If it's foldable, i.e. normal load with single use, we will let code
7558     // selection to fold it. Otherwise, we will short the conversion sequence.
7559     if (CIdx && CIdx->getZExtValue() == 0 &&
7560         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7561       MVT FullVT = V.getSimpleValueType();
7562       MVT V1VT = V1.getSimpleValueType();
7563       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7564         // The "ext_vec_elt" node is wider than the result node.
7565         // In this case we should extract subvector from V.
7566         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7567         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7568         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7569                                         FullVT.getVectorNumElements()/Ratio);
7570         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7571                         DAG.getIntPtrConstant(0));
7572       }
7573       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7574     }
7575   }
7576
7577   return DAG.getNode(ISD::BITCAST, DL, VT,
7578                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7579 }
7580
7581 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7582                                       SelectionDAG &DAG) {
7583   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7584   MVT VT = Op.getSimpleValueType();
7585   SDLoc dl(Op);
7586   SDValue V1 = Op.getOperand(0);
7587   SDValue V2 = Op.getOperand(1);
7588
7589   if (isZeroShuffle(SVOp))
7590     return getZeroVector(VT, Subtarget, DAG, dl);
7591
7592   // Handle splat operations
7593   if (SVOp->isSplat()) {
7594     // Use vbroadcast whenever the splat comes from a foldable load
7595     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7596     if (Broadcast.getNode())
7597       return Broadcast;
7598   }
7599
7600   // Check integer expanding shuffles.
7601   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7602   if (NewOp.getNode())
7603     return NewOp;
7604
7605   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7606   // do it!
7607   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7608       VT == MVT::v32i8) {
7609     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7610     if (NewOp.getNode())
7611       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7612   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7613     // FIXME: Figure out a cleaner way to do this.
7614     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7615       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7616       if (NewOp.getNode()) {
7617         MVT NewVT = NewOp.getSimpleValueType();
7618         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7619                                NewVT, true, false))
7620           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7621                               dl);
7622       }
7623     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7624       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7625       if (NewOp.getNode()) {
7626         MVT NewVT = NewOp.getSimpleValueType();
7627         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7628           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7629                               dl);
7630       }
7631     }
7632   }
7633   return SDValue();
7634 }
7635
7636 SDValue
7637 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7639   SDValue V1 = Op.getOperand(0);
7640   SDValue V2 = Op.getOperand(1);
7641   MVT VT = Op.getSimpleValueType();
7642   SDLoc dl(Op);
7643   unsigned NumElems = VT.getVectorNumElements();
7644   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7645   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7646   bool V1IsSplat = false;
7647   bool V2IsSplat = false;
7648   bool HasSSE2 = Subtarget->hasSSE2();
7649   bool HasFp256    = Subtarget->hasFp256();
7650   bool HasInt256   = Subtarget->hasInt256();
7651   MachineFunction &MF = DAG.getMachineFunction();
7652   bool OptForSize = MF.getFunction()->getAttributes().
7653     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7654
7655   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7656
7657   if (V1IsUndef && V2IsUndef)
7658     return DAG.getUNDEF(VT);
7659
7660   // When we create a shuffle node we put the UNDEF node to second operand,
7661   // but in some cases the first operand may be transformed to UNDEF.
7662   // In this case we should just commute the node.
7663   if (V1IsUndef)
7664     return CommuteVectorShuffle(SVOp, DAG);
7665
7666   // Vector shuffle lowering takes 3 steps:
7667   //
7668   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7669   //    narrowing and commutation of operands should be handled.
7670   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7671   //    shuffle nodes.
7672   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7673   //    so the shuffle can be broken into other shuffles and the legalizer can
7674   //    try the lowering again.
7675   //
7676   // The general idea is that no vector_shuffle operation should be left to
7677   // be matched during isel, all of them must be converted to a target specific
7678   // node here.
7679
7680   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7681   // narrowing and commutation of operands should be handled. The actual code
7682   // doesn't include all of those, work in progress...
7683   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7684   if (NewOp.getNode())
7685     return NewOp;
7686
7687   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7688
7689   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7690   // unpckh_undef). Only use pshufd if speed is more important than size.
7691   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7692     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7693   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7694     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7695
7696   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7697       V2IsUndef && MayFoldVectorLoad(V1))
7698     return getMOVDDup(Op, dl, V1, DAG);
7699
7700   if (isMOVHLPS_v_undef_Mask(M, VT))
7701     return getMOVHighToLow(Op, dl, DAG);
7702
7703   // Use to match splats
7704   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7705       (VT == MVT::v2f64 || VT == MVT::v2i64))
7706     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7707
7708   if (isPSHUFDMask(M, VT)) {
7709     // The actual implementation will match the mask in the if above and then
7710     // during isel it can match several different instructions, not only pshufd
7711     // as its name says, sad but true, emulate the behavior for now...
7712     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7713       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7714
7715     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7716
7717     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7718       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7719
7720     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7721       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7722                                   DAG);
7723
7724     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7725                                 TargetMask, DAG);
7726   }
7727
7728   if (isPALIGNRMask(M, VT, Subtarget))
7729     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7730                                 getShufflePALIGNRImmediate(SVOp),
7731                                 DAG);
7732
7733   // Check if this can be converted into a logical shift.
7734   bool isLeft = false;
7735   unsigned ShAmt = 0;
7736   SDValue ShVal;
7737   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7738   if (isShift && ShVal.hasOneUse()) {
7739     // If the shifted value has multiple uses, it may be cheaper to use
7740     // v_set0 + movlhps or movhlps, etc.
7741     MVT EltVT = VT.getVectorElementType();
7742     ShAmt *= EltVT.getSizeInBits();
7743     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7744   }
7745
7746   if (isMOVLMask(M, VT)) {
7747     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7748       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7749     if (!isMOVLPMask(M, VT)) {
7750       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7751         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7752
7753       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7754         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7755     }
7756   }
7757
7758   // FIXME: fold these into legal mask.
7759   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7760     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7761
7762   if (isMOVHLPSMask(M, VT))
7763     return getMOVHighToLow(Op, dl, DAG);
7764
7765   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7766     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7767
7768   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7769     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7770
7771   if (isMOVLPMask(M, VT))
7772     return getMOVLP(Op, dl, DAG, HasSSE2);
7773
7774   if (ShouldXformToMOVHLPS(M, VT) ||
7775       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7776     return CommuteVectorShuffle(SVOp, DAG);
7777
7778   if (isShift) {
7779     // No better options. Use a vshldq / vsrldq.
7780     MVT EltVT = VT.getVectorElementType();
7781     ShAmt *= EltVT.getSizeInBits();
7782     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7783   }
7784
7785   bool Commuted = false;
7786   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7787   // 1,1,1,1 -> v8i16 though.
7788   V1IsSplat = isSplatVector(V1.getNode());
7789   V2IsSplat = isSplatVector(V2.getNode());
7790
7791   // Canonicalize the splat or undef, if present, to be on the RHS.
7792   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7793     CommuteVectorShuffleMask(M, NumElems);
7794     std::swap(V1, V2);
7795     std::swap(V1IsSplat, V2IsSplat);
7796     Commuted = true;
7797   }
7798
7799   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7800     // Shuffling low element of v1 into undef, just return v1.
7801     if (V2IsUndef)
7802       return V1;
7803     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7804     // the instruction selector will not match, so get a canonical MOVL with
7805     // swapped operands to undo the commute.
7806     return getMOVL(DAG, dl, VT, V2, V1);
7807   }
7808
7809   if (isUNPCKLMask(M, VT, HasInt256))
7810     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7811
7812   if (isUNPCKHMask(M, VT, HasInt256))
7813     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7814
7815   if (V2IsSplat) {
7816     // Normalize mask so all entries that point to V2 points to its first
7817     // element then try to match unpck{h|l} again. If match, return a
7818     // new vector_shuffle with the corrected mask.p
7819     SmallVector<int, 8> NewMask(M.begin(), M.end());
7820     NormalizeMask(NewMask, NumElems);
7821     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7822       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7823     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7824       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7825   }
7826
7827   if (Commuted) {
7828     // Commute is back and try unpck* again.
7829     // FIXME: this seems wrong.
7830     CommuteVectorShuffleMask(M, NumElems);
7831     std::swap(V1, V2);
7832     std::swap(V1IsSplat, V2IsSplat);
7833
7834     if (isUNPCKLMask(M, VT, HasInt256))
7835       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7836
7837     if (isUNPCKHMask(M, VT, HasInt256))
7838       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7839   }
7840
7841   // Normalize the node to match x86 shuffle ops if needed
7842   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7843     return CommuteVectorShuffle(SVOp, DAG);
7844
7845   // The checks below are all present in isShuffleMaskLegal, but they are
7846   // inlined here right now to enable us to directly emit target specific
7847   // nodes, and remove one by one until they don't return Op anymore.
7848
7849   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7850       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7851     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7852       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7853   }
7854
7855   if (isPSHUFHWMask(M, VT, HasInt256))
7856     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7857                                 getShufflePSHUFHWImmediate(SVOp),
7858                                 DAG);
7859
7860   if (isPSHUFLWMask(M, VT, HasInt256))
7861     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7862                                 getShufflePSHUFLWImmediate(SVOp),
7863                                 DAG);
7864
7865   if (isSHUFPMask(M, VT))
7866     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7867                                 getShuffleSHUFImmediate(SVOp), DAG);
7868
7869   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7870     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7871   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7872     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7873
7874   //===--------------------------------------------------------------------===//
7875   // Generate target specific nodes for 128 or 256-bit shuffles only
7876   // supported in the AVX instruction set.
7877   //
7878
7879   // Handle VMOVDDUPY permutations
7880   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7881     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7882
7883   // Handle VPERMILPS/D* permutations
7884   if (isVPERMILPMask(M, VT)) {
7885     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7886       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7887                                   getShuffleSHUFImmediate(SVOp), DAG);
7888     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7889                                 getShuffleSHUFImmediate(SVOp), DAG);
7890   }
7891
7892   unsigned Idx;
7893   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7894     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7895                               Idx*(NumElems/2), DAG, dl);
7896
7897   // Handle VPERM2F128/VPERM2I128 permutations
7898   if (isVPERM2X128Mask(M, VT, HasFp256))
7899     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7900                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7901
7902   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7903   if (BlendOp.getNode())
7904     return BlendOp;
7905
7906   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7907     return getINSERTPS(SVOp, dl, DAG);
7908
7909   unsigned Imm8;
7910   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7911     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7912
7913   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7914       VT.is512BitVector()) {
7915     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7916     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7917     SmallVector<SDValue, 16> permclMask;
7918     for (unsigned i = 0; i != NumElems; ++i) {
7919       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7920     }
7921
7922     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7923     if (V2IsUndef)
7924       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7925       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7926                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7927     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7928                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7929   }
7930
7931   //===--------------------------------------------------------------------===//
7932   // Since no target specific shuffle was selected for this generic one,
7933   // lower it into other known shuffles. FIXME: this isn't true yet, but
7934   // this is the plan.
7935   //
7936
7937   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7938   if (VT == MVT::v8i16) {
7939     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7940     if (NewOp.getNode())
7941       return NewOp;
7942   }
7943
7944   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7945     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7946     if (NewOp.getNode())
7947       return NewOp;
7948   }
7949
7950   if (VT == MVT::v16i8) {
7951     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7952     if (NewOp.getNode())
7953       return NewOp;
7954   }
7955
7956   if (VT == MVT::v32i8) {
7957     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7958     if (NewOp.getNode())
7959       return NewOp;
7960   }
7961
7962   // Handle all 128-bit wide vectors with 4 elements, and match them with
7963   // several different shuffle types.
7964   if (NumElems == 4 && VT.is128BitVector())
7965     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7966
7967   // Handle general 256-bit shuffles
7968   if (VT.is256BitVector())
7969     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7970
7971   return SDValue();
7972 }
7973
7974 // This function assumes its argument is a BUILD_VECTOR of constand or
7975 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
7976 // true.
7977 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
7978                                     unsigned &MaskValue) {
7979   MaskValue = 0;
7980   unsigned NumElems = BuildVector->getNumOperands();
7981   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7982   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7983   unsigned NumElemsInLane = NumElems / NumLanes;
7984
7985   // Blend for v16i16 should be symetric for the both lanes.
7986   for (unsigned i = 0; i < NumElemsInLane; ++i) {
7987     SDValue EltCond = BuildVector->getOperand(i);
7988     SDValue SndLaneEltCond =
7989         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
7990
7991     int Lane1Cond = -1, Lane2Cond = -1;
7992     if (isa<ConstantSDNode>(EltCond))
7993       Lane1Cond = !isZero(EltCond);
7994     if (isa<ConstantSDNode>(SndLaneEltCond))
7995       Lane2Cond = !isZero(SndLaneEltCond);
7996
7997     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
7998       MaskValue |= !!Lane1Cond << i;
7999     else if (Lane1Cond < 0)
8000       MaskValue |= !!Lane2Cond << i;
8001     else
8002       return false;
8003   }
8004   return true;
8005 }
8006
8007 // Try to lower a vselect node into a simple blend instruction.
8008 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8009                                    SelectionDAG &DAG) {
8010   SDValue Cond = Op.getOperand(0);
8011   SDValue LHS = Op.getOperand(1);
8012   SDValue RHS = Op.getOperand(2);
8013   SDLoc dl(Op);
8014   MVT VT = Op.getSimpleValueType();
8015   MVT EltVT = VT.getVectorElementType();
8016   unsigned NumElems = VT.getVectorNumElements();
8017
8018   // There is no blend with immediate in AVX-512.
8019   if (VT.is512BitVector())
8020     return SDValue();
8021
8022   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8023     return SDValue();
8024   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8025     return SDValue();
8026
8027   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8028     return SDValue();
8029
8030   // Check the mask for BLEND and build the value.
8031   unsigned MaskValue = 0;
8032   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8033     return SDValue();
8034
8035   // Convert i32 vectors to floating point if it is not AVX2.
8036   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8037   MVT BlendVT = VT;
8038   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8039     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8040                                NumElems);
8041     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8042     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8043   }
8044
8045   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8046                             DAG.getConstant(MaskValue, MVT::i32));
8047   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8048 }
8049
8050 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8051   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8052   if (BlendOp.getNode())
8053     return BlendOp;
8054
8055   // Some types for vselect were previously set to Expand, not Legal or
8056   // Custom. Return an empty SDValue so we fall-through to Expand, after
8057   // the Custom lowering phase.
8058   MVT VT = Op.getSimpleValueType();
8059   switch (VT.SimpleTy) {
8060   default:
8061     break;
8062   case MVT::v8i16:
8063   case MVT::v16i16:
8064     return SDValue();
8065   }
8066
8067   // We couldn't create a "Blend with immediate" node.
8068   // This node should still be legal, but we'll have to emit a blendv*
8069   // instruction.
8070   return Op;
8071 }
8072
8073 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8074   MVT VT = Op.getSimpleValueType();
8075   SDLoc dl(Op);
8076
8077   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8078     return SDValue();
8079
8080   if (VT.getSizeInBits() == 8) {
8081     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8082                                   Op.getOperand(0), Op.getOperand(1));
8083     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8084                                   DAG.getValueType(VT));
8085     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8086   }
8087
8088   if (VT.getSizeInBits() == 16) {
8089     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8090     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8091     if (Idx == 0)
8092       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8093                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8094                                      DAG.getNode(ISD::BITCAST, dl,
8095                                                  MVT::v4i32,
8096                                                  Op.getOperand(0)),
8097                                      Op.getOperand(1)));
8098     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8099                                   Op.getOperand(0), Op.getOperand(1));
8100     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8101                                   DAG.getValueType(VT));
8102     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8103   }
8104
8105   if (VT == MVT::f32) {
8106     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8107     // the result back to FR32 register. It's only worth matching if the
8108     // result has a single use which is a store or a bitcast to i32.  And in
8109     // the case of a store, it's not worth it if the index is a constant 0,
8110     // because a MOVSSmr can be used instead, which is smaller and faster.
8111     if (!Op.hasOneUse())
8112       return SDValue();
8113     SDNode *User = *Op.getNode()->use_begin();
8114     if ((User->getOpcode() != ISD::STORE ||
8115          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8116           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8117         (User->getOpcode() != ISD::BITCAST ||
8118          User->getValueType(0) != MVT::i32))
8119       return SDValue();
8120     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8121                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8122                                               Op.getOperand(0)),
8123                                               Op.getOperand(1));
8124     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8125   }
8126
8127   if (VT == MVT::i32 || VT == MVT::i64) {
8128     // ExtractPS/pextrq works with constant index.
8129     if (isa<ConstantSDNode>(Op.getOperand(1)))
8130       return Op;
8131   }
8132   return SDValue();
8133 }
8134
8135 /// Extract one bit from mask vector, like v16i1 or v8i1.
8136 /// AVX-512 feature.
8137 SDValue
8138 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8139   SDValue Vec = Op.getOperand(0);
8140   SDLoc dl(Vec);
8141   MVT VecVT = Vec.getSimpleValueType();
8142   SDValue Idx = Op.getOperand(1);
8143   MVT EltVT = Op.getSimpleValueType();
8144
8145   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8146
8147   // variable index can't be handled in mask registers,
8148   // extend vector to VR512
8149   if (!isa<ConstantSDNode>(Idx)) {
8150     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8151     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8152     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8153                               ExtVT.getVectorElementType(), Ext, Idx);
8154     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8155   }
8156
8157   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8158   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8159   unsigned MaxSift = rc->getSize()*8 - 1;
8160   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8161                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8162   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8163                     DAG.getConstant(MaxSift, MVT::i8));
8164   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8165                        DAG.getIntPtrConstant(0));
8166 }
8167
8168 SDValue
8169 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8170                                            SelectionDAG &DAG) const {
8171   SDLoc dl(Op);
8172   SDValue Vec = Op.getOperand(0);
8173   MVT VecVT = Vec.getSimpleValueType();
8174   SDValue Idx = Op.getOperand(1);
8175
8176   if (Op.getSimpleValueType() == MVT::i1)
8177     return ExtractBitFromMaskVector(Op, DAG);
8178
8179   if (!isa<ConstantSDNode>(Idx)) {
8180     if (VecVT.is512BitVector() ||
8181         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8182          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8183
8184       MVT MaskEltVT =
8185         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8186       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8187                                     MaskEltVT.getSizeInBits());
8188
8189       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8190       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8191                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8192                                 Idx, DAG.getConstant(0, getPointerTy()));
8193       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8194       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8195                         Perm, DAG.getConstant(0, getPointerTy()));
8196     }
8197     return SDValue();
8198   }
8199
8200   // If this is a 256-bit vector result, first extract the 128-bit vector and
8201   // then extract the element from the 128-bit vector.
8202   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8203
8204     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8205     // Get the 128-bit vector.
8206     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8207     MVT EltVT = VecVT.getVectorElementType();
8208
8209     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8210
8211     //if (IdxVal >= NumElems/2)
8212     //  IdxVal -= NumElems/2;
8213     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8214     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8215                        DAG.getConstant(IdxVal, MVT::i32));
8216   }
8217
8218   assert(VecVT.is128BitVector() && "Unexpected vector length");
8219
8220   if (Subtarget->hasSSE41()) {
8221     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8222     if (Res.getNode())
8223       return Res;
8224   }
8225
8226   MVT VT = Op.getSimpleValueType();
8227   // TODO: handle v16i8.
8228   if (VT.getSizeInBits() == 16) {
8229     SDValue Vec = Op.getOperand(0);
8230     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8231     if (Idx == 0)
8232       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8233                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8234                                      DAG.getNode(ISD::BITCAST, dl,
8235                                                  MVT::v4i32, Vec),
8236                                      Op.getOperand(1)));
8237     // Transform it so it match pextrw which produces a 32-bit result.
8238     MVT EltVT = MVT::i32;
8239     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8240                                   Op.getOperand(0), Op.getOperand(1));
8241     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8242                                   DAG.getValueType(VT));
8243     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8244   }
8245
8246   if (VT.getSizeInBits() == 32) {
8247     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8248     if (Idx == 0)
8249       return Op;
8250
8251     // SHUFPS the element to the lowest double word, then movss.
8252     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8253     MVT VVT = Op.getOperand(0).getSimpleValueType();
8254     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8255                                        DAG.getUNDEF(VVT), Mask);
8256     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8257                        DAG.getIntPtrConstant(0));
8258   }
8259
8260   if (VT.getSizeInBits() == 64) {
8261     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8262     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8263     //        to match extract_elt for f64.
8264     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8265     if (Idx == 0)
8266       return Op;
8267
8268     // UNPCKHPD the element to the lowest double word, then movsd.
8269     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8270     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8271     int Mask[2] = { 1, -1 };
8272     MVT VVT = Op.getOperand(0).getSimpleValueType();
8273     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8274                                        DAG.getUNDEF(VVT), Mask);
8275     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8276                        DAG.getIntPtrConstant(0));
8277   }
8278
8279   return SDValue();
8280 }
8281
8282 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8283   MVT VT = Op.getSimpleValueType();
8284   MVT EltVT = VT.getVectorElementType();
8285   SDLoc dl(Op);
8286
8287   SDValue N0 = Op.getOperand(0);
8288   SDValue N1 = Op.getOperand(1);
8289   SDValue N2 = Op.getOperand(2);
8290
8291   if (!VT.is128BitVector())
8292     return SDValue();
8293
8294   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8295       isa<ConstantSDNode>(N2)) {
8296     unsigned Opc;
8297     if (VT == MVT::v8i16)
8298       Opc = X86ISD::PINSRW;
8299     else if (VT == MVT::v16i8)
8300       Opc = X86ISD::PINSRB;
8301     else
8302       Opc = X86ISD::PINSRB;
8303
8304     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8305     // argument.
8306     if (N1.getValueType() != MVT::i32)
8307       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8308     if (N2.getValueType() != MVT::i32)
8309       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8310     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8311   }
8312
8313   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8314     // Bits [7:6] of the constant are the source select.  This will always be
8315     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8316     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8317     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8318     // Bits [5:4] of the constant are the destination select.  This is the
8319     //  value of the incoming immediate.
8320     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8321     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8322     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8323     // Create this as a scalar to vector..
8324     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8325     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8326   }
8327
8328   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8329     // PINSR* works with constant index.
8330     return Op;
8331   }
8332   return SDValue();
8333 }
8334
8335 /// Insert one bit to mask vector, like v16i1 or v8i1.
8336 /// AVX-512 feature.
8337 SDValue 
8338 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8339   SDLoc dl(Op);
8340   SDValue Vec = Op.getOperand(0);
8341   SDValue Elt = Op.getOperand(1);
8342   SDValue Idx = Op.getOperand(2);
8343   MVT VecVT = Vec.getSimpleValueType();
8344
8345   if (!isa<ConstantSDNode>(Idx)) {
8346     // Non constant index. Extend source and destination,
8347     // insert element and then truncate the result.
8348     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8349     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8350     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8351       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8352       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8353     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8354   }
8355
8356   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8357   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8358   if (Vec.getOpcode() == ISD::UNDEF)
8359     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8360                        DAG.getConstant(IdxVal, MVT::i8));
8361   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8362   unsigned MaxSift = rc->getSize()*8 - 1;
8363   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8364                     DAG.getConstant(MaxSift, MVT::i8));
8365   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8366                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8367   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8368 }
8369 SDValue
8370 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8371   MVT VT = Op.getSimpleValueType();
8372   MVT EltVT = VT.getVectorElementType();
8373   
8374   if (EltVT == MVT::i1)
8375     return InsertBitToMaskVector(Op, DAG);
8376
8377   SDLoc dl(Op);
8378   SDValue N0 = Op.getOperand(0);
8379   SDValue N1 = Op.getOperand(1);
8380   SDValue N2 = Op.getOperand(2);
8381
8382   // If this is a 256-bit vector result, first extract the 128-bit vector,
8383   // insert the element into the extracted half and then place it back.
8384   if (VT.is256BitVector() || VT.is512BitVector()) {
8385     if (!isa<ConstantSDNode>(N2))
8386       return SDValue();
8387
8388     // Get the desired 128-bit vector half.
8389     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8390     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8391
8392     // Insert the element into the desired half.
8393     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8394     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8395
8396     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8397                     DAG.getConstant(IdxIn128, MVT::i32));
8398
8399     // Insert the changed part back to the 256-bit vector
8400     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8401   }
8402
8403   if (Subtarget->hasSSE41())
8404     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8405
8406   if (EltVT == MVT::i8)
8407     return SDValue();
8408
8409   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8410     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8411     // as its second argument.
8412     if (N1.getValueType() != MVT::i32)
8413       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8414     if (N2.getValueType() != MVT::i32)
8415       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8416     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8417   }
8418   return SDValue();
8419 }
8420
8421 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8422   SDLoc dl(Op);
8423   MVT OpVT = Op.getSimpleValueType();
8424
8425   // If this is a 256-bit vector result, first insert into a 128-bit
8426   // vector and then insert into the 256-bit vector.
8427   if (!OpVT.is128BitVector()) {
8428     // Insert into a 128-bit vector.
8429     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8430     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8431                                  OpVT.getVectorNumElements() / SizeFactor);
8432
8433     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8434
8435     // Insert the 128-bit vector.
8436     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8437   }
8438
8439   if (OpVT == MVT::v1i64 &&
8440       Op.getOperand(0).getValueType() == MVT::i64)
8441     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8442
8443   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8444   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8445   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8446                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8447 }
8448
8449 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8450 // a simple subregister reference or explicit instructions to grab
8451 // upper bits of a vector.
8452 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8453                                       SelectionDAG &DAG) {
8454   SDLoc dl(Op);
8455   SDValue In =  Op.getOperand(0);
8456   SDValue Idx = Op.getOperand(1);
8457   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8458   MVT ResVT   = Op.getSimpleValueType();
8459   MVT InVT    = In.getSimpleValueType();
8460
8461   if (Subtarget->hasFp256()) {
8462     if (ResVT.is128BitVector() &&
8463         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8464         isa<ConstantSDNode>(Idx)) {
8465       return Extract128BitVector(In, IdxVal, DAG, dl);
8466     }
8467     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8468         isa<ConstantSDNode>(Idx)) {
8469       return Extract256BitVector(In, IdxVal, DAG, dl);
8470     }
8471   }
8472   return SDValue();
8473 }
8474
8475 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8476 // simple superregister reference or explicit instructions to insert
8477 // the upper bits of a vector.
8478 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8479                                      SelectionDAG &DAG) {
8480   if (Subtarget->hasFp256()) {
8481     SDLoc dl(Op.getNode());
8482     SDValue Vec = Op.getNode()->getOperand(0);
8483     SDValue SubVec = Op.getNode()->getOperand(1);
8484     SDValue Idx = Op.getNode()->getOperand(2);
8485
8486     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8487          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8488         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8489         isa<ConstantSDNode>(Idx)) {
8490       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8491       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8492     }
8493
8494     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8495         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8496         isa<ConstantSDNode>(Idx)) {
8497       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8498       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8499     }
8500   }
8501   return SDValue();
8502 }
8503
8504 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8505 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8506 // one of the above mentioned nodes. It has to be wrapped because otherwise
8507 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8508 // be used to form addressing mode. These wrapped nodes will be selected
8509 // into MOV32ri.
8510 SDValue
8511 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8512   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8513
8514   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8515   // global base reg.
8516   unsigned char OpFlag = 0;
8517   unsigned WrapperKind = X86ISD::Wrapper;
8518   CodeModel::Model M = getTargetMachine().getCodeModel();
8519
8520   if (Subtarget->isPICStyleRIPRel() &&
8521       (M == CodeModel::Small || M == CodeModel::Kernel))
8522     WrapperKind = X86ISD::WrapperRIP;
8523   else if (Subtarget->isPICStyleGOT())
8524     OpFlag = X86II::MO_GOTOFF;
8525   else if (Subtarget->isPICStyleStubPIC())
8526     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8527
8528   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8529                                              CP->getAlignment(),
8530                                              CP->getOffset(), OpFlag);
8531   SDLoc DL(CP);
8532   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8533   // With PIC, the address is actually $g + Offset.
8534   if (OpFlag) {
8535     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8536                          DAG.getNode(X86ISD::GlobalBaseReg,
8537                                      SDLoc(), getPointerTy()),
8538                          Result);
8539   }
8540
8541   return Result;
8542 }
8543
8544 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8545   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8546
8547   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8548   // global base reg.
8549   unsigned char OpFlag = 0;
8550   unsigned WrapperKind = X86ISD::Wrapper;
8551   CodeModel::Model M = getTargetMachine().getCodeModel();
8552
8553   if (Subtarget->isPICStyleRIPRel() &&
8554       (M == CodeModel::Small || M == CodeModel::Kernel))
8555     WrapperKind = X86ISD::WrapperRIP;
8556   else if (Subtarget->isPICStyleGOT())
8557     OpFlag = X86II::MO_GOTOFF;
8558   else if (Subtarget->isPICStyleStubPIC())
8559     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8560
8561   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8562                                           OpFlag);
8563   SDLoc DL(JT);
8564   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8565
8566   // With PIC, the address is actually $g + Offset.
8567   if (OpFlag)
8568     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8569                          DAG.getNode(X86ISD::GlobalBaseReg,
8570                                      SDLoc(), getPointerTy()),
8571                          Result);
8572
8573   return Result;
8574 }
8575
8576 SDValue
8577 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8578   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8579
8580   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8581   // global base reg.
8582   unsigned char OpFlag = 0;
8583   unsigned WrapperKind = X86ISD::Wrapper;
8584   CodeModel::Model M = getTargetMachine().getCodeModel();
8585
8586   if (Subtarget->isPICStyleRIPRel() &&
8587       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8588     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8589       OpFlag = X86II::MO_GOTPCREL;
8590     WrapperKind = X86ISD::WrapperRIP;
8591   } else if (Subtarget->isPICStyleGOT()) {
8592     OpFlag = X86II::MO_GOT;
8593   } else if (Subtarget->isPICStyleStubPIC()) {
8594     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8595   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8596     OpFlag = X86II::MO_DARWIN_NONLAZY;
8597   }
8598
8599   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8600
8601   SDLoc DL(Op);
8602   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8603
8604   // With PIC, the address is actually $g + Offset.
8605   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8606       !Subtarget->is64Bit()) {
8607     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8608                          DAG.getNode(X86ISD::GlobalBaseReg,
8609                                      SDLoc(), getPointerTy()),
8610                          Result);
8611   }
8612
8613   // For symbols that require a load from a stub to get the address, emit the
8614   // load.
8615   if (isGlobalStubReference(OpFlag))
8616     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8617                          MachinePointerInfo::getGOT(), false, false, false, 0);
8618
8619   return Result;
8620 }
8621
8622 SDValue
8623 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8624   // Create the TargetBlockAddressAddress node.
8625   unsigned char OpFlags =
8626     Subtarget->ClassifyBlockAddressReference();
8627   CodeModel::Model M = getTargetMachine().getCodeModel();
8628   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8629   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8630   SDLoc dl(Op);
8631   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8632                                              OpFlags);
8633
8634   if (Subtarget->isPICStyleRIPRel() &&
8635       (M == CodeModel::Small || M == CodeModel::Kernel))
8636     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8637   else
8638     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8639
8640   // With PIC, the address is actually $g + Offset.
8641   if (isGlobalRelativeToPICBase(OpFlags)) {
8642     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8643                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8644                          Result);
8645   }
8646
8647   return Result;
8648 }
8649
8650 SDValue
8651 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8652                                       int64_t Offset, SelectionDAG &DAG) const {
8653   // Create the TargetGlobalAddress node, folding in the constant
8654   // offset if it is legal.
8655   unsigned char OpFlags =
8656     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8657   CodeModel::Model M = getTargetMachine().getCodeModel();
8658   SDValue Result;
8659   if (OpFlags == X86II::MO_NO_FLAG &&
8660       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8661     // A direct static reference to a global.
8662     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8663     Offset = 0;
8664   } else {
8665     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8666   }
8667
8668   if (Subtarget->isPICStyleRIPRel() &&
8669       (M == CodeModel::Small || M == CodeModel::Kernel))
8670     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8671   else
8672     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8673
8674   // With PIC, the address is actually $g + Offset.
8675   if (isGlobalRelativeToPICBase(OpFlags)) {
8676     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8677                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8678                          Result);
8679   }
8680
8681   // For globals that require a load from a stub to get the address, emit the
8682   // load.
8683   if (isGlobalStubReference(OpFlags))
8684     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8685                          MachinePointerInfo::getGOT(), false, false, false, 0);
8686
8687   // If there was a non-zero offset that we didn't fold, create an explicit
8688   // addition for it.
8689   if (Offset != 0)
8690     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8691                          DAG.getConstant(Offset, getPointerTy()));
8692
8693   return Result;
8694 }
8695
8696 SDValue
8697 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8698   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8699   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8700   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8701 }
8702
8703 static SDValue
8704 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8705            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8706            unsigned char OperandFlags, bool LocalDynamic = false) {
8707   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8708   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8709   SDLoc dl(GA);
8710   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8711                                            GA->getValueType(0),
8712                                            GA->getOffset(),
8713                                            OperandFlags);
8714
8715   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8716                                            : X86ISD::TLSADDR;
8717
8718   if (InFlag) {
8719     SDValue Ops[] = { Chain,  TGA, *InFlag };
8720     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8721   } else {
8722     SDValue Ops[]  = { Chain, TGA };
8723     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8724   }
8725
8726   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8727   MFI->setAdjustsStack(true);
8728
8729   SDValue Flag = Chain.getValue(1);
8730   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8731 }
8732
8733 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8734 static SDValue
8735 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8736                                 const EVT PtrVT) {
8737   SDValue InFlag;
8738   SDLoc dl(GA);  // ? function entry point might be better
8739   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8740                                    DAG.getNode(X86ISD::GlobalBaseReg,
8741                                                SDLoc(), PtrVT), InFlag);
8742   InFlag = Chain.getValue(1);
8743
8744   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8745 }
8746
8747 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8748 static SDValue
8749 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8750                                 const EVT PtrVT) {
8751   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8752                     X86::RAX, X86II::MO_TLSGD);
8753 }
8754
8755 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8756                                            SelectionDAG &DAG,
8757                                            const EVT PtrVT,
8758                                            bool is64Bit) {
8759   SDLoc dl(GA);
8760
8761   // Get the start address of the TLS block for this module.
8762   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8763       .getInfo<X86MachineFunctionInfo>();
8764   MFI->incNumLocalDynamicTLSAccesses();
8765
8766   SDValue Base;
8767   if (is64Bit) {
8768     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8769                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8770   } else {
8771     SDValue InFlag;
8772     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8773         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8774     InFlag = Chain.getValue(1);
8775     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8776                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8777   }
8778
8779   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8780   // of Base.
8781
8782   // Build x@dtpoff.
8783   unsigned char OperandFlags = X86II::MO_DTPOFF;
8784   unsigned WrapperKind = X86ISD::Wrapper;
8785   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8786                                            GA->getValueType(0),
8787                                            GA->getOffset(), OperandFlags);
8788   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8789
8790   // Add x@dtpoff with the base.
8791   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8792 }
8793
8794 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8795 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8796                                    const EVT PtrVT, TLSModel::Model model,
8797                                    bool is64Bit, bool isPIC) {
8798   SDLoc dl(GA);
8799
8800   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8801   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8802                                                          is64Bit ? 257 : 256));
8803
8804   SDValue ThreadPointer =
8805       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8806                   MachinePointerInfo(Ptr), false, false, false, 0);
8807
8808   unsigned char OperandFlags = 0;
8809   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8810   // initialexec.
8811   unsigned WrapperKind = X86ISD::Wrapper;
8812   if (model == TLSModel::LocalExec) {
8813     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8814   } else if (model == TLSModel::InitialExec) {
8815     if (is64Bit) {
8816       OperandFlags = X86II::MO_GOTTPOFF;
8817       WrapperKind = X86ISD::WrapperRIP;
8818     } else {
8819       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8820     }
8821   } else {
8822     llvm_unreachable("Unexpected model");
8823   }
8824
8825   // emit "addl x@ntpoff,%eax" (local exec)
8826   // or "addl x@indntpoff,%eax" (initial exec)
8827   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8828   SDValue TGA =
8829       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8830                                  GA->getOffset(), OperandFlags);
8831   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8832
8833   if (model == TLSModel::InitialExec) {
8834     if (isPIC && !is64Bit) {
8835       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8836                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8837                            Offset);
8838     }
8839
8840     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8841                          MachinePointerInfo::getGOT(), false, false, false, 0);
8842   }
8843
8844   // The address of the thread local variable is the add of the thread
8845   // pointer with the offset of the variable.
8846   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8847 }
8848
8849 SDValue
8850 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8851
8852   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8853   const GlobalValue *GV = GA->getGlobal();
8854
8855   if (Subtarget->isTargetELF()) {
8856     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8857
8858     switch (model) {
8859       case TLSModel::GeneralDynamic:
8860         if (Subtarget->is64Bit())
8861           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8862         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8863       case TLSModel::LocalDynamic:
8864         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8865                                            Subtarget->is64Bit());
8866       case TLSModel::InitialExec:
8867       case TLSModel::LocalExec:
8868         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8869                                    Subtarget->is64Bit(),
8870                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8871     }
8872     llvm_unreachable("Unknown TLS model.");
8873   }
8874
8875   if (Subtarget->isTargetDarwin()) {
8876     // Darwin only has one model of TLS.  Lower to that.
8877     unsigned char OpFlag = 0;
8878     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8879                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8880
8881     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8882     // global base reg.
8883     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8884                   !Subtarget->is64Bit();
8885     if (PIC32)
8886       OpFlag = X86II::MO_TLVP_PIC_BASE;
8887     else
8888       OpFlag = X86II::MO_TLVP;
8889     SDLoc DL(Op);
8890     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8891                                                 GA->getValueType(0),
8892                                                 GA->getOffset(), OpFlag);
8893     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8894
8895     // With PIC32, the address is actually $g + Offset.
8896     if (PIC32)
8897       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8898                            DAG.getNode(X86ISD::GlobalBaseReg,
8899                                        SDLoc(), getPointerTy()),
8900                            Offset);
8901
8902     // Lowering the machine isd will make sure everything is in the right
8903     // location.
8904     SDValue Chain = DAG.getEntryNode();
8905     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8906     SDValue Args[] = { Chain, Offset };
8907     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8908
8909     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8910     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8911     MFI->setAdjustsStack(true);
8912
8913     // And our return value (tls address) is in the standard call return value
8914     // location.
8915     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8916     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8917                               Chain.getValue(1));
8918   }
8919
8920   if (Subtarget->isTargetKnownWindowsMSVC() ||
8921       Subtarget->isTargetWindowsGNU()) {
8922     // Just use the implicit TLS architecture
8923     // Need to generate someting similar to:
8924     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8925     //                                  ; from TEB
8926     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8927     //   mov     rcx, qword [rdx+rcx*8]
8928     //   mov     eax, .tls$:tlsvar
8929     //   [rax+rcx] contains the address
8930     // Windows 64bit: gs:0x58
8931     // Windows 32bit: fs:__tls_array
8932
8933     // If GV is an alias then use the aliasee for determining
8934     // thread-localness.
8935     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8936       GV = GA->getAliasee();
8937     SDLoc dl(GA);
8938     SDValue Chain = DAG.getEntryNode();
8939
8940     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8941     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8942     // use its literal value of 0x2C.
8943     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8944                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8945                                                              256)
8946                                         : Type::getInt32PtrTy(*DAG.getContext(),
8947                                                               257));
8948
8949     SDValue TlsArray =
8950         Subtarget->is64Bit()
8951             ? DAG.getIntPtrConstant(0x58)
8952             : (Subtarget->isTargetWindowsGNU()
8953                    ? DAG.getIntPtrConstant(0x2C)
8954                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8955
8956     SDValue ThreadPointer =
8957         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8958                     MachinePointerInfo(Ptr), false, false, false, 0);
8959
8960     // Load the _tls_index variable
8961     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8962     if (Subtarget->is64Bit())
8963       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8964                            IDX, MachinePointerInfo(), MVT::i32,
8965                            false, false, 0);
8966     else
8967       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8968                         false, false, false, 0);
8969
8970     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8971                                     getPointerTy());
8972     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8973
8974     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8975     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8976                       false, false, false, 0);
8977
8978     // Get the offset of start of .tls section
8979     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8980                                              GA->getValueType(0),
8981                                              GA->getOffset(), X86II::MO_SECREL);
8982     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8983
8984     // The address of the thread local variable is the add of the thread
8985     // pointer with the offset of the variable.
8986     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8987   }
8988
8989   llvm_unreachable("TLS not implemented for this target.");
8990 }
8991
8992 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8993 /// and take a 2 x i32 value to shift plus a shift amount.
8994 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8995   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8996   MVT VT = Op.getSimpleValueType();
8997   unsigned VTBits = VT.getSizeInBits();
8998   SDLoc dl(Op);
8999   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9000   SDValue ShOpLo = Op.getOperand(0);
9001   SDValue ShOpHi = Op.getOperand(1);
9002   SDValue ShAmt  = Op.getOperand(2);
9003   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9004   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9005   // during isel.
9006   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9007                                   DAG.getConstant(VTBits - 1, MVT::i8));
9008   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9009                                      DAG.getConstant(VTBits - 1, MVT::i8))
9010                        : DAG.getConstant(0, VT);
9011
9012   SDValue Tmp2, Tmp3;
9013   if (Op.getOpcode() == ISD::SHL_PARTS) {
9014     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9015     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9016   } else {
9017     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9018     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9019   }
9020
9021   // If the shift amount is larger or equal than the width of a part we can't
9022   // rely on the results of shld/shrd. Insert a test and select the appropriate
9023   // values for large shift amounts.
9024   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9025                                 DAG.getConstant(VTBits, MVT::i8));
9026   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9027                              AndNode, DAG.getConstant(0, MVT::i8));
9028
9029   SDValue Hi, Lo;
9030   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9031   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9032   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9033
9034   if (Op.getOpcode() == ISD::SHL_PARTS) {
9035     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9036     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9037   } else {
9038     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9039     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9040   }
9041
9042   SDValue Ops[2] = { Lo, Hi };
9043   return DAG.getMergeValues(Ops, dl);
9044 }
9045
9046 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9047                                            SelectionDAG &DAG) const {
9048   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9049
9050   if (SrcVT.isVector())
9051     return SDValue();
9052
9053   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9054          "Unknown SINT_TO_FP to lower!");
9055
9056   // These are really Legal; return the operand so the caller accepts it as
9057   // Legal.
9058   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9059     return Op;
9060   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9061       Subtarget->is64Bit()) {
9062     return Op;
9063   }
9064
9065   SDLoc dl(Op);
9066   unsigned Size = SrcVT.getSizeInBits()/8;
9067   MachineFunction &MF = DAG.getMachineFunction();
9068   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9069   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9070   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9071                                StackSlot,
9072                                MachinePointerInfo::getFixedStack(SSFI),
9073                                false, false, 0);
9074   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9075 }
9076
9077 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9078                                      SDValue StackSlot,
9079                                      SelectionDAG &DAG) const {
9080   // Build the FILD
9081   SDLoc DL(Op);
9082   SDVTList Tys;
9083   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9084   if (useSSE)
9085     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9086   else
9087     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9088
9089   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9090
9091   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9092   MachineMemOperand *MMO;
9093   if (FI) {
9094     int SSFI = FI->getIndex();
9095     MMO =
9096       DAG.getMachineFunction()
9097       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9099   } else {
9100     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9101     StackSlot = StackSlot.getOperand(1);
9102   }
9103   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9104   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9105                                            X86ISD::FILD, DL,
9106                                            Tys, Ops, SrcVT, MMO);
9107
9108   if (useSSE) {
9109     Chain = Result.getValue(1);
9110     SDValue InFlag = Result.getValue(2);
9111
9112     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9113     // shouldn't be necessary except that RFP cannot be live across
9114     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9115     MachineFunction &MF = DAG.getMachineFunction();
9116     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9117     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9118     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9119     Tys = DAG.getVTList(MVT::Other);
9120     SDValue Ops[] = {
9121       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9122     };
9123     MachineMemOperand *MMO =
9124       DAG.getMachineFunction()
9125       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9126                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9127
9128     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9129                                     Ops, Op.getValueType(), MMO);
9130     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9131                          MachinePointerInfo::getFixedStack(SSFI),
9132                          false, false, false, 0);
9133   }
9134
9135   return Result;
9136 }
9137
9138 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9139 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9140                                                SelectionDAG &DAG) const {
9141   // This algorithm is not obvious. Here it is what we're trying to output:
9142   /*
9143      movq       %rax,  %xmm0
9144      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9145      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9146      #ifdef __SSE3__
9147        haddpd   %xmm0, %xmm0
9148      #else
9149        pshufd   $0x4e, %xmm0, %xmm1
9150        addpd    %xmm1, %xmm0
9151      #endif
9152   */
9153
9154   SDLoc dl(Op);
9155   LLVMContext *Context = DAG.getContext();
9156
9157   // Build some magic constants.
9158   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9159   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9160   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9161
9162   SmallVector<Constant*,2> CV1;
9163   CV1.push_back(
9164     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9165                                       APInt(64, 0x4330000000000000ULL))));
9166   CV1.push_back(
9167     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9168                                       APInt(64, 0x4530000000000000ULL))));
9169   Constant *C1 = ConstantVector::get(CV1);
9170   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9171
9172   // Load the 64-bit value into an XMM register.
9173   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9174                             Op.getOperand(0));
9175   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9176                               MachinePointerInfo::getConstantPool(),
9177                               false, false, false, 16);
9178   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9179                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9180                               CLod0);
9181
9182   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9183                               MachinePointerInfo::getConstantPool(),
9184                               false, false, false, 16);
9185   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9186   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9187   SDValue Result;
9188
9189   if (Subtarget->hasSSE3()) {
9190     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9191     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9192   } else {
9193     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9194     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9195                                            S2F, 0x4E, DAG);
9196     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9197                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9198                          Sub);
9199   }
9200
9201   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9202                      DAG.getIntPtrConstant(0));
9203 }
9204
9205 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9206 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9207                                                SelectionDAG &DAG) const {
9208   SDLoc dl(Op);
9209   // FP constant to bias correct the final result.
9210   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9211                                    MVT::f64);
9212
9213   // Load the 32-bit value into an XMM register.
9214   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9215                              Op.getOperand(0));
9216
9217   // Zero out the upper parts of the register.
9218   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9219
9220   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9221                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9222                      DAG.getIntPtrConstant(0));
9223
9224   // Or the load with the bias.
9225   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9226                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9227                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9228                                                    MVT::v2f64, Load)),
9229                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9230                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9231                                                    MVT::v2f64, Bias)));
9232   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9233                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9234                    DAG.getIntPtrConstant(0));
9235
9236   // Subtract the bias.
9237   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9238
9239   // Handle final rounding.
9240   EVT DestVT = Op.getValueType();
9241
9242   if (DestVT.bitsLT(MVT::f64))
9243     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9244                        DAG.getIntPtrConstant(0));
9245   if (DestVT.bitsGT(MVT::f64))
9246     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9247
9248   // Handle final rounding.
9249   return Sub;
9250 }
9251
9252 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9253                                                SelectionDAG &DAG) const {
9254   SDValue N0 = Op.getOperand(0);
9255   MVT SVT = N0.getSimpleValueType();
9256   SDLoc dl(Op);
9257
9258   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9259           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9260          "Custom UINT_TO_FP is not supported!");
9261
9262   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9263   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9264                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9265 }
9266
9267 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9268                                            SelectionDAG &DAG) const {
9269   SDValue N0 = Op.getOperand(0);
9270   SDLoc dl(Op);
9271
9272   if (Op.getValueType().isVector())
9273     return lowerUINT_TO_FP_vec(Op, DAG);
9274
9275   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9276   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9277   // the optimization here.
9278   if (DAG.SignBitIsZero(N0))
9279     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9280
9281   MVT SrcVT = N0.getSimpleValueType();
9282   MVT DstVT = Op.getSimpleValueType();
9283   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9284     return LowerUINT_TO_FP_i64(Op, DAG);
9285   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9286     return LowerUINT_TO_FP_i32(Op, DAG);
9287   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9288     return SDValue();
9289
9290   // Make a 64-bit buffer, and use it to build an FILD.
9291   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9292   if (SrcVT == MVT::i32) {
9293     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9294     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9295                                      getPointerTy(), StackSlot, WordOff);
9296     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9297                                   StackSlot, MachinePointerInfo(),
9298                                   false, false, 0);
9299     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9300                                   OffsetSlot, MachinePointerInfo(),
9301                                   false, false, 0);
9302     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9303     return Fild;
9304   }
9305
9306   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9307   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9308                                StackSlot, MachinePointerInfo(),
9309                                false, false, 0);
9310   // For i64 source, we need to add the appropriate power of 2 if the input
9311   // was negative.  This is the same as the optimization in
9312   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9313   // we must be careful to do the computation in x87 extended precision, not
9314   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9315   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9316   MachineMemOperand *MMO =
9317     DAG.getMachineFunction()
9318     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9319                           MachineMemOperand::MOLoad, 8, 8);
9320
9321   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9322   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9323   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9324                                          MVT::i64, MMO);
9325
9326   APInt FF(32, 0x5F800000ULL);
9327
9328   // Check whether the sign bit is set.
9329   SDValue SignSet = DAG.getSetCC(dl,
9330                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9331                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9332                                  ISD::SETLT);
9333
9334   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9335   SDValue FudgePtr = DAG.getConstantPool(
9336                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9337                                          getPointerTy());
9338
9339   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9340   SDValue Zero = DAG.getIntPtrConstant(0);
9341   SDValue Four = DAG.getIntPtrConstant(4);
9342   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9343                                Zero, Four);
9344   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9345
9346   // Load the value out, extending it from f32 to f80.
9347   // FIXME: Avoid the extend by constructing the right constant pool?
9348   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9349                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9350                                  MVT::f32, false, false, 4);
9351   // Extend everything to 80 bits to force it to be done on x87.
9352   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9353   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9354 }
9355
9356 std::pair<SDValue,SDValue>
9357 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9358                                     bool IsSigned, bool IsReplace) const {
9359   SDLoc DL(Op);
9360
9361   EVT DstTy = Op.getValueType();
9362
9363   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9364     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9365     DstTy = MVT::i64;
9366   }
9367
9368   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9369          DstTy.getSimpleVT() >= MVT::i16 &&
9370          "Unknown FP_TO_INT to lower!");
9371
9372   // These are really Legal.
9373   if (DstTy == MVT::i32 &&
9374       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9375     return std::make_pair(SDValue(), SDValue());
9376   if (Subtarget->is64Bit() &&
9377       DstTy == MVT::i64 &&
9378       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9379     return std::make_pair(SDValue(), SDValue());
9380
9381   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9382   // stack slot, or into the FTOL runtime function.
9383   MachineFunction &MF = DAG.getMachineFunction();
9384   unsigned MemSize = DstTy.getSizeInBits()/8;
9385   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9386   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9387
9388   unsigned Opc;
9389   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9390     Opc = X86ISD::WIN_FTOL;
9391   else
9392     switch (DstTy.getSimpleVT().SimpleTy) {
9393     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9394     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9395     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9396     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9397     }
9398
9399   SDValue Chain = DAG.getEntryNode();
9400   SDValue Value = Op.getOperand(0);
9401   EVT TheVT = Op.getOperand(0).getValueType();
9402   // FIXME This causes a redundant load/store if the SSE-class value is already
9403   // in memory, such as if it is on the callstack.
9404   if (isScalarFPTypeInSSEReg(TheVT)) {
9405     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9406     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9407                          MachinePointerInfo::getFixedStack(SSFI),
9408                          false, false, 0);
9409     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9410     SDValue Ops[] = {
9411       Chain, StackSlot, DAG.getValueType(TheVT)
9412     };
9413
9414     MachineMemOperand *MMO =
9415       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9416                               MachineMemOperand::MOLoad, MemSize, MemSize);
9417     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9418     Chain = Value.getValue(1);
9419     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9420     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9421   }
9422
9423   MachineMemOperand *MMO =
9424     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9425                             MachineMemOperand::MOStore, MemSize, MemSize);
9426
9427   if (Opc != X86ISD::WIN_FTOL) {
9428     // Build the FP_TO_INT*_IN_MEM
9429     SDValue Ops[] = { Chain, Value, StackSlot };
9430     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9431                                            Ops, DstTy, MMO);
9432     return std::make_pair(FIST, StackSlot);
9433   } else {
9434     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9435       DAG.getVTList(MVT::Other, MVT::Glue),
9436       Chain, Value);
9437     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9438       MVT::i32, ftol.getValue(1));
9439     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9440       MVT::i32, eax.getValue(2));
9441     SDValue Ops[] = { eax, edx };
9442     SDValue pair = IsReplace
9443       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9444       : DAG.getMergeValues(Ops, DL);
9445     return std::make_pair(pair, SDValue());
9446   }
9447 }
9448
9449 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9450                               const X86Subtarget *Subtarget) {
9451   MVT VT = Op->getSimpleValueType(0);
9452   SDValue In = Op->getOperand(0);
9453   MVT InVT = In.getSimpleValueType();
9454   SDLoc dl(Op);
9455
9456   // Optimize vectors in AVX mode:
9457   //
9458   //   v8i16 -> v8i32
9459   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9460   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9461   //   Concat upper and lower parts.
9462   //
9463   //   v4i32 -> v4i64
9464   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9465   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9466   //   Concat upper and lower parts.
9467   //
9468
9469   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9470       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9471       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9472     return SDValue();
9473
9474   if (Subtarget->hasInt256())
9475     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9476
9477   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9478   SDValue Undef = DAG.getUNDEF(InVT);
9479   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9480   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9481   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9482
9483   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9484                              VT.getVectorNumElements()/2);
9485
9486   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9487   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9488
9489   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9490 }
9491
9492 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9493                                         SelectionDAG &DAG) {
9494   MVT VT = Op->getSimpleValueType(0);
9495   SDValue In = Op->getOperand(0);
9496   MVT InVT = In.getSimpleValueType();
9497   SDLoc DL(Op);
9498   unsigned int NumElts = VT.getVectorNumElements();
9499   if (NumElts != 8 && NumElts != 16)
9500     return SDValue();
9501
9502   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9503     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9504
9505   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9507   // Now we have only mask extension
9508   assert(InVT.getVectorElementType() == MVT::i1);
9509   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9510   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9511   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9512   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9513   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9514                            MachinePointerInfo::getConstantPool(),
9515                            false, false, false, Alignment);
9516
9517   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9518   if (VT.is512BitVector())
9519     return Brcst;
9520   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9521 }
9522
9523 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9524                                SelectionDAG &DAG) {
9525   if (Subtarget->hasFp256()) {
9526     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9527     if (Res.getNode())
9528       return Res;
9529   }
9530
9531   return SDValue();
9532 }
9533
9534 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9535                                 SelectionDAG &DAG) {
9536   SDLoc DL(Op);
9537   MVT VT = Op.getSimpleValueType();
9538   SDValue In = Op.getOperand(0);
9539   MVT SVT = In.getSimpleValueType();
9540
9541   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9542     return LowerZERO_EXTEND_AVX512(Op, DAG);
9543
9544   if (Subtarget->hasFp256()) {
9545     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9546     if (Res.getNode())
9547       return Res;
9548   }
9549
9550   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9551          VT.getVectorNumElements() != SVT.getVectorNumElements());
9552   return SDValue();
9553 }
9554
9555 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9556   SDLoc DL(Op);
9557   MVT VT = Op.getSimpleValueType();
9558   SDValue In = Op.getOperand(0);
9559   MVT InVT = In.getSimpleValueType();
9560
9561   if (VT == MVT::i1) {
9562     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9563            "Invalid scalar TRUNCATE operation");
9564     if (InVT == MVT::i32)
9565       return SDValue();
9566     if (InVT.getSizeInBits() == 64)
9567       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9568     else if (InVT.getSizeInBits() < 32)
9569       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9570     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9571   }
9572   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9573          "Invalid TRUNCATE operation");
9574
9575   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9576     if (VT.getVectorElementType().getSizeInBits() >=8)
9577       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9578
9579     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9580     unsigned NumElts = InVT.getVectorNumElements();
9581     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9582     if (InVT.getSizeInBits() < 512) {
9583       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9584       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9585       InVT = ExtVT;
9586     }
9587     
9588     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9589     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9590     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9591     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9592     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9593                            MachinePointerInfo::getConstantPool(),
9594                            false, false, false, Alignment);
9595     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9596     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9597     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9598   }
9599
9600   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9601     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9602     if (Subtarget->hasInt256()) {
9603       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9604       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9605       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9606                                 ShufMask);
9607       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9608                          DAG.getIntPtrConstant(0));
9609     }
9610
9611     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9612                                DAG.getIntPtrConstant(0));
9613     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9614                                DAG.getIntPtrConstant(2));
9615     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9616     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9617     static const int ShufMask[] = {0, 2, 4, 6};
9618     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9619   }
9620
9621   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9622     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9623     if (Subtarget->hasInt256()) {
9624       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9625
9626       SmallVector<SDValue,32> pshufbMask;
9627       for (unsigned i = 0; i < 2; ++i) {
9628         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9629         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9630         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9631         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9632         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9633         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9634         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9635         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9636         for (unsigned j = 0; j < 8; ++j)
9637           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9638       }
9639       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9640       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9641       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9642
9643       static const int ShufMask[] = {0,  2,  -1,  -1};
9644       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9645                                 &ShufMask[0]);
9646       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9647                        DAG.getIntPtrConstant(0));
9648       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9649     }
9650
9651     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9652                                DAG.getIntPtrConstant(0));
9653
9654     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9655                                DAG.getIntPtrConstant(4));
9656
9657     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9658     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9659
9660     // The PSHUFB mask:
9661     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9662                                    -1, -1, -1, -1, -1, -1, -1, -1};
9663
9664     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9665     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9666     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9667
9668     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9669     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9670
9671     // The MOVLHPS Mask:
9672     static const int ShufMask2[] = {0, 1, 4, 5};
9673     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9674     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9675   }
9676
9677   // Handle truncation of V256 to V128 using shuffles.
9678   if (!VT.is128BitVector() || !InVT.is256BitVector())
9679     return SDValue();
9680
9681   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9682
9683   unsigned NumElems = VT.getVectorNumElements();
9684   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9685
9686   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9687   // Prepare truncation shuffle mask
9688   for (unsigned i = 0; i != NumElems; ++i)
9689     MaskVec[i] = i * 2;
9690   SDValue V = DAG.getVectorShuffle(NVT, DL,
9691                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9692                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9693   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9694                      DAG.getIntPtrConstant(0));
9695 }
9696
9697 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9698                                            SelectionDAG &DAG) const {
9699   assert(!Op.getSimpleValueType().isVector());
9700
9701   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9702     /*IsSigned=*/ true, /*IsReplace=*/ false);
9703   SDValue FIST = Vals.first, StackSlot = Vals.second;
9704   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9705   if (!FIST.getNode()) return Op;
9706
9707   if (StackSlot.getNode())
9708     // Load the result.
9709     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9710                        FIST, StackSlot, MachinePointerInfo(),
9711                        false, false, false, 0);
9712
9713   // The node is the result.
9714   return FIST;
9715 }
9716
9717 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9718                                            SelectionDAG &DAG) const {
9719   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9720     /*IsSigned=*/ false, /*IsReplace=*/ false);
9721   SDValue FIST = Vals.first, StackSlot = Vals.second;
9722   assert(FIST.getNode() && "Unexpected failure");
9723
9724   if (StackSlot.getNode())
9725     // Load the result.
9726     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9727                        FIST, StackSlot, MachinePointerInfo(),
9728                        false, false, false, 0);
9729
9730   // The node is the result.
9731   return FIST;
9732 }
9733
9734 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9735   SDLoc DL(Op);
9736   MVT VT = Op.getSimpleValueType();
9737   SDValue In = Op.getOperand(0);
9738   MVT SVT = In.getSimpleValueType();
9739
9740   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9741
9742   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9743                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9744                                  In, DAG.getUNDEF(SVT)));
9745 }
9746
9747 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9748   LLVMContext *Context = DAG.getContext();
9749   SDLoc dl(Op);
9750   MVT VT = Op.getSimpleValueType();
9751   MVT EltVT = VT;
9752   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9753   if (VT.isVector()) {
9754     EltVT = VT.getVectorElementType();
9755     NumElts = VT.getVectorNumElements();
9756   }
9757   Constant *C;
9758   if (EltVT == MVT::f64)
9759     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9760                                           APInt(64, ~(1ULL << 63))));
9761   else
9762     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9763                                           APInt(32, ~(1U << 31))));
9764   C = ConstantVector::getSplat(NumElts, C);
9765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9766   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9767   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9768   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9769                              MachinePointerInfo::getConstantPool(),
9770                              false, false, false, Alignment);
9771   if (VT.isVector()) {
9772     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9773     return DAG.getNode(ISD::BITCAST, dl, VT,
9774                        DAG.getNode(ISD::AND, dl, ANDVT,
9775                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9776                                                Op.getOperand(0)),
9777                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9778   }
9779   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9780 }
9781
9782 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9783   LLVMContext *Context = DAG.getContext();
9784   SDLoc dl(Op);
9785   MVT VT = Op.getSimpleValueType();
9786   MVT EltVT = VT;
9787   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9788   if (VT.isVector()) {
9789     EltVT = VT.getVectorElementType();
9790     NumElts = VT.getVectorNumElements();
9791   }
9792   Constant *C;
9793   if (EltVT == MVT::f64)
9794     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9795                                           APInt(64, 1ULL << 63)));
9796   else
9797     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9798                                           APInt(32, 1U << 31)));
9799   C = ConstantVector::getSplat(NumElts, C);
9800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9801   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9802   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9803   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9804                              MachinePointerInfo::getConstantPool(),
9805                              false, false, false, Alignment);
9806   if (VT.isVector()) {
9807     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9808     return DAG.getNode(ISD::BITCAST, dl, VT,
9809                        DAG.getNode(ISD::XOR, dl, XORVT,
9810                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9811                                                Op.getOperand(0)),
9812                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9813   }
9814
9815   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9816 }
9817
9818 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9820   LLVMContext *Context = DAG.getContext();
9821   SDValue Op0 = Op.getOperand(0);
9822   SDValue Op1 = Op.getOperand(1);
9823   SDLoc dl(Op);
9824   MVT VT = Op.getSimpleValueType();
9825   MVT SrcVT = Op1.getSimpleValueType();
9826
9827   // If second operand is smaller, extend it first.
9828   if (SrcVT.bitsLT(VT)) {
9829     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9830     SrcVT = VT;
9831   }
9832   // And if it is bigger, shrink it first.
9833   if (SrcVT.bitsGT(VT)) {
9834     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9835     SrcVT = VT;
9836   }
9837
9838   // At this point the operands and the result should have the same
9839   // type, and that won't be f80 since that is not custom lowered.
9840
9841   // First get the sign bit of second operand.
9842   SmallVector<Constant*,4> CV;
9843   if (SrcVT == MVT::f64) {
9844     const fltSemantics &Sem = APFloat::IEEEdouble;
9845     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9846     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9847   } else {
9848     const fltSemantics &Sem = APFloat::IEEEsingle;
9849     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9850     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9851     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9852     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9853   }
9854   Constant *C = ConstantVector::get(CV);
9855   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9856   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9857                               MachinePointerInfo::getConstantPool(),
9858                               false, false, false, 16);
9859   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9860
9861   // Shift sign bit right or left if the two operands have different types.
9862   if (SrcVT.bitsGT(VT)) {
9863     // Op0 is MVT::f32, Op1 is MVT::f64.
9864     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9865     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9866                           DAG.getConstant(32, MVT::i32));
9867     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9868     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9869                           DAG.getIntPtrConstant(0));
9870   }
9871
9872   // Clear first operand sign bit.
9873   CV.clear();
9874   if (VT == MVT::f64) {
9875     const fltSemantics &Sem = APFloat::IEEEdouble;
9876     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9877                                                    APInt(64, ~(1ULL << 63)))));
9878     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9879   } else {
9880     const fltSemantics &Sem = APFloat::IEEEsingle;
9881     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9882                                                    APInt(32, ~(1U << 31)))));
9883     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9884     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9885     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9886   }
9887   C = ConstantVector::get(CV);
9888   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9889   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9890                               MachinePointerInfo::getConstantPool(),
9891                               false, false, false, 16);
9892   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9893
9894   // Or the value with the sign bit.
9895   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9896 }
9897
9898 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9899   SDValue N0 = Op.getOperand(0);
9900   SDLoc dl(Op);
9901   MVT VT = Op.getSimpleValueType();
9902
9903   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9904   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9905                                   DAG.getConstant(1, VT));
9906   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9907 }
9908
9909 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9910 //
9911 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9912                                       SelectionDAG &DAG) {
9913   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9914
9915   if (!Subtarget->hasSSE41())
9916     return SDValue();
9917
9918   if (!Op->hasOneUse())
9919     return SDValue();
9920
9921   SDNode *N = Op.getNode();
9922   SDLoc DL(N);
9923
9924   SmallVector<SDValue, 8> Opnds;
9925   DenseMap<SDValue, unsigned> VecInMap;
9926   SmallVector<SDValue, 8> VecIns;
9927   EVT VT = MVT::Other;
9928
9929   // Recognize a special case where a vector is casted into wide integer to
9930   // test all 0s.
9931   Opnds.push_back(N->getOperand(0));
9932   Opnds.push_back(N->getOperand(1));
9933
9934   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9935     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9936     // BFS traverse all OR'd operands.
9937     if (I->getOpcode() == ISD::OR) {
9938       Opnds.push_back(I->getOperand(0));
9939       Opnds.push_back(I->getOperand(1));
9940       // Re-evaluate the number of nodes to be traversed.
9941       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9942       continue;
9943     }
9944
9945     // Quit if a non-EXTRACT_VECTOR_ELT
9946     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9947       return SDValue();
9948
9949     // Quit if without a constant index.
9950     SDValue Idx = I->getOperand(1);
9951     if (!isa<ConstantSDNode>(Idx))
9952       return SDValue();
9953
9954     SDValue ExtractedFromVec = I->getOperand(0);
9955     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9956     if (M == VecInMap.end()) {
9957       VT = ExtractedFromVec.getValueType();
9958       // Quit if not 128/256-bit vector.
9959       if (!VT.is128BitVector() && !VT.is256BitVector())
9960         return SDValue();
9961       // Quit if not the same type.
9962       if (VecInMap.begin() != VecInMap.end() &&
9963           VT != VecInMap.begin()->first.getValueType())
9964         return SDValue();
9965       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9966       VecIns.push_back(ExtractedFromVec);
9967     }
9968     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9969   }
9970
9971   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9972          "Not extracted from 128-/256-bit vector.");
9973
9974   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9975
9976   for (DenseMap<SDValue, unsigned>::const_iterator
9977         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9978     // Quit if not all elements are used.
9979     if (I->second != FullMask)
9980       return SDValue();
9981   }
9982
9983   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9984
9985   // Cast all vectors into TestVT for PTEST.
9986   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9987     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9988
9989   // If more than one full vectors are evaluated, OR them first before PTEST.
9990   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9991     // Each iteration will OR 2 nodes and append the result until there is only
9992     // 1 node left, i.e. the final OR'd value of all vectors.
9993     SDValue LHS = VecIns[Slot];
9994     SDValue RHS = VecIns[Slot + 1];
9995     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9996   }
9997
9998   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9999                      VecIns.back(), VecIns.back());
10000 }
10001
10002 /// \brief return true if \c Op has a use that doesn't just read flags.
10003 static bool hasNonFlagsUse(SDValue Op) {
10004   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10005        ++UI) {
10006     SDNode *User = *UI;
10007     unsigned UOpNo = UI.getOperandNo();
10008     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10009       // Look pass truncate.
10010       UOpNo = User->use_begin().getOperandNo();
10011       User = *User->use_begin();
10012     }
10013
10014     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10015         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10016       return true;
10017   }
10018   return false;
10019 }
10020
10021 /// Emit nodes that will be selected as "test Op0,Op0", or something
10022 /// equivalent.
10023 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10024                                     SelectionDAG &DAG) const {
10025   if (Op.getValueType() == MVT::i1)
10026     // KORTEST instruction should be selected
10027     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10028                        DAG.getConstant(0, Op.getValueType()));
10029
10030   // CF and OF aren't always set the way we want. Determine which
10031   // of these we need.
10032   bool NeedCF = false;
10033   bool NeedOF = false;
10034   switch (X86CC) {
10035   default: break;
10036   case X86::COND_A: case X86::COND_AE:
10037   case X86::COND_B: case X86::COND_BE:
10038     NeedCF = true;
10039     break;
10040   case X86::COND_G: case X86::COND_GE:
10041   case X86::COND_L: case X86::COND_LE:
10042   case X86::COND_O: case X86::COND_NO:
10043     NeedOF = true;
10044     break;
10045   }
10046   // See if we can use the EFLAGS value from the operand instead of
10047   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10048   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10049   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10050     // Emit a CMP with 0, which is the TEST pattern.
10051     //if (Op.getValueType() == MVT::i1)
10052     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10053     //                     DAG.getConstant(0, MVT::i1));
10054     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10055                        DAG.getConstant(0, Op.getValueType()));
10056   }
10057   unsigned Opcode = 0;
10058   unsigned NumOperands = 0;
10059
10060   // Truncate operations may prevent the merge of the SETCC instruction
10061   // and the arithmetic instruction before it. Attempt to truncate the operands
10062   // of the arithmetic instruction and use a reduced bit-width instruction.
10063   bool NeedTruncation = false;
10064   SDValue ArithOp = Op;
10065   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10066     SDValue Arith = Op->getOperand(0);
10067     // Both the trunc and the arithmetic op need to have one user each.
10068     if (Arith->hasOneUse())
10069       switch (Arith.getOpcode()) {
10070         default: break;
10071         case ISD::ADD:
10072         case ISD::SUB:
10073         case ISD::AND:
10074         case ISD::OR:
10075         case ISD::XOR: {
10076           NeedTruncation = true;
10077           ArithOp = Arith;
10078         }
10079       }
10080   }
10081
10082   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10083   // which may be the result of a CAST.  We use the variable 'Op', which is the
10084   // non-casted variable when we check for possible users.
10085   switch (ArithOp.getOpcode()) {
10086   case ISD::ADD:
10087     // Due to an isel shortcoming, be conservative if this add is likely to be
10088     // selected as part of a load-modify-store instruction. When the root node
10089     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10090     // uses of other nodes in the match, such as the ADD in this case. This
10091     // leads to the ADD being left around and reselected, with the result being
10092     // two adds in the output.  Alas, even if none our users are stores, that
10093     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10094     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10095     // climbing the DAG back to the root, and it doesn't seem to be worth the
10096     // effort.
10097     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10098          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10099       if (UI->getOpcode() != ISD::CopyToReg &&
10100           UI->getOpcode() != ISD::SETCC &&
10101           UI->getOpcode() != ISD::STORE)
10102         goto default_case;
10103
10104     if (ConstantSDNode *C =
10105         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10106       // An add of one will be selected as an INC.
10107       if (C->getAPIntValue() == 1) {
10108         Opcode = X86ISD::INC;
10109         NumOperands = 1;
10110         break;
10111       }
10112
10113       // An add of negative one (subtract of one) will be selected as a DEC.
10114       if (C->getAPIntValue().isAllOnesValue()) {
10115         Opcode = X86ISD::DEC;
10116         NumOperands = 1;
10117         break;
10118       }
10119     }
10120
10121     // Otherwise use a regular EFLAGS-setting add.
10122     Opcode = X86ISD::ADD;
10123     NumOperands = 2;
10124     break;
10125   case ISD::SHL:
10126   case ISD::SRL:
10127     // If we have a constant logical shift that's only used in a comparison
10128     // against zero turn it into an equivalent AND. This allows turning it into
10129     // a TEST instruction later.
10130     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10131         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10132       EVT VT = Op.getValueType();
10133       unsigned BitWidth = VT.getSizeInBits();
10134       unsigned ShAmt = Op->getConstantOperandVal(1);
10135       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10136         break;
10137       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10138                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10139                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10140       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10141         break;
10142       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10143                                 DAG.getConstant(Mask, VT));
10144       DAG.ReplaceAllUsesWith(Op, New);
10145       Op = New;
10146     }
10147     break;
10148
10149   case ISD::AND:
10150     // If the primary and result isn't used, don't bother using X86ISD::AND,
10151     // because a TEST instruction will be better.
10152     if (!hasNonFlagsUse(Op))
10153       break;
10154     // FALL THROUGH
10155   case ISD::SUB:
10156   case ISD::OR:
10157   case ISD::XOR:
10158     // Due to the ISEL shortcoming noted above, be conservative if this op is
10159     // likely to be selected as part of a load-modify-store instruction.
10160     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10161            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10162       if (UI->getOpcode() == ISD::STORE)
10163         goto default_case;
10164
10165     // Otherwise use a regular EFLAGS-setting instruction.
10166     switch (ArithOp.getOpcode()) {
10167     default: llvm_unreachable("unexpected operator!");
10168     case ISD::SUB: Opcode = X86ISD::SUB; break;
10169     case ISD::XOR: Opcode = X86ISD::XOR; break;
10170     case ISD::AND: Opcode = X86ISD::AND; break;
10171     case ISD::OR: {
10172       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10173         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10174         if (EFLAGS.getNode())
10175           return EFLAGS;
10176       }
10177       Opcode = X86ISD::OR;
10178       break;
10179     }
10180     }
10181
10182     NumOperands = 2;
10183     break;
10184   case X86ISD::ADD:
10185   case X86ISD::SUB:
10186   case X86ISD::INC:
10187   case X86ISD::DEC:
10188   case X86ISD::OR:
10189   case X86ISD::XOR:
10190   case X86ISD::AND:
10191     return SDValue(Op.getNode(), 1);
10192   default:
10193   default_case:
10194     break;
10195   }
10196
10197   // If we found that truncation is beneficial, perform the truncation and
10198   // update 'Op'.
10199   if (NeedTruncation) {
10200     EVT VT = Op.getValueType();
10201     SDValue WideVal = Op->getOperand(0);
10202     EVT WideVT = WideVal.getValueType();
10203     unsigned ConvertedOp = 0;
10204     // Use a target machine opcode to prevent further DAGCombine
10205     // optimizations that may separate the arithmetic operations
10206     // from the setcc node.
10207     switch (WideVal.getOpcode()) {
10208       default: break;
10209       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10210       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10211       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10212       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10213       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10214     }
10215
10216     if (ConvertedOp) {
10217       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10218       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10219         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10220         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10221         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10222       }
10223     }
10224   }
10225
10226   if (Opcode == 0)
10227     // Emit a CMP with 0, which is the TEST pattern.
10228     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10229                        DAG.getConstant(0, Op.getValueType()));
10230
10231   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10232   SmallVector<SDValue, 4> Ops;
10233   for (unsigned i = 0; i != NumOperands; ++i)
10234     Ops.push_back(Op.getOperand(i));
10235
10236   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10237   DAG.ReplaceAllUsesWith(Op, New);
10238   return SDValue(New.getNode(), 1);
10239 }
10240
10241 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10242 /// equivalent.
10243 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10244                                    SDLoc dl, SelectionDAG &DAG) const {
10245   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10246     if (C->getAPIntValue() == 0)
10247       return EmitTest(Op0, X86CC, dl, DAG);
10248
10249      if (Op0.getValueType() == MVT::i1)
10250        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10251   }
10252  
10253   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10254        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10255     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10256     // This avoids subregister aliasing issues. Keep the smaller reference 
10257     // if we're optimizing for size, however, as that'll allow better folding 
10258     // of memory operations.
10259     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10260         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10261              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10262         !Subtarget->isAtom()) {
10263       unsigned ExtendOp =
10264           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10265       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10266       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10267     }
10268     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10269     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10270     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10271                               Op0, Op1);
10272     return SDValue(Sub.getNode(), 1);
10273   }
10274   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10275 }
10276
10277 /// Convert a comparison if required by the subtarget.
10278 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10279                                                  SelectionDAG &DAG) const {
10280   // If the subtarget does not support the FUCOMI instruction, floating-point
10281   // comparisons have to be converted.
10282   if (Subtarget->hasCMov() ||
10283       Cmp.getOpcode() != X86ISD::CMP ||
10284       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10285       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10286     return Cmp;
10287
10288   // The instruction selector will select an FUCOM instruction instead of
10289   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10290   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10291   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10292   SDLoc dl(Cmp);
10293   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10294   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10295   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10296                             DAG.getConstant(8, MVT::i8));
10297   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10298   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10299 }
10300
10301 static bool isAllOnes(SDValue V) {
10302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10303   return C && C->isAllOnesValue();
10304 }
10305
10306 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10307 /// if it's possible.
10308 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10309                                      SDLoc dl, SelectionDAG &DAG) const {
10310   SDValue Op0 = And.getOperand(0);
10311   SDValue Op1 = And.getOperand(1);
10312   if (Op0.getOpcode() == ISD::TRUNCATE)
10313     Op0 = Op0.getOperand(0);
10314   if (Op1.getOpcode() == ISD::TRUNCATE)
10315     Op1 = Op1.getOperand(0);
10316
10317   SDValue LHS, RHS;
10318   if (Op1.getOpcode() == ISD::SHL)
10319     std::swap(Op0, Op1);
10320   if (Op0.getOpcode() == ISD::SHL) {
10321     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10322       if (And00C->getZExtValue() == 1) {
10323         // If we looked past a truncate, check that it's only truncating away
10324         // known zeros.
10325         unsigned BitWidth = Op0.getValueSizeInBits();
10326         unsigned AndBitWidth = And.getValueSizeInBits();
10327         if (BitWidth > AndBitWidth) {
10328           APInt Zeros, Ones;
10329           DAG.computeKnownBits(Op0, Zeros, Ones);
10330           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10331             return SDValue();
10332         }
10333         LHS = Op1;
10334         RHS = Op0.getOperand(1);
10335       }
10336   } else if (Op1.getOpcode() == ISD::Constant) {
10337     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10338     uint64_t AndRHSVal = AndRHS->getZExtValue();
10339     SDValue AndLHS = Op0;
10340
10341     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10342       LHS = AndLHS.getOperand(0);
10343       RHS = AndLHS.getOperand(1);
10344     }
10345
10346     // Use BT if the immediate can't be encoded in a TEST instruction.
10347     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10348       LHS = AndLHS;
10349       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10350     }
10351   }
10352
10353   if (LHS.getNode()) {
10354     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10355     // instruction.  Since the shift amount is in-range-or-undefined, we know
10356     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10357     // the encoding for the i16 version is larger than the i32 version.
10358     // Also promote i16 to i32 for performance / code size reason.
10359     if (LHS.getValueType() == MVT::i8 ||
10360         LHS.getValueType() == MVT::i16)
10361       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10362
10363     // If the operand types disagree, extend the shift amount to match.  Since
10364     // BT ignores high bits (like shifts) we can use anyextend.
10365     if (LHS.getValueType() != RHS.getValueType())
10366       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10367
10368     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10369     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10370     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10371                        DAG.getConstant(Cond, MVT::i8), BT);
10372   }
10373
10374   return SDValue();
10375 }
10376
10377 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10378 /// mask CMPs.
10379 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10380                               SDValue &Op1) {
10381   unsigned SSECC;
10382   bool Swap = false;
10383
10384   // SSE Condition code mapping:
10385   //  0 - EQ
10386   //  1 - LT
10387   //  2 - LE
10388   //  3 - UNORD
10389   //  4 - NEQ
10390   //  5 - NLT
10391   //  6 - NLE
10392   //  7 - ORD
10393   switch (SetCCOpcode) {
10394   default: llvm_unreachable("Unexpected SETCC condition");
10395   case ISD::SETOEQ:
10396   case ISD::SETEQ:  SSECC = 0; break;
10397   case ISD::SETOGT:
10398   case ISD::SETGT:  Swap = true; // Fallthrough
10399   case ISD::SETLT:
10400   case ISD::SETOLT: SSECC = 1; break;
10401   case ISD::SETOGE:
10402   case ISD::SETGE:  Swap = true; // Fallthrough
10403   case ISD::SETLE:
10404   case ISD::SETOLE: SSECC = 2; break;
10405   case ISD::SETUO:  SSECC = 3; break;
10406   case ISD::SETUNE:
10407   case ISD::SETNE:  SSECC = 4; break;
10408   case ISD::SETULE: Swap = true; // Fallthrough
10409   case ISD::SETUGE: SSECC = 5; break;
10410   case ISD::SETULT: Swap = true; // Fallthrough
10411   case ISD::SETUGT: SSECC = 6; break;
10412   case ISD::SETO:   SSECC = 7; break;
10413   case ISD::SETUEQ:
10414   case ISD::SETONE: SSECC = 8; break;
10415   }
10416   if (Swap)
10417     std::swap(Op0, Op1);
10418
10419   return SSECC;
10420 }
10421
10422 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10423 // ones, and then concatenate the result back.
10424 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10425   MVT VT = Op.getSimpleValueType();
10426
10427   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10428          "Unsupported value type for operation");
10429
10430   unsigned NumElems = VT.getVectorNumElements();
10431   SDLoc dl(Op);
10432   SDValue CC = Op.getOperand(2);
10433
10434   // Extract the LHS vectors
10435   SDValue LHS = Op.getOperand(0);
10436   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10437   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10438
10439   // Extract the RHS vectors
10440   SDValue RHS = Op.getOperand(1);
10441   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10442   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10443
10444   // Issue the operation on the smaller types and concatenate the result back
10445   MVT EltVT = VT.getVectorElementType();
10446   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10447   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10448                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10449                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10450 }
10451
10452 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10453                                      const X86Subtarget *Subtarget) {
10454   SDValue Op0 = Op.getOperand(0);
10455   SDValue Op1 = Op.getOperand(1);
10456   SDValue CC = Op.getOperand(2);
10457   MVT VT = Op.getSimpleValueType();
10458   SDLoc dl(Op);
10459
10460   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10461          Op.getValueType().getScalarType() == MVT::i1 &&
10462          "Cannot set masked compare for this operation");
10463
10464   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10465   unsigned  Opc = 0;
10466   bool Unsigned = false;
10467   bool Swap = false;
10468   unsigned SSECC;
10469   switch (SetCCOpcode) {
10470   default: llvm_unreachable("Unexpected SETCC condition");
10471   case ISD::SETNE:  SSECC = 4; break;
10472   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10473   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10474   case ISD::SETLT:  Swap = true; //fall-through
10475   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10476   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10477   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10478   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10479   case ISD::SETULE: Unsigned = true; //fall-through
10480   case ISD::SETLE:  SSECC = 2; break;
10481   }
10482
10483   if (Swap)
10484     std::swap(Op0, Op1);
10485   if (Opc)
10486     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10487   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10488   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10489                      DAG.getConstant(SSECC, MVT::i8));
10490 }
10491
10492 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10493 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10494 /// return an empty value.
10495 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10496 {
10497   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10498   if (!BV)
10499     return SDValue();
10500
10501   MVT VT = Op1.getSimpleValueType();
10502   MVT EVT = VT.getVectorElementType();
10503   unsigned n = VT.getVectorNumElements();
10504   SmallVector<SDValue, 8> ULTOp1;
10505
10506   for (unsigned i = 0; i < n; ++i) {
10507     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10508     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10509       return SDValue();
10510
10511     // Avoid underflow.
10512     APInt Val = Elt->getAPIntValue();
10513     if (Val == 0)
10514       return SDValue();
10515
10516     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10517   }
10518
10519   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10520 }
10521
10522 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10523                            SelectionDAG &DAG) {
10524   SDValue Op0 = Op.getOperand(0);
10525   SDValue Op1 = Op.getOperand(1);
10526   SDValue CC = Op.getOperand(2);
10527   MVT VT = Op.getSimpleValueType();
10528   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10529   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10530   SDLoc dl(Op);
10531
10532   if (isFP) {
10533 #ifndef NDEBUG
10534     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10535     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10536 #endif
10537
10538     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10539     unsigned Opc = X86ISD::CMPP;
10540     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10541       assert(VT.getVectorNumElements() <= 16);
10542       Opc = X86ISD::CMPM;
10543     }
10544     // In the two special cases we can't handle, emit two comparisons.
10545     if (SSECC == 8) {
10546       unsigned CC0, CC1;
10547       unsigned CombineOpc;
10548       if (SetCCOpcode == ISD::SETUEQ) {
10549         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10550       } else {
10551         assert(SetCCOpcode == ISD::SETONE);
10552         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10553       }
10554
10555       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10556                                  DAG.getConstant(CC0, MVT::i8));
10557       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10558                                  DAG.getConstant(CC1, MVT::i8));
10559       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10560     }
10561     // Handle all other FP comparisons here.
10562     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10563                        DAG.getConstant(SSECC, MVT::i8));
10564   }
10565
10566   // Break 256-bit integer vector compare into smaller ones.
10567   if (VT.is256BitVector() && !Subtarget->hasInt256())
10568     return Lower256IntVSETCC(Op, DAG);
10569
10570   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10571   EVT OpVT = Op1.getValueType();
10572   if (Subtarget->hasAVX512()) {
10573     if (Op1.getValueType().is512BitVector() ||
10574         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10575       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10576
10577     // In AVX-512 architecture setcc returns mask with i1 elements,
10578     // But there is no compare instruction for i8 and i16 elements.
10579     // We are not talking about 512-bit operands in this case, these
10580     // types are illegal.
10581     if (MaskResult &&
10582         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10583          OpVT.getVectorElementType().getSizeInBits() >= 8))
10584       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10585                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10586   }
10587
10588   // We are handling one of the integer comparisons here.  Since SSE only has
10589   // GT and EQ comparisons for integer, swapping operands and multiple
10590   // operations may be required for some comparisons.
10591   unsigned Opc;
10592   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10593   bool Subus = false;
10594
10595   switch (SetCCOpcode) {
10596   default: llvm_unreachable("Unexpected SETCC condition");
10597   case ISD::SETNE:  Invert = true;
10598   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10599   case ISD::SETLT:  Swap = true;
10600   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10601   case ISD::SETGE:  Swap = true;
10602   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10603                     Invert = true; break;
10604   case ISD::SETULT: Swap = true;
10605   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10606                     FlipSigns = true; break;
10607   case ISD::SETUGE: Swap = true;
10608   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10609                     FlipSigns = true; Invert = true; break;
10610   }
10611
10612   // Special case: Use min/max operations for SETULE/SETUGE
10613   MVT VET = VT.getVectorElementType();
10614   bool hasMinMax =
10615        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10616     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10617
10618   if (hasMinMax) {
10619     switch (SetCCOpcode) {
10620     default: break;
10621     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10622     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10623     }
10624
10625     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10626   }
10627
10628   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10629   if (!MinMax && hasSubus) {
10630     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10631     // Op0 u<= Op1:
10632     //   t = psubus Op0, Op1
10633     //   pcmpeq t, <0..0>
10634     switch (SetCCOpcode) {
10635     default: break;
10636     case ISD::SETULT: {
10637       // If the comparison is against a constant we can turn this into a
10638       // setule.  With psubus, setule does not require a swap.  This is
10639       // beneficial because the constant in the register is no longer
10640       // destructed as the destination so it can be hoisted out of a loop.
10641       // Only do this pre-AVX since vpcmp* is no longer destructive.
10642       if (Subtarget->hasAVX())
10643         break;
10644       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10645       if (ULEOp1.getNode()) {
10646         Op1 = ULEOp1;
10647         Subus = true; Invert = false; Swap = false;
10648       }
10649       break;
10650     }
10651     // Psubus is better than flip-sign because it requires no inversion.
10652     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10653     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10654     }
10655
10656     if (Subus) {
10657       Opc = X86ISD::SUBUS;
10658       FlipSigns = false;
10659     }
10660   }
10661
10662   if (Swap)
10663     std::swap(Op0, Op1);
10664
10665   // Check that the operation in question is available (most are plain SSE2,
10666   // but PCMPGTQ and PCMPEQQ have different requirements).
10667   if (VT == MVT::v2i64) {
10668     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10669       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10670
10671       // First cast everything to the right type.
10672       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10673       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10674
10675       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10676       // bits of the inputs before performing those operations. The lower
10677       // compare is always unsigned.
10678       SDValue SB;
10679       if (FlipSigns) {
10680         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10681       } else {
10682         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10683         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10684         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10685                          Sign, Zero, Sign, Zero);
10686       }
10687       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10688       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10689
10690       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10691       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10692       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10693
10694       // Create masks for only the low parts/high parts of the 64 bit integers.
10695       static const int MaskHi[] = { 1, 1, 3, 3 };
10696       static const int MaskLo[] = { 0, 0, 2, 2 };
10697       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10698       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10699       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10700
10701       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10702       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10703
10704       if (Invert)
10705         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10706
10707       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10708     }
10709
10710     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10711       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10712       // pcmpeqd + pshufd + pand.
10713       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10714
10715       // First cast everything to the right type.
10716       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10717       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10718
10719       // Do the compare.
10720       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10721
10722       // Make sure the lower and upper halves are both all-ones.
10723       static const int Mask[] = { 1, 0, 3, 2 };
10724       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10725       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10726
10727       if (Invert)
10728         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10729
10730       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10731     }
10732   }
10733
10734   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10735   // bits of the inputs before performing those operations.
10736   if (FlipSigns) {
10737     EVT EltVT = VT.getVectorElementType();
10738     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10739     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10740     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10741   }
10742
10743   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10744
10745   // If the logical-not of the result is required, perform that now.
10746   if (Invert)
10747     Result = DAG.getNOT(dl, Result, VT);
10748
10749   if (MinMax)
10750     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10751
10752   if (Subus)
10753     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10754                          getZeroVector(VT, Subtarget, DAG, dl));
10755
10756   return Result;
10757 }
10758
10759 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10760
10761   MVT VT = Op.getSimpleValueType();
10762
10763   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10764
10765   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10766          && "SetCC type must be 8-bit or 1-bit integer");
10767   SDValue Op0 = Op.getOperand(0);
10768   SDValue Op1 = Op.getOperand(1);
10769   SDLoc dl(Op);
10770   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10771
10772   // Optimize to BT if possible.
10773   // Lower (X & (1 << N)) == 0 to BT(X, N).
10774   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10775   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10776   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10777       Op1.getOpcode() == ISD::Constant &&
10778       cast<ConstantSDNode>(Op1)->isNullValue() &&
10779       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10780     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10781     if (NewSetCC.getNode())
10782       return NewSetCC;
10783   }
10784
10785   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10786   // these.
10787   if (Op1.getOpcode() == ISD::Constant &&
10788       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10789        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10790       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10791
10792     // If the input is a setcc, then reuse the input setcc or use a new one with
10793     // the inverted condition.
10794     if (Op0.getOpcode() == X86ISD::SETCC) {
10795       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10796       bool Invert = (CC == ISD::SETNE) ^
10797         cast<ConstantSDNode>(Op1)->isNullValue();
10798       if (!Invert)
10799         return Op0;
10800
10801       CCode = X86::GetOppositeBranchCondition(CCode);
10802       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10803                                   DAG.getConstant(CCode, MVT::i8),
10804                                   Op0.getOperand(1));
10805       if (VT == MVT::i1)
10806         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10807       return SetCC;
10808     }
10809   }
10810   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10811       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10812       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10813
10814     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10815     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10816   }
10817
10818   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10819   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10820   if (X86CC == X86::COND_INVALID)
10821     return SDValue();
10822
10823   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10824   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10825   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10826                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10827   if (VT == MVT::i1)
10828     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10829   return SetCC;
10830 }
10831
10832 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10833 static bool isX86LogicalCmp(SDValue Op) {
10834   unsigned Opc = Op.getNode()->getOpcode();
10835   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10836       Opc == X86ISD::SAHF)
10837     return true;
10838   if (Op.getResNo() == 1 &&
10839       (Opc == X86ISD::ADD ||
10840        Opc == X86ISD::SUB ||
10841        Opc == X86ISD::ADC ||
10842        Opc == X86ISD::SBB ||
10843        Opc == X86ISD::SMUL ||
10844        Opc == X86ISD::UMUL ||
10845        Opc == X86ISD::INC ||
10846        Opc == X86ISD::DEC ||
10847        Opc == X86ISD::OR ||
10848        Opc == X86ISD::XOR ||
10849        Opc == X86ISD::AND))
10850     return true;
10851
10852   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10853     return true;
10854
10855   return false;
10856 }
10857
10858 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10859   if (V.getOpcode() != ISD::TRUNCATE)
10860     return false;
10861
10862   SDValue VOp0 = V.getOperand(0);
10863   unsigned InBits = VOp0.getValueSizeInBits();
10864   unsigned Bits = V.getValueSizeInBits();
10865   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10866 }
10867
10868 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10869   bool addTest = true;
10870   SDValue Cond  = Op.getOperand(0);
10871   SDValue Op1 = Op.getOperand(1);
10872   SDValue Op2 = Op.getOperand(2);
10873   SDLoc DL(Op);
10874   EVT VT = Op1.getValueType();
10875   SDValue CC;
10876
10877   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10878   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10879   // sequence later on.
10880   if (Cond.getOpcode() == ISD::SETCC &&
10881       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10882        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10883       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10884     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10885     int SSECC = translateX86FSETCC(
10886         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10887
10888     if (SSECC != 8) {
10889       if (Subtarget->hasAVX512()) {
10890         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10891                                   DAG.getConstant(SSECC, MVT::i8));
10892         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10893       }
10894       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10895                                 DAG.getConstant(SSECC, MVT::i8));
10896       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10897       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10898       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10899     }
10900   }
10901
10902   if (Cond.getOpcode() == ISD::SETCC) {
10903     SDValue NewCond = LowerSETCC(Cond, DAG);
10904     if (NewCond.getNode())
10905       Cond = NewCond;
10906   }
10907
10908   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10909   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10910   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10911   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10912   if (Cond.getOpcode() == X86ISD::SETCC &&
10913       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10914       isZero(Cond.getOperand(1).getOperand(1))) {
10915     SDValue Cmp = Cond.getOperand(1);
10916
10917     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10918
10919     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10920         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10921       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10922
10923       SDValue CmpOp0 = Cmp.getOperand(0);
10924       // Apply further optimizations for special cases
10925       // (select (x != 0), -1, 0) -> neg & sbb
10926       // (select (x == 0), 0, -1) -> neg & sbb
10927       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10928         if (YC->isNullValue() &&
10929             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10930           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10931           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10932                                     DAG.getConstant(0, CmpOp0.getValueType()),
10933                                     CmpOp0);
10934           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10935                                     DAG.getConstant(X86::COND_B, MVT::i8),
10936                                     SDValue(Neg.getNode(), 1));
10937           return Res;
10938         }
10939
10940       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10941                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10942       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10943
10944       SDValue Res =   // Res = 0 or -1.
10945         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10946                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10947
10948       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10949         Res = DAG.getNOT(DL, Res, Res.getValueType());
10950
10951       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10952       if (!N2C || !N2C->isNullValue())
10953         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10954       return Res;
10955     }
10956   }
10957
10958   // Look past (and (setcc_carry (cmp ...)), 1).
10959   if (Cond.getOpcode() == ISD::AND &&
10960       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10961     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10962     if (C && C->getAPIntValue() == 1)
10963       Cond = Cond.getOperand(0);
10964   }
10965
10966   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10967   // setting operand in place of the X86ISD::SETCC.
10968   unsigned CondOpcode = Cond.getOpcode();
10969   if (CondOpcode == X86ISD::SETCC ||
10970       CondOpcode == X86ISD::SETCC_CARRY) {
10971     CC = Cond.getOperand(0);
10972
10973     SDValue Cmp = Cond.getOperand(1);
10974     unsigned Opc = Cmp.getOpcode();
10975     MVT VT = Op.getSimpleValueType();
10976
10977     bool IllegalFPCMov = false;
10978     if (VT.isFloatingPoint() && !VT.isVector() &&
10979         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10980       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10981
10982     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10983         Opc == X86ISD::BT) { // FIXME
10984       Cond = Cmp;
10985       addTest = false;
10986     }
10987   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10988              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10989              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10990               Cond.getOperand(0).getValueType() != MVT::i8)) {
10991     SDValue LHS = Cond.getOperand(0);
10992     SDValue RHS = Cond.getOperand(1);
10993     unsigned X86Opcode;
10994     unsigned X86Cond;
10995     SDVTList VTs;
10996     switch (CondOpcode) {
10997     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10998     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10999     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11000     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11001     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11002     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11003     default: llvm_unreachable("unexpected overflowing operator");
11004     }
11005     if (CondOpcode == ISD::UMULO)
11006       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11007                           MVT::i32);
11008     else
11009       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11010
11011     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11012
11013     if (CondOpcode == ISD::UMULO)
11014       Cond = X86Op.getValue(2);
11015     else
11016       Cond = X86Op.getValue(1);
11017
11018     CC = DAG.getConstant(X86Cond, MVT::i8);
11019     addTest = false;
11020   }
11021
11022   if (addTest) {
11023     // Look pass the truncate if the high bits are known zero.
11024     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11025         Cond = Cond.getOperand(0);
11026
11027     // We know the result of AND is compared against zero. Try to match
11028     // it to BT.
11029     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11030       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11031       if (NewSetCC.getNode()) {
11032         CC = NewSetCC.getOperand(0);
11033         Cond = NewSetCC.getOperand(1);
11034         addTest = false;
11035       }
11036     }
11037   }
11038
11039   if (addTest) {
11040     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11041     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11042   }
11043
11044   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11045   // a <  b ?  0 : -1 -> RES = setcc_carry
11046   // a >= b ? -1 :  0 -> RES = setcc_carry
11047   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11048   if (Cond.getOpcode() == X86ISD::SUB) {
11049     Cond = ConvertCmpIfNecessary(Cond, DAG);
11050     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11051
11052     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11053         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11054       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11055                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11056       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11057         return DAG.getNOT(DL, Res, Res.getValueType());
11058       return Res;
11059     }
11060   }
11061
11062   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11063   // widen the cmov and push the truncate through. This avoids introducing a new
11064   // branch during isel and doesn't add any extensions.
11065   if (Op.getValueType() == MVT::i8 &&
11066       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11067     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11068     if (T1.getValueType() == T2.getValueType() &&
11069         // Blacklist CopyFromReg to avoid partial register stalls.
11070         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11071       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11072       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11073       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11074     }
11075   }
11076
11077   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11078   // condition is true.
11079   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11080   SDValue Ops[] = { Op2, Op1, CC, Cond };
11081   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11082 }
11083
11084 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11085   MVT VT = Op->getSimpleValueType(0);
11086   SDValue In = Op->getOperand(0);
11087   MVT InVT = In.getSimpleValueType();
11088   SDLoc dl(Op);
11089
11090   unsigned int NumElts = VT.getVectorNumElements();
11091   if (NumElts != 8 && NumElts != 16)
11092     return SDValue();
11093
11094   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11095     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11096
11097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11098   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11099
11100   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11101   Constant *C = ConstantInt::get(*DAG.getContext(),
11102     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11103
11104   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11105   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11106   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11107                           MachinePointerInfo::getConstantPool(),
11108                           false, false, false, Alignment);
11109   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11110   if (VT.is512BitVector())
11111     return Brcst;
11112   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11113 }
11114
11115 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11116                                 SelectionDAG &DAG) {
11117   MVT VT = Op->getSimpleValueType(0);
11118   SDValue In = Op->getOperand(0);
11119   MVT InVT = In.getSimpleValueType();
11120   SDLoc dl(Op);
11121
11122   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11123     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11124
11125   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11126       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11127       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11128     return SDValue();
11129
11130   if (Subtarget->hasInt256())
11131     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11132
11133   // Optimize vectors in AVX mode
11134   // Sign extend  v8i16 to v8i32 and
11135   //              v4i32 to v4i64
11136   //
11137   // Divide input vector into two parts
11138   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11139   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11140   // concat the vectors to original VT
11141
11142   unsigned NumElems = InVT.getVectorNumElements();
11143   SDValue Undef = DAG.getUNDEF(InVT);
11144
11145   SmallVector<int,8> ShufMask1(NumElems, -1);
11146   for (unsigned i = 0; i != NumElems/2; ++i)
11147     ShufMask1[i] = i;
11148
11149   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11150
11151   SmallVector<int,8> ShufMask2(NumElems, -1);
11152   for (unsigned i = 0; i != NumElems/2; ++i)
11153     ShufMask2[i] = i + NumElems/2;
11154
11155   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11156
11157   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11158                                 VT.getVectorNumElements()/2);
11159
11160   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11161   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11162
11163   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11164 }
11165
11166 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11167 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11168 // from the AND / OR.
11169 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11170   Opc = Op.getOpcode();
11171   if (Opc != ISD::OR && Opc != ISD::AND)
11172     return false;
11173   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11174           Op.getOperand(0).hasOneUse() &&
11175           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11176           Op.getOperand(1).hasOneUse());
11177 }
11178
11179 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11180 // 1 and that the SETCC node has a single use.
11181 static bool isXor1OfSetCC(SDValue Op) {
11182   if (Op.getOpcode() != ISD::XOR)
11183     return false;
11184   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11185   if (N1C && N1C->getAPIntValue() == 1) {
11186     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11187       Op.getOperand(0).hasOneUse();
11188   }
11189   return false;
11190 }
11191
11192 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11193   bool addTest = true;
11194   SDValue Chain = Op.getOperand(0);
11195   SDValue Cond  = Op.getOperand(1);
11196   SDValue Dest  = Op.getOperand(2);
11197   SDLoc dl(Op);
11198   SDValue CC;
11199   bool Inverted = false;
11200
11201   if (Cond.getOpcode() == ISD::SETCC) {
11202     // Check for setcc([su]{add,sub,mul}o == 0).
11203     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11204         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11205         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11206         Cond.getOperand(0).getResNo() == 1 &&
11207         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11208          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11209          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11210          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11211          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11212          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11213       Inverted = true;
11214       Cond = Cond.getOperand(0);
11215     } else {
11216       SDValue NewCond = LowerSETCC(Cond, DAG);
11217       if (NewCond.getNode())
11218         Cond = NewCond;
11219     }
11220   }
11221 #if 0
11222   // FIXME: LowerXALUO doesn't handle these!!
11223   else if (Cond.getOpcode() == X86ISD::ADD  ||
11224            Cond.getOpcode() == X86ISD::SUB  ||
11225            Cond.getOpcode() == X86ISD::SMUL ||
11226            Cond.getOpcode() == X86ISD::UMUL)
11227     Cond = LowerXALUO(Cond, DAG);
11228 #endif
11229
11230   // Look pass (and (setcc_carry (cmp ...)), 1).
11231   if (Cond.getOpcode() == ISD::AND &&
11232       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11233     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11234     if (C && C->getAPIntValue() == 1)
11235       Cond = Cond.getOperand(0);
11236   }
11237
11238   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11239   // setting operand in place of the X86ISD::SETCC.
11240   unsigned CondOpcode = Cond.getOpcode();
11241   if (CondOpcode == X86ISD::SETCC ||
11242       CondOpcode == X86ISD::SETCC_CARRY) {
11243     CC = Cond.getOperand(0);
11244
11245     SDValue Cmp = Cond.getOperand(1);
11246     unsigned Opc = Cmp.getOpcode();
11247     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11248     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11249       Cond = Cmp;
11250       addTest = false;
11251     } else {
11252       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11253       default: break;
11254       case X86::COND_O:
11255       case X86::COND_B:
11256         // These can only come from an arithmetic instruction with overflow,
11257         // e.g. SADDO, UADDO.
11258         Cond = Cond.getNode()->getOperand(1);
11259         addTest = false;
11260         break;
11261       }
11262     }
11263   }
11264   CondOpcode = Cond.getOpcode();
11265   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11266       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11267       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11268        Cond.getOperand(0).getValueType() != MVT::i8)) {
11269     SDValue LHS = Cond.getOperand(0);
11270     SDValue RHS = Cond.getOperand(1);
11271     unsigned X86Opcode;
11272     unsigned X86Cond;
11273     SDVTList VTs;
11274     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11275     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11276     // X86ISD::INC).
11277     switch (CondOpcode) {
11278     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11279     case ISD::SADDO:
11280       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11281         if (C->isOne()) {
11282           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11283           break;
11284         }
11285       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11286     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11287     case ISD::SSUBO:
11288       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11289         if (C->isOne()) {
11290           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11291           break;
11292         }
11293       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11294     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11295     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11296     default: llvm_unreachable("unexpected overflowing operator");
11297     }
11298     if (Inverted)
11299       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11300     if (CondOpcode == ISD::UMULO)
11301       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11302                           MVT::i32);
11303     else
11304       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11305
11306     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11307
11308     if (CondOpcode == ISD::UMULO)
11309       Cond = X86Op.getValue(2);
11310     else
11311       Cond = X86Op.getValue(1);
11312
11313     CC = DAG.getConstant(X86Cond, MVT::i8);
11314     addTest = false;
11315   } else {
11316     unsigned CondOpc;
11317     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11318       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11319       if (CondOpc == ISD::OR) {
11320         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11321         // two branches instead of an explicit OR instruction with a
11322         // separate test.
11323         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11324             isX86LogicalCmp(Cmp)) {
11325           CC = Cond.getOperand(0).getOperand(0);
11326           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11327                               Chain, Dest, CC, Cmp);
11328           CC = Cond.getOperand(1).getOperand(0);
11329           Cond = Cmp;
11330           addTest = false;
11331         }
11332       } else { // ISD::AND
11333         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11334         // two branches instead of an explicit AND instruction with a
11335         // separate test. However, we only do this if this block doesn't
11336         // have a fall-through edge, because this requires an explicit
11337         // jmp when the condition is false.
11338         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11339             isX86LogicalCmp(Cmp) &&
11340             Op.getNode()->hasOneUse()) {
11341           X86::CondCode CCode =
11342             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11343           CCode = X86::GetOppositeBranchCondition(CCode);
11344           CC = DAG.getConstant(CCode, MVT::i8);
11345           SDNode *User = *Op.getNode()->use_begin();
11346           // Look for an unconditional branch following this conditional branch.
11347           // We need this because we need to reverse the successors in order
11348           // to implement FCMP_OEQ.
11349           if (User->getOpcode() == ISD::BR) {
11350             SDValue FalseBB = User->getOperand(1);
11351             SDNode *NewBR =
11352               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11353             assert(NewBR == User);
11354             (void)NewBR;
11355             Dest = FalseBB;
11356
11357             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11358                                 Chain, Dest, CC, Cmp);
11359             X86::CondCode CCode =
11360               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11361             CCode = X86::GetOppositeBranchCondition(CCode);
11362             CC = DAG.getConstant(CCode, MVT::i8);
11363             Cond = Cmp;
11364             addTest = false;
11365           }
11366         }
11367       }
11368     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11369       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11370       // It should be transformed during dag combiner except when the condition
11371       // is set by a arithmetics with overflow node.
11372       X86::CondCode CCode =
11373         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11374       CCode = X86::GetOppositeBranchCondition(CCode);
11375       CC = DAG.getConstant(CCode, MVT::i8);
11376       Cond = Cond.getOperand(0).getOperand(1);
11377       addTest = false;
11378     } else if (Cond.getOpcode() == ISD::SETCC &&
11379                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11380       // For FCMP_OEQ, we can emit
11381       // two branches instead of an explicit AND instruction with a
11382       // separate test. However, we only do this if this block doesn't
11383       // have a fall-through edge, because this requires an explicit
11384       // jmp when the condition is false.
11385       if (Op.getNode()->hasOneUse()) {
11386         SDNode *User = *Op.getNode()->use_begin();
11387         // Look for an unconditional branch following this conditional branch.
11388         // We need this because we need to reverse the successors in order
11389         // to implement FCMP_OEQ.
11390         if (User->getOpcode() == ISD::BR) {
11391           SDValue FalseBB = User->getOperand(1);
11392           SDNode *NewBR =
11393             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11394           assert(NewBR == User);
11395           (void)NewBR;
11396           Dest = FalseBB;
11397
11398           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11399                                     Cond.getOperand(0), Cond.getOperand(1));
11400           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11401           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11402           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11403                               Chain, Dest, CC, Cmp);
11404           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11405           Cond = Cmp;
11406           addTest = false;
11407         }
11408       }
11409     } else if (Cond.getOpcode() == ISD::SETCC &&
11410                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11411       // For FCMP_UNE, we can emit
11412       // two branches instead of an explicit AND instruction with a
11413       // separate test. However, we only do this if this block doesn't
11414       // have a fall-through edge, because this requires an explicit
11415       // jmp when the condition is false.
11416       if (Op.getNode()->hasOneUse()) {
11417         SDNode *User = *Op.getNode()->use_begin();
11418         // Look for an unconditional branch following this conditional branch.
11419         // We need this because we need to reverse the successors in order
11420         // to implement FCMP_UNE.
11421         if (User->getOpcode() == ISD::BR) {
11422           SDValue FalseBB = User->getOperand(1);
11423           SDNode *NewBR =
11424             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11425           assert(NewBR == User);
11426           (void)NewBR;
11427
11428           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11429                                     Cond.getOperand(0), Cond.getOperand(1));
11430           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11431           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11432           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11433                               Chain, Dest, CC, Cmp);
11434           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11435           Cond = Cmp;
11436           addTest = false;
11437           Dest = FalseBB;
11438         }
11439       }
11440     }
11441   }
11442
11443   if (addTest) {
11444     // Look pass the truncate if the high bits are known zero.
11445     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11446         Cond = Cond.getOperand(0);
11447
11448     // We know the result of AND is compared against zero. Try to match
11449     // it to BT.
11450     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11451       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11452       if (NewSetCC.getNode()) {
11453         CC = NewSetCC.getOperand(0);
11454         Cond = NewSetCC.getOperand(1);
11455         addTest = false;
11456       }
11457     }
11458   }
11459
11460   if (addTest) {
11461     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11462     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11463   }
11464   Cond = ConvertCmpIfNecessary(Cond, DAG);
11465   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11466                      Chain, Dest, CC, Cond);
11467 }
11468
11469 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11470 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11471 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11472 // that the guard pages used by the OS virtual memory manager are allocated in
11473 // correct sequence.
11474 SDValue
11475 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11476                                            SelectionDAG &DAG) const {
11477   MachineFunction &MF = DAG.getMachineFunction();
11478   bool SplitStack = MF.shouldSplitStack();
11479   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11480                SplitStack;
11481   SDLoc dl(Op);
11482
11483   if (!Lower) {
11484     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11485     SDNode* Node = Op.getNode();
11486
11487     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11488     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11489         " not tell us which reg is the stack pointer!");
11490     EVT VT = Node->getValueType(0);
11491     SDValue Tmp1 = SDValue(Node, 0);
11492     SDValue Tmp2 = SDValue(Node, 1);
11493     SDValue Tmp3 = Node->getOperand(2);
11494     SDValue Chain = Tmp1.getOperand(0);
11495
11496     // Chain the dynamic stack allocation so that it doesn't modify the stack
11497     // pointer when other instructions are using the stack.
11498     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11499         SDLoc(Node));
11500
11501     SDValue Size = Tmp2.getOperand(1);
11502     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11503     Chain = SP.getValue(1);
11504     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11505     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11506     unsigned StackAlign = TFI.getStackAlignment();
11507     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11508     if (Align > StackAlign)
11509       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11510           DAG.getConstant(-(uint64_t)Align, VT));
11511     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11512
11513     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11514         DAG.getIntPtrConstant(0, true), SDValue(),
11515         SDLoc(Node));
11516
11517     SDValue Ops[2] = { Tmp1, Tmp2 };
11518     return DAG.getMergeValues(Ops, dl);
11519   }
11520
11521   // Get the inputs.
11522   SDValue Chain = Op.getOperand(0);
11523   SDValue Size  = Op.getOperand(1);
11524   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11525   EVT VT = Op.getNode()->getValueType(0);
11526
11527   bool Is64Bit = Subtarget->is64Bit();
11528   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11529
11530   if (SplitStack) {
11531     MachineRegisterInfo &MRI = MF.getRegInfo();
11532
11533     if (Is64Bit) {
11534       // The 64 bit implementation of segmented stacks needs to clobber both r10
11535       // r11. This makes it impossible to use it along with nested parameters.
11536       const Function *F = MF.getFunction();
11537
11538       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11539            I != E; ++I)
11540         if (I->hasNestAttr())
11541           report_fatal_error("Cannot use segmented stacks with functions that "
11542                              "have nested arguments.");
11543     }
11544
11545     const TargetRegisterClass *AddrRegClass =
11546       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11547     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11548     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11549     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11550                                 DAG.getRegister(Vreg, SPTy));
11551     SDValue Ops1[2] = { Value, Chain };
11552     return DAG.getMergeValues(Ops1, dl);
11553   } else {
11554     SDValue Flag;
11555     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11556
11557     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11558     Flag = Chain.getValue(1);
11559     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11560
11561     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11562
11563     const X86RegisterInfo *RegInfo =
11564       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11565     unsigned SPReg = RegInfo->getStackRegister();
11566     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11567     Chain = SP.getValue(1);
11568
11569     if (Align) {
11570       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11571                        DAG.getConstant(-(uint64_t)Align, VT));
11572       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11573     }
11574
11575     SDValue Ops1[2] = { SP, Chain };
11576     return DAG.getMergeValues(Ops1, dl);
11577   }
11578 }
11579
11580 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11581   MachineFunction &MF = DAG.getMachineFunction();
11582   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11583
11584   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11585   SDLoc DL(Op);
11586
11587   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11588     // vastart just stores the address of the VarArgsFrameIndex slot into the
11589     // memory location argument.
11590     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11591                                    getPointerTy());
11592     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11593                         MachinePointerInfo(SV), false, false, 0);
11594   }
11595
11596   // __va_list_tag:
11597   //   gp_offset         (0 - 6 * 8)
11598   //   fp_offset         (48 - 48 + 8 * 16)
11599   //   overflow_arg_area (point to parameters coming in memory).
11600   //   reg_save_area
11601   SmallVector<SDValue, 8> MemOps;
11602   SDValue FIN = Op.getOperand(1);
11603   // Store gp_offset
11604   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11605                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11606                                                MVT::i32),
11607                                FIN, MachinePointerInfo(SV), false, false, 0);
11608   MemOps.push_back(Store);
11609
11610   // Store fp_offset
11611   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11612                     FIN, DAG.getIntPtrConstant(4));
11613   Store = DAG.getStore(Op.getOperand(0), DL,
11614                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11615                                        MVT::i32),
11616                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11617   MemOps.push_back(Store);
11618
11619   // Store ptr to overflow_arg_area
11620   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11621                     FIN, DAG.getIntPtrConstant(4));
11622   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11623                                     getPointerTy());
11624   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11625                        MachinePointerInfo(SV, 8),
11626                        false, false, 0);
11627   MemOps.push_back(Store);
11628
11629   // Store ptr to reg_save_area.
11630   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11631                     FIN, DAG.getIntPtrConstant(8));
11632   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11633                                     getPointerTy());
11634   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11635                        MachinePointerInfo(SV, 16), false, false, 0);
11636   MemOps.push_back(Store);
11637   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11638 }
11639
11640 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11641   assert(Subtarget->is64Bit() &&
11642          "LowerVAARG only handles 64-bit va_arg!");
11643   assert((Subtarget->isTargetLinux() ||
11644           Subtarget->isTargetDarwin()) &&
11645           "Unhandled target in LowerVAARG");
11646   assert(Op.getNode()->getNumOperands() == 4);
11647   SDValue Chain = Op.getOperand(0);
11648   SDValue SrcPtr = Op.getOperand(1);
11649   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11650   unsigned Align = Op.getConstantOperandVal(3);
11651   SDLoc dl(Op);
11652
11653   EVT ArgVT = Op.getNode()->getValueType(0);
11654   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11655   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11656   uint8_t ArgMode;
11657
11658   // Decide which area this value should be read from.
11659   // TODO: Implement the AMD64 ABI in its entirety. This simple
11660   // selection mechanism works only for the basic types.
11661   if (ArgVT == MVT::f80) {
11662     llvm_unreachable("va_arg for f80 not yet implemented");
11663   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11664     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11665   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11666     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11667   } else {
11668     llvm_unreachable("Unhandled argument type in LowerVAARG");
11669   }
11670
11671   if (ArgMode == 2) {
11672     // Sanity Check: Make sure using fp_offset makes sense.
11673     assert(!getTargetMachine().Options.UseSoftFloat &&
11674            !(DAG.getMachineFunction()
11675                 .getFunction()->getAttributes()
11676                 .hasAttribute(AttributeSet::FunctionIndex,
11677                               Attribute::NoImplicitFloat)) &&
11678            Subtarget->hasSSE1());
11679   }
11680
11681   // Insert VAARG_64 node into the DAG
11682   // VAARG_64 returns two values: Variable Argument Address, Chain
11683   SmallVector<SDValue, 11> InstOps;
11684   InstOps.push_back(Chain);
11685   InstOps.push_back(SrcPtr);
11686   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11687   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11688   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11689   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11690   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11691                                           VTs, InstOps, MVT::i64,
11692                                           MachinePointerInfo(SV),
11693                                           /*Align=*/0,
11694                                           /*Volatile=*/false,
11695                                           /*ReadMem=*/true,
11696                                           /*WriteMem=*/true);
11697   Chain = VAARG.getValue(1);
11698
11699   // Load the next argument and return it
11700   return DAG.getLoad(ArgVT, dl,
11701                      Chain,
11702                      VAARG,
11703                      MachinePointerInfo(),
11704                      false, false, false, 0);
11705 }
11706
11707 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11708                            SelectionDAG &DAG) {
11709   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11710   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11711   SDValue Chain = Op.getOperand(0);
11712   SDValue DstPtr = Op.getOperand(1);
11713   SDValue SrcPtr = Op.getOperand(2);
11714   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11715   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11716   SDLoc DL(Op);
11717
11718   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11719                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11720                        false,
11721                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11722 }
11723
11724 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11725 // amount is a constant. Takes immediate version of shift as input.
11726 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11727                                           SDValue SrcOp, uint64_t ShiftAmt,
11728                                           SelectionDAG &DAG) {
11729   MVT ElementType = VT.getVectorElementType();
11730
11731   // Fold this packed shift into its first operand if ShiftAmt is 0.
11732   if (ShiftAmt == 0)
11733     return SrcOp;
11734
11735   // Check for ShiftAmt >= element width
11736   if (ShiftAmt >= ElementType.getSizeInBits()) {
11737     if (Opc == X86ISD::VSRAI)
11738       ShiftAmt = ElementType.getSizeInBits() - 1;
11739     else
11740       return DAG.getConstant(0, VT);
11741   }
11742
11743   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11744          && "Unknown target vector shift-by-constant node");
11745
11746   // Fold this packed vector shift into a build vector if SrcOp is a
11747   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11748   if (VT == SrcOp.getSimpleValueType() &&
11749       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11750     SmallVector<SDValue, 8> Elts;
11751     unsigned NumElts = SrcOp->getNumOperands();
11752     ConstantSDNode *ND;
11753
11754     switch(Opc) {
11755     default: llvm_unreachable(nullptr);
11756     case X86ISD::VSHLI:
11757       for (unsigned i=0; i!=NumElts; ++i) {
11758         SDValue CurrentOp = SrcOp->getOperand(i);
11759         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11760           Elts.push_back(CurrentOp);
11761           continue;
11762         }
11763         ND = cast<ConstantSDNode>(CurrentOp);
11764         const APInt &C = ND->getAPIntValue();
11765         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11766       }
11767       break;
11768     case X86ISD::VSRLI:
11769       for (unsigned i=0; i!=NumElts; ++i) {
11770         SDValue CurrentOp = SrcOp->getOperand(i);
11771         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11772           Elts.push_back(CurrentOp);
11773           continue;
11774         }
11775         ND = cast<ConstantSDNode>(CurrentOp);
11776         const APInt &C = ND->getAPIntValue();
11777         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11778       }
11779       break;
11780     case X86ISD::VSRAI:
11781       for (unsigned i=0; i!=NumElts; ++i) {
11782         SDValue CurrentOp = SrcOp->getOperand(i);
11783         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11784           Elts.push_back(CurrentOp);
11785           continue;
11786         }
11787         ND = cast<ConstantSDNode>(CurrentOp);
11788         const APInt &C = ND->getAPIntValue();
11789         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11790       }
11791       break;
11792     }
11793
11794     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11795   }
11796
11797   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11798 }
11799
11800 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11801 // may or may not be a constant. Takes immediate version of shift as input.
11802 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11803                                    SDValue SrcOp, SDValue ShAmt,
11804                                    SelectionDAG &DAG) {
11805   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11806
11807   // Catch shift-by-constant.
11808   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11809     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11810                                       CShAmt->getZExtValue(), DAG);
11811
11812   // Change opcode to non-immediate version
11813   switch (Opc) {
11814     default: llvm_unreachable("Unknown target vector shift node");
11815     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11816     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11817     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11818   }
11819
11820   // Need to build a vector containing shift amount
11821   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11822   SDValue ShOps[4];
11823   ShOps[0] = ShAmt;
11824   ShOps[1] = DAG.getConstant(0, MVT::i32);
11825   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11826   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11827
11828   // The return type has to be a 128-bit type with the same element
11829   // type as the input type.
11830   MVT EltVT = VT.getVectorElementType();
11831   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11832
11833   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11834   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11835 }
11836
11837 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11838   SDLoc dl(Op);
11839   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11840   switch (IntNo) {
11841   default: return SDValue();    // Don't custom lower most intrinsics.
11842   // Comparison intrinsics.
11843   case Intrinsic::x86_sse_comieq_ss:
11844   case Intrinsic::x86_sse_comilt_ss:
11845   case Intrinsic::x86_sse_comile_ss:
11846   case Intrinsic::x86_sse_comigt_ss:
11847   case Intrinsic::x86_sse_comige_ss:
11848   case Intrinsic::x86_sse_comineq_ss:
11849   case Intrinsic::x86_sse_ucomieq_ss:
11850   case Intrinsic::x86_sse_ucomilt_ss:
11851   case Intrinsic::x86_sse_ucomile_ss:
11852   case Intrinsic::x86_sse_ucomigt_ss:
11853   case Intrinsic::x86_sse_ucomige_ss:
11854   case Intrinsic::x86_sse_ucomineq_ss:
11855   case Intrinsic::x86_sse2_comieq_sd:
11856   case Intrinsic::x86_sse2_comilt_sd:
11857   case Intrinsic::x86_sse2_comile_sd:
11858   case Intrinsic::x86_sse2_comigt_sd:
11859   case Intrinsic::x86_sse2_comige_sd:
11860   case Intrinsic::x86_sse2_comineq_sd:
11861   case Intrinsic::x86_sse2_ucomieq_sd:
11862   case Intrinsic::x86_sse2_ucomilt_sd:
11863   case Intrinsic::x86_sse2_ucomile_sd:
11864   case Intrinsic::x86_sse2_ucomigt_sd:
11865   case Intrinsic::x86_sse2_ucomige_sd:
11866   case Intrinsic::x86_sse2_ucomineq_sd: {
11867     unsigned Opc;
11868     ISD::CondCode CC;
11869     switch (IntNo) {
11870     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11871     case Intrinsic::x86_sse_comieq_ss:
11872     case Intrinsic::x86_sse2_comieq_sd:
11873       Opc = X86ISD::COMI;
11874       CC = ISD::SETEQ;
11875       break;
11876     case Intrinsic::x86_sse_comilt_ss:
11877     case Intrinsic::x86_sse2_comilt_sd:
11878       Opc = X86ISD::COMI;
11879       CC = ISD::SETLT;
11880       break;
11881     case Intrinsic::x86_sse_comile_ss:
11882     case Intrinsic::x86_sse2_comile_sd:
11883       Opc = X86ISD::COMI;
11884       CC = ISD::SETLE;
11885       break;
11886     case Intrinsic::x86_sse_comigt_ss:
11887     case Intrinsic::x86_sse2_comigt_sd:
11888       Opc = X86ISD::COMI;
11889       CC = ISD::SETGT;
11890       break;
11891     case Intrinsic::x86_sse_comige_ss:
11892     case Intrinsic::x86_sse2_comige_sd:
11893       Opc = X86ISD::COMI;
11894       CC = ISD::SETGE;
11895       break;
11896     case Intrinsic::x86_sse_comineq_ss:
11897     case Intrinsic::x86_sse2_comineq_sd:
11898       Opc = X86ISD::COMI;
11899       CC = ISD::SETNE;
11900       break;
11901     case Intrinsic::x86_sse_ucomieq_ss:
11902     case Intrinsic::x86_sse2_ucomieq_sd:
11903       Opc = X86ISD::UCOMI;
11904       CC = ISD::SETEQ;
11905       break;
11906     case Intrinsic::x86_sse_ucomilt_ss:
11907     case Intrinsic::x86_sse2_ucomilt_sd:
11908       Opc = X86ISD::UCOMI;
11909       CC = ISD::SETLT;
11910       break;
11911     case Intrinsic::x86_sse_ucomile_ss:
11912     case Intrinsic::x86_sse2_ucomile_sd:
11913       Opc = X86ISD::UCOMI;
11914       CC = ISD::SETLE;
11915       break;
11916     case Intrinsic::x86_sse_ucomigt_ss:
11917     case Intrinsic::x86_sse2_ucomigt_sd:
11918       Opc = X86ISD::UCOMI;
11919       CC = ISD::SETGT;
11920       break;
11921     case Intrinsic::x86_sse_ucomige_ss:
11922     case Intrinsic::x86_sse2_ucomige_sd:
11923       Opc = X86ISD::UCOMI;
11924       CC = ISD::SETGE;
11925       break;
11926     case Intrinsic::x86_sse_ucomineq_ss:
11927     case Intrinsic::x86_sse2_ucomineq_sd:
11928       Opc = X86ISD::UCOMI;
11929       CC = ISD::SETNE;
11930       break;
11931     }
11932
11933     SDValue LHS = Op.getOperand(1);
11934     SDValue RHS = Op.getOperand(2);
11935     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11936     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11937     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11938     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11939                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11940     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11941   }
11942
11943   // Arithmetic intrinsics.
11944   case Intrinsic::x86_sse2_pmulu_dq:
11945   case Intrinsic::x86_avx2_pmulu_dq:
11946     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11947                        Op.getOperand(1), Op.getOperand(2));
11948
11949   case Intrinsic::x86_sse41_pmuldq:
11950   case Intrinsic::x86_avx2_pmul_dq:
11951     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11952                        Op.getOperand(1), Op.getOperand(2));
11953
11954   case Intrinsic::x86_sse2_pmulhu_w:
11955   case Intrinsic::x86_avx2_pmulhu_w:
11956     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11957                        Op.getOperand(1), Op.getOperand(2));
11958
11959   case Intrinsic::x86_sse2_pmulh_w:
11960   case Intrinsic::x86_avx2_pmulh_w:
11961     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11962                        Op.getOperand(1), Op.getOperand(2));
11963
11964   // SSE2/AVX2 sub with unsigned saturation intrinsics
11965   case Intrinsic::x86_sse2_psubus_b:
11966   case Intrinsic::x86_sse2_psubus_w:
11967   case Intrinsic::x86_avx2_psubus_b:
11968   case Intrinsic::x86_avx2_psubus_w:
11969     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11970                        Op.getOperand(1), Op.getOperand(2));
11971
11972   // SSE3/AVX horizontal add/sub intrinsics
11973   case Intrinsic::x86_sse3_hadd_ps:
11974   case Intrinsic::x86_sse3_hadd_pd:
11975   case Intrinsic::x86_avx_hadd_ps_256:
11976   case Intrinsic::x86_avx_hadd_pd_256:
11977   case Intrinsic::x86_sse3_hsub_ps:
11978   case Intrinsic::x86_sse3_hsub_pd:
11979   case Intrinsic::x86_avx_hsub_ps_256:
11980   case Intrinsic::x86_avx_hsub_pd_256:
11981   case Intrinsic::x86_ssse3_phadd_w_128:
11982   case Intrinsic::x86_ssse3_phadd_d_128:
11983   case Intrinsic::x86_avx2_phadd_w:
11984   case Intrinsic::x86_avx2_phadd_d:
11985   case Intrinsic::x86_ssse3_phsub_w_128:
11986   case Intrinsic::x86_ssse3_phsub_d_128:
11987   case Intrinsic::x86_avx2_phsub_w:
11988   case Intrinsic::x86_avx2_phsub_d: {
11989     unsigned Opcode;
11990     switch (IntNo) {
11991     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11992     case Intrinsic::x86_sse3_hadd_ps:
11993     case Intrinsic::x86_sse3_hadd_pd:
11994     case Intrinsic::x86_avx_hadd_ps_256:
11995     case Intrinsic::x86_avx_hadd_pd_256:
11996       Opcode = X86ISD::FHADD;
11997       break;
11998     case Intrinsic::x86_sse3_hsub_ps:
11999     case Intrinsic::x86_sse3_hsub_pd:
12000     case Intrinsic::x86_avx_hsub_ps_256:
12001     case Intrinsic::x86_avx_hsub_pd_256:
12002       Opcode = X86ISD::FHSUB;
12003       break;
12004     case Intrinsic::x86_ssse3_phadd_w_128:
12005     case Intrinsic::x86_ssse3_phadd_d_128:
12006     case Intrinsic::x86_avx2_phadd_w:
12007     case Intrinsic::x86_avx2_phadd_d:
12008       Opcode = X86ISD::HADD;
12009       break;
12010     case Intrinsic::x86_ssse3_phsub_w_128:
12011     case Intrinsic::x86_ssse3_phsub_d_128:
12012     case Intrinsic::x86_avx2_phsub_w:
12013     case Intrinsic::x86_avx2_phsub_d:
12014       Opcode = X86ISD::HSUB;
12015       break;
12016     }
12017     return DAG.getNode(Opcode, dl, Op.getValueType(),
12018                        Op.getOperand(1), Op.getOperand(2));
12019   }
12020
12021   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12022   case Intrinsic::x86_sse2_pmaxu_b:
12023   case Intrinsic::x86_sse41_pmaxuw:
12024   case Intrinsic::x86_sse41_pmaxud:
12025   case Intrinsic::x86_avx2_pmaxu_b:
12026   case Intrinsic::x86_avx2_pmaxu_w:
12027   case Intrinsic::x86_avx2_pmaxu_d:
12028   case Intrinsic::x86_sse2_pminu_b:
12029   case Intrinsic::x86_sse41_pminuw:
12030   case Intrinsic::x86_sse41_pminud:
12031   case Intrinsic::x86_avx2_pminu_b:
12032   case Intrinsic::x86_avx2_pminu_w:
12033   case Intrinsic::x86_avx2_pminu_d:
12034   case Intrinsic::x86_sse41_pmaxsb:
12035   case Intrinsic::x86_sse2_pmaxs_w:
12036   case Intrinsic::x86_sse41_pmaxsd:
12037   case Intrinsic::x86_avx2_pmaxs_b:
12038   case Intrinsic::x86_avx2_pmaxs_w:
12039   case Intrinsic::x86_avx2_pmaxs_d:
12040   case Intrinsic::x86_sse41_pminsb:
12041   case Intrinsic::x86_sse2_pmins_w:
12042   case Intrinsic::x86_sse41_pminsd:
12043   case Intrinsic::x86_avx2_pmins_b:
12044   case Intrinsic::x86_avx2_pmins_w:
12045   case Intrinsic::x86_avx2_pmins_d: {
12046     unsigned Opcode;
12047     switch (IntNo) {
12048     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12049     case Intrinsic::x86_sse2_pmaxu_b:
12050     case Intrinsic::x86_sse41_pmaxuw:
12051     case Intrinsic::x86_sse41_pmaxud:
12052     case Intrinsic::x86_avx2_pmaxu_b:
12053     case Intrinsic::x86_avx2_pmaxu_w:
12054     case Intrinsic::x86_avx2_pmaxu_d:
12055       Opcode = X86ISD::UMAX;
12056       break;
12057     case Intrinsic::x86_sse2_pminu_b:
12058     case Intrinsic::x86_sse41_pminuw:
12059     case Intrinsic::x86_sse41_pminud:
12060     case Intrinsic::x86_avx2_pminu_b:
12061     case Intrinsic::x86_avx2_pminu_w:
12062     case Intrinsic::x86_avx2_pminu_d:
12063       Opcode = X86ISD::UMIN;
12064       break;
12065     case Intrinsic::x86_sse41_pmaxsb:
12066     case Intrinsic::x86_sse2_pmaxs_w:
12067     case Intrinsic::x86_sse41_pmaxsd:
12068     case Intrinsic::x86_avx2_pmaxs_b:
12069     case Intrinsic::x86_avx2_pmaxs_w:
12070     case Intrinsic::x86_avx2_pmaxs_d:
12071       Opcode = X86ISD::SMAX;
12072       break;
12073     case Intrinsic::x86_sse41_pminsb:
12074     case Intrinsic::x86_sse2_pmins_w:
12075     case Intrinsic::x86_sse41_pminsd:
12076     case Intrinsic::x86_avx2_pmins_b:
12077     case Intrinsic::x86_avx2_pmins_w:
12078     case Intrinsic::x86_avx2_pmins_d:
12079       Opcode = X86ISD::SMIN;
12080       break;
12081     }
12082     return DAG.getNode(Opcode, dl, Op.getValueType(),
12083                        Op.getOperand(1), Op.getOperand(2));
12084   }
12085
12086   // SSE/SSE2/AVX floating point max/min intrinsics.
12087   case Intrinsic::x86_sse_max_ps:
12088   case Intrinsic::x86_sse2_max_pd:
12089   case Intrinsic::x86_avx_max_ps_256:
12090   case Intrinsic::x86_avx_max_pd_256:
12091   case Intrinsic::x86_sse_min_ps:
12092   case Intrinsic::x86_sse2_min_pd:
12093   case Intrinsic::x86_avx_min_ps_256:
12094   case Intrinsic::x86_avx_min_pd_256: {
12095     unsigned Opcode;
12096     switch (IntNo) {
12097     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12098     case Intrinsic::x86_sse_max_ps:
12099     case Intrinsic::x86_sse2_max_pd:
12100     case Intrinsic::x86_avx_max_ps_256:
12101     case Intrinsic::x86_avx_max_pd_256:
12102       Opcode = X86ISD::FMAX;
12103       break;
12104     case Intrinsic::x86_sse_min_ps:
12105     case Intrinsic::x86_sse2_min_pd:
12106     case Intrinsic::x86_avx_min_ps_256:
12107     case Intrinsic::x86_avx_min_pd_256:
12108       Opcode = X86ISD::FMIN;
12109       break;
12110     }
12111     return DAG.getNode(Opcode, dl, Op.getValueType(),
12112                        Op.getOperand(1), Op.getOperand(2));
12113   }
12114
12115   // AVX2 variable shift intrinsics
12116   case Intrinsic::x86_avx2_psllv_d:
12117   case Intrinsic::x86_avx2_psllv_q:
12118   case Intrinsic::x86_avx2_psllv_d_256:
12119   case Intrinsic::x86_avx2_psllv_q_256:
12120   case Intrinsic::x86_avx2_psrlv_d:
12121   case Intrinsic::x86_avx2_psrlv_q:
12122   case Intrinsic::x86_avx2_psrlv_d_256:
12123   case Intrinsic::x86_avx2_psrlv_q_256:
12124   case Intrinsic::x86_avx2_psrav_d:
12125   case Intrinsic::x86_avx2_psrav_d_256: {
12126     unsigned Opcode;
12127     switch (IntNo) {
12128     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12129     case Intrinsic::x86_avx2_psllv_d:
12130     case Intrinsic::x86_avx2_psllv_q:
12131     case Intrinsic::x86_avx2_psllv_d_256:
12132     case Intrinsic::x86_avx2_psllv_q_256:
12133       Opcode = ISD::SHL;
12134       break;
12135     case Intrinsic::x86_avx2_psrlv_d:
12136     case Intrinsic::x86_avx2_psrlv_q:
12137     case Intrinsic::x86_avx2_psrlv_d_256:
12138     case Intrinsic::x86_avx2_psrlv_q_256:
12139       Opcode = ISD::SRL;
12140       break;
12141     case Intrinsic::x86_avx2_psrav_d:
12142     case Intrinsic::x86_avx2_psrav_d_256:
12143       Opcode = ISD::SRA;
12144       break;
12145     }
12146     return DAG.getNode(Opcode, dl, Op.getValueType(),
12147                        Op.getOperand(1), Op.getOperand(2));
12148   }
12149
12150   case Intrinsic::x86_ssse3_pshuf_b_128:
12151   case Intrinsic::x86_avx2_pshuf_b:
12152     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12153                        Op.getOperand(1), Op.getOperand(2));
12154
12155   case Intrinsic::x86_ssse3_psign_b_128:
12156   case Intrinsic::x86_ssse3_psign_w_128:
12157   case Intrinsic::x86_ssse3_psign_d_128:
12158   case Intrinsic::x86_avx2_psign_b:
12159   case Intrinsic::x86_avx2_psign_w:
12160   case Intrinsic::x86_avx2_psign_d:
12161     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12162                        Op.getOperand(1), Op.getOperand(2));
12163
12164   case Intrinsic::x86_sse41_insertps:
12165     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12166                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12167
12168   case Intrinsic::x86_avx_vperm2f128_ps_256:
12169   case Intrinsic::x86_avx_vperm2f128_pd_256:
12170   case Intrinsic::x86_avx_vperm2f128_si_256:
12171   case Intrinsic::x86_avx2_vperm2i128:
12172     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12173                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12174
12175   case Intrinsic::x86_avx2_permd:
12176   case Intrinsic::x86_avx2_permps:
12177     // Operands intentionally swapped. Mask is last operand to intrinsic,
12178     // but second operand for node/instruction.
12179     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12180                        Op.getOperand(2), Op.getOperand(1));
12181
12182   case Intrinsic::x86_sse_sqrt_ps:
12183   case Intrinsic::x86_sse2_sqrt_pd:
12184   case Intrinsic::x86_avx_sqrt_ps_256:
12185   case Intrinsic::x86_avx_sqrt_pd_256:
12186     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12187
12188   // ptest and testp intrinsics. The intrinsic these come from are designed to
12189   // return an integer value, not just an instruction so lower it to the ptest
12190   // or testp pattern and a setcc for the result.
12191   case Intrinsic::x86_sse41_ptestz:
12192   case Intrinsic::x86_sse41_ptestc:
12193   case Intrinsic::x86_sse41_ptestnzc:
12194   case Intrinsic::x86_avx_ptestz_256:
12195   case Intrinsic::x86_avx_ptestc_256:
12196   case Intrinsic::x86_avx_ptestnzc_256:
12197   case Intrinsic::x86_avx_vtestz_ps:
12198   case Intrinsic::x86_avx_vtestc_ps:
12199   case Intrinsic::x86_avx_vtestnzc_ps:
12200   case Intrinsic::x86_avx_vtestz_pd:
12201   case Intrinsic::x86_avx_vtestc_pd:
12202   case Intrinsic::x86_avx_vtestnzc_pd:
12203   case Intrinsic::x86_avx_vtestz_ps_256:
12204   case Intrinsic::x86_avx_vtestc_ps_256:
12205   case Intrinsic::x86_avx_vtestnzc_ps_256:
12206   case Intrinsic::x86_avx_vtestz_pd_256:
12207   case Intrinsic::x86_avx_vtestc_pd_256:
12208   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12209     bool IsTestPacked = false;
12210     unsigned X86CC;
12211     switch (IntNo) {
12212     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12213     case Intrinsic::x86_avx_vtestz_ps:
12214     case Intrinsic::x86_avx_vtestz_pd:
12215     case Intrinsic::x86_avx_vtestz_ps_256:
12216     case Intrinsic::x86_avx_vtestz_pd_256:
12217       IsTestPacked = true; // Fallthrough
12218     case Intrinsic::x86_sse41_ptestz:
12219     case Intrinsic::x86_avx_ptestz_256:
12220       // ZF = 1
12221       X86CC = X86::COND_E;
12222       break;
12223     case Intrinsic::x86_avx_vtestc_ps:
12224     case Intrinsic::x86_avx_vtestc_pd:
12225     case Intrinsic::x86_avx_vtestc_ps_256:
12226     case Intrinsic::x86_avx_vtestc_pd_256:
12227       IsTestPacked = true; // Fallthrough
12228     case Intrinsic::x86_sse41_ptestc:
12229     case Intrinsic::x86_avx_ptestc_256:
12230       // CF = 1
12231       X86CC = X86::COND_B;
12232       break;
12233     case Intrinsic::x86_avx_vtestnzc_ps:
12234     case Intrinsic::x86_avx_vtestnzc_pd:
12235     case Intrinsic::x86_avx_vtestnzc_ps_256:
12236     case Intrinsic::x86_avx_vtestnzc_pd_256:
12237       IsTestPacked = true; // Fallthrough
12238     case Intrinsic::x86_sse41_ptestnzc:
12239     case Intrinsic::x86_avx_ptestnzc_256:
12240       // ZF and CF = 0
12241       X86CC = X86::COND_A;
12242       break;
12243     }
12244
12245     SDValue LHS = Op.getOperand(1);
12246     SDValue RHS = Op.getOperand(2);
12247     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12248     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12249     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12250     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12251     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12252   }
12253   case Intrinsic::x86_avx512_kortestz_w:
12254   case Intrinsic::x86_avx512_kortestc_w: {
12255     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12256     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12257     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12258     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12259     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12260     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12261     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12262   }
12263
12264   // SSE/AVX shift intrinsics
12265   case Intrinsic::x86_sse2_psll_w:
12266   case Intrinsic::x86_sse2_psll_d:
12267   case Intrinsic::x86_sse2_psll_q:
12268   case Intrinsic::x86_avx2_psll_w:
12269   case Intrinsic::x86_avx2_psll_d:
12270   case Intrinsic::x86_avx2_psll_q:
12271   case Intrinsic::x86_sse2_psrl_w:
12272   case Intrinsic::x86_sse2_psrl_d:
12273   case Intrinsic::x86_sse2_psrl_q:
12274   case Intrinsic::x86_avx2_psrl_w:
12275   case Intrinsic::x86_avx2_psrl_d:
12276   case Intrinsic::x86_avx2_psrl_q:
12277   case Intrinsic::x86_sse2_psra_w:
12278   case Intrinsic::x86_sse2_psra_d:
12279   case Intrinsic::x86_avx2_psra_w:
12280   case Intrinsic::x86_avx2_psra_d: {
12281     unsigned Opcode;
12282     switch (IntNo) {
12283     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12284     case Intrinsic::x86_sse2_psll_w:
12285     case Intrinsic::x86_sse2_psll_d:
12286     case Intrinsic::x86_sse2_psll_q:
12287     case Intrinsic::x86_avx2_psll_w:
12288     case Intrinsic::x86_avx2_psll_d:
12289     case Intrinsic::x86_avx2_psll_q:
12290       Opcode = X86ISD::VSHL;
12291       break;
12292     case Intrinsic::x86_sse2_psrl_w:
12293     case Intrinsic::x86_sse2_psrl_d:
12294     case Intrinsic::x86_sse2_psrl_q:
12295     case Intrinsic::x86_avx2_psrl_w:
12296     case Intrinsic::x86_avx2_psrl_d:
12297     case Intrinsic::x86_avx2_psrl_q:
12298       Opcode = X86ISD::VSRL;
12299       break;
12300     case Intrinsic::x86_sse2_psra_w:
12301     case Intrinsic::x86_sse2_psra_d:
12302     case Intrinsic::x86_avx2_psra_w:
12303     case Intrinsic::x86_avx2_psra_d:
12304       Opcode = X86ISD::VSRA;
12305       break;
12306     }
12307     return DAG.getNode(Opcode, dl, Op.getValueType(),
12308                        Op.getOperand(1), Op.getOperand(2));
12309   }
12310
12311   // SSE/AVX immediate shift intrinsics
12312   case Intrinsic::x86_sse2_pslli_w:
12313   case Intrinsic::x86_sse2_pslli_d:
12314   case Intrinsic::x86_sse2_pslli_q:
12315   case Intrinsic::x86_avx2_pslli_w:
12316   case Intrinsic::x86_avx2_pslli_d:
12317   case Intrinsic::x86_avx2_pslli_q:
12318   case Intrinsic::x86_sse2_psrli_w:
12319   case Intrinsic::x86_sse2_psrli_d:
12320   case Intrinsic::x86_sse2_psrli_q:
12321   case Intrinsic::x86_avx2_psrli_w:
12322   case Intrinsic::x86_avx2_psrli_d:
12323   case Intrinsic::x86_avx2_psrli_q:
12324   case Intrinsic::x86_sse2_psrai_w:
12325   case Intrinsic::x86_sse2_psrai_d:
12326   case Intrinsic::x86_avx2_psrai_w:
12327   case Intrinsic::x86_avx2_psrai_d: {
12328     unsigned Opcode;
12329     switch (IntNo) {
12330     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12331     case Intrinsic::x86_sse2_pslli_w:
12332     case Intrinsic::x86_sse2_pslli_d:
12333     case Intrinsic::x86_sse2_pslli_q:
12334     case Intrinsic::x86_avx2_pslli_w:
12335     case Intrinsic::x86_avx2_pslli_d:
12336     case Intrinsic::x86_avx2_pslli_q:
12337       Opcode = X86ISD::VSHLI;
12338       break;
12339     case Intrinsic::x86_sse2_psrli_w:
12340     case Intrinsic::x86_sse2_psrli_d:
12341     case Intrinsic::x86_sse2_psrli_q:
12342     case Intrinsic::x86_avx2_psrli_w:
12343     case Intrinsic::x86_avx2_psrli_d:
12344     case Intrinsic::x86_avx2_psrli_q:
12345       Opcode = X86ISD::VSRLI;
12346       break;
12347     case Intrinsic::x86_sse2_psrai_w:
12348     case Intrinsic::x86_sse2_psrai_d:
12349     case Intrinsic::x86_avx2_psrai_w:
12350     case Intrinsic::x86_avx2_psrai_d:
12351       Opcode = X86ISD::VSRAI;
12352       break;
12353     }
12354     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12355                                Op.getOperand(1), Op.getOperand(2), DAG);
12356   }
12357
12358   case Intrinsic::x86_sse42_pcmpistria128:
12359   case Intrinsic::x86_sse42_pcmpestria128:
12360   case Intrinsic::x86_sse42_pcmpistric128:
12361   case Intrinsic::x86_sse42_pcmpestric128:
12362   case Intrinsic::x86_sse42_pcmpistrio128:
12363   case Intrinsic::x86_sse42_pcmpestrio128:
12364   case Intrinsic::x86_sse42_pcmpistris128:
12365   case Intrinsic::x86_sse42_pcmpestris128:
12366   case Intrinsic::x86_sse42_pcmpistriz128:
12367   case Intrinsic::x86_sse42_pcmpestriz128: {
12368     unsigned Opcode;
12369     unsigned X86CC;
12370     switch (IntNo) {
12371     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12372     case Intrinsic::x86_sse42_pcmpistria128:
12373       Opcode = X86ISD::PCMPISTRI;
12374       X86CC = X86::COND_A;
12375       break;
12376     case Intrinsic::x86_sse42_pcmpestria128:
12377       Opcode = X86ISD::PCMPESTRI;
12378       X86CC = X86::COND_A;
12379       break;
12380     case Intrinsic::x86_sse42_pcmpistric128:
12381       Opcode = X86ISD::PCMPISTRI;
12382       X86CC = X86::COND_B;
12383       break;
12384     case Intrinsic::x86_sse42_pcmpestric128:
12385       Opcode = X86ISD::PCMPESTRI;
12386       X86CC = X86::COND_B;
12387       break;
12388     case Intrinsic::x86_sse42_pcmpistrio128:
12389       Opcode = X86ISD::PCMPISTRI;
12390       X86CC = X86::COND_O;
12391       break;
12392     case Intrinsic::x86_sse42_pcmpestrio128:
12393       Opcode = X86ISD::PCMPESTRI;
12394       X86CC = X86::COND_O;
12395       break;
12396     case Intrinsic::x86_sse42_pcmpistris128:
12397       Opcode = X86ISD::PCMPISTRI;
12398       X86CC = X86::COND_S;
12399       break;
12400     case Intrinsic::x86_sse42_pcmpestris128:
12401       Opcode = X86ISD::PCMPESTRI;
12402       X86CC = X86::COND_S;
12403       break;
12404     case Intrinsic::x86_sse42_pcmpistriz128:
12405       Opcode = X86ISD::PCMPISTRI;
12406       X86CC = X86::COND_E;
12407       break;
12408     case Intrinsic::x86_sse42_pcmpestriz128:
12409       Opcode = X86ISD::PCMPESTRI;
12410       X86CC = X86::COND_E;
12411       break;
12412     }
12413     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12414     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12415     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12416     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12417                                 DAG.getConstant(X86CC, MVT::i8),
12418                                 SDValue(PCMP.getNode(), 1));
12419     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12420   }
12421
12422   case Intrinsic::x86_sse42_pcmpistri128:
12423   case Intrinsic::x86_sse42_pcmpestri128: {
12424     unsigned Opcode;
12425     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12426       Opcode = X86ISD::PCMPISTRI;
12427     else
12428       Opcode = X86ISD::PCMPESTRI;
12429
12430     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12431     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12432     return DAG.getNode(Opcode, dl, VTs, NewOps);
12433   }
12434   case Intrinsic::x86_fma_vfmadd_ps:
12435   case Intrinsic::x86_fma_vfmadd_pd:
12436   case Intrinsic::x86_fma_vfmsub_ps:
12437   case Intrinsic::x86_fma_vfmsub_pd:
12438   case Intrinsic::x86_fma_vfnmadd_ps:
12439   case Intrinsic::x86_fma_vfnmadd_pd:
12440   case Intrinsic::x86_fma_vfnmsub_ps:
12441   case Intrinsic::x86_fma_vfnmsub_pd:
12442   case Intrinsic::x86_fma_vfmaddsub_ps:
12443   case Intrinsic::x86_fma_vfmaddsub_pd:
12444   case Intrinsic::x86_fma_vfmsubadd_ps:
12445   case Intrinsic::x86_fma_vfmsubadd_pd:
12446   case Intrinsic::x86_fma_vfmadd_ps_256:
12447   case Intrinsic::x86_fma_vfmadd_pd_256:
12448   case Intrinsic::x86_fma_vfmsub_ps_256:
12449   case Intrinsic::x86_fma_vfmsub_pd_256:
12450   case Intrinsic::x86_fma_vfnmadd_ps_256:
12451   case Intrinsic::x86_fma_vfnmadd_pd_256:
12452   case Intrinsic::x86_fma_vfnmsub_ps_256:
12453   case Intrinsic::x86_fma_vfnmsub_pd_256:
12454   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12455   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12456   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12457   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12458   case Intrinsic::x86_fma_vfmadd_ps_512:
12459   case Intrinsic::x86_fma_vfmadd_pd_512:
12460   case Intrinsic::x86_fma_vfmsub_ps_512:
12461   case Intrinsic::x86_fma_vfmsub_pd_512:
12462   case Intrinsic::x86_fma_vfnmadd_ps_512:
12463   case Intrinsic::x86_fma_vfnmadd_pd_512:
12464   case Intrinsic::x86_fma_vfnmsub_ps_512:
12465   case Intrinsic::x86_fma_vfnmsub_pd_512:
12466   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12467   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12468   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12469   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12470     unsigned Opc;
12471     switch (IntNo) {
12472     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12473     case Intrinsic::x86_fma_vfmadd_ps:
12474     case Intrinsic::x86_fma_vfmadd_pd:
12475     case Intrinsic::x86_fma_vfmadd_ps_256:
12476     case Intrinsic::x86_fma_vfmadd_pd_256:
12477     case Intrinsic::x86_fma_vfmadd_ps_512:
12478     case Intrinsic::x86_fma_vfmadd_pd_512:
12479       Opc = X86ISD::FMADD;
12480       break;
12481     case Intrinsic::x86_fma_vfmsub_ps:
12482     case Intrinsic::x86_fma_vfmsub_pd:
12483     case Intrinsic::x86_fma_vfmsub_ps_256:
12484     case Intrinsic::x86_fma_vfmsub_pd_256:
12485     case Intrinsic::x86_fma_vfmsub_ps_512:
12486     case Intrinsic::x86_fma_vfmsub_pd_512:
12487       Opc = X86ISD::FMSUB;
12488       break;
12489     case Intrinsic::x86_fma_vfnmadd_ps:
12490     case Intrinsic::x86_fma_vfnmadd_pd:
12491     case Intrinsic::x86_fma_vfnmadd_ps_256:
12492     case Intrinsic::x86_fma_vfnmadd_pd_256:
12493     case Intrinsic::x86_fma_vfnmadd_ps_512:
12494     case Intrinsic::x86_fma_vfnmadd_pd_512:
12495       Opc = X86ISD::FNMADD;
12496       break;
12497     case Intrinsic::x86_fma_vfnmsub_ps:
12498     case Intrinsic::x86_fma_vfnmsub_pd:
12499     case Intrinsic::x86_fma_vfnmsub_ps_256:
12500     case Intrinsic::x86_fma_vfnmsub_pd_256:
12501     case Intrinsic::x86_fma_vfnmsub_ps_512:
12502     case Intrinsic::x86_fma_vfnmsub_pd_512:
12503       Opc = X86ISD::FNMSUB;
12504       break;
12505     case Intrinsic::x86_fma_vfmaddsub_ps:
12506     case Intrinsic::x86_fma_vfmaddsub_pd:
12507     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12508     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12509     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12510     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12511       Opc = X86ISD::FMADDSUB;
12512       break;
12513     case Intrinsic::x86_fma_vfmsubadd_ps:
12514     case Intrinsic::x86_fma_vfmsubadd_pd:
12515     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12516     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12517     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12518     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12519       Opc = X86ISD::FMSUBADD;
12520       break;
12521     }
12522
12523     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12524                        Op.getOperand(2), Op.getOperand(3));
12525   }
12526   }
12527 }
12528
12529 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12530                               SDValue Src, SDValue Mask, SDValue Base,
12531                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12532                               const X86Subtarget * Subtarget) {
12533   SDLoc dl(Op);
12534   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12535   assert(C && "Invalid scale type");
12536   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12537   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12538                              Index.getSimpleValueType().getVectorNumElements());
12539   SDValue MaskInReg;
12540   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12541   if (MaskC)
12542     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12543   else
12544     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12545   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12546   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12547   SDValue Segment = DAG.getRegister(0, MVT::i32);
12548   if (Src.getOpcode() == ISD::UNDEF)
12549     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12550   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12551   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12552   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12553   return DAG.getMergeValues(RetOps, dl);
12554 }
12555
12556 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12557                                SDValue Src, SDValue Mask, SDValue Base,
12558                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12559   SDLoc dl(Op);
12560   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12561   assert(C && "Invalid scale type");
12562   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12563   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12564   SDValue Segment = DAG.getRegister(0, MVT::i32);
12565   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12566                              Index.getSimpleValueType().getVectorNumElements());
12567   SDValue MaskInReg;
12568   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12569   if (MaskC)
12570     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12571   else
12572     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12573   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12574   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12575   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12576   return SDValue(Res, 1);
12577 }
12578
12579 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12580                                SDValue Mask, SDValue Base, SDValue Index,
12581                                SDValue ScaleOp, SDValue Chain) {
12582   SDLoc dl(Op);
12583   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12584   assert(C && "Invalid scale type");
12585   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12586   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12587   SDValue Segment = DAG.getRegister(0, MVT::i32);
12588   EVT MaskVT =
12589     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12590   SDValue MaskInReg;
12591   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12592   if (MaskC)
12593     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12594   else
12595     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12596   //SDVTList VTs = DAG.getVTList(MVT::Other);
12597   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12598   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12599   return SDValue(Res, 0);
12600 }
12601
12602 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12603 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12604 // also used to custom lower READCYCLECOUNTER nodes.
12605 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12606                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12607                               SmallVectorImpl<SDValue> &Results) {
12608   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12609   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12610   SDValue LO, HI;
12611
12612   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12613   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12614   // and the EAX register is loaded with the low-order 32 bits.
12615   if (Subtarget->is64Bit()) {
12616     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12617     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12618                             LO.getValue(2));
12619   } else {
12620     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12621     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12622                             LO.getValue(2));
12623   }
12624   SDValue Chain = HI.getValue(1);
12625
12626   if (Opcode == X86ISD::RDTSCP_DAG) {
12627     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12628
12629     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12630     // the ECX register. Add 'ecx' explicitly to the chain.
12631     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12632                                      HI.getValue(2));
12633     // Explicitly store the content of ECX at the location passed in input
12634     // to the 'rdtscp' intrinsic.
12635     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12636                          MachinePointerInfo(), false, false, 0);
12637   }
12638
12639   if (Subtarget->is64Bit()) {
12640     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12641     // the EAX register is loaded with the low-order 32 bits.
12642     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12643                               DAG.getConstant(32, MVT::i8));
12644     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12645     Results.push_back(Chain);
12646     return;
12647   }
12648
12649   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12650   SDValue Ops[] = { LO, HI };
12651   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12652   Results.push_back(Pair);
12653   Results.push_back(Chain);
12654 }
12655
12656 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12657                                      SelectionDAG &DAG) {
12658   SmallVector<SDValue, 2> Results;
12659   SDLoc DL(Op);
12660   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12661                           Results);
12662   return DAG.getMergeValues(Results, DL);
12663 }
12664
12665 enum IntrinsicType {
12666   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12667 };
12668
12669 struct IntrinsicData {
12670   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12671     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12672   IntrinsicType Type;
12673   unsigned      Opc0;
12674   unsigned      Opc1;
12675 };
12676
12677 std::map < unsigned, IntrinsicData> IntrMap;
12678 static void InitIntinsicsMap() {
12679   static bool Initialized = false;
12680   if (Initialized) 
12681     return;
12682   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12683                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12684   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12685                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12686   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12687                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12688   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12689                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12690   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12691                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12692   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12693                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12694   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12695                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12696   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12697                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12698   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12699                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12700
12701   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12702                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12703   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12704                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12705   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12706                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12707   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12708                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12709   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12710                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12711   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12712                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12713   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12714                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12715   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12716                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12717    
12718   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12719                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12720                                                         X86::VGATHERPF1QPSm)));
12721   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12722                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12723                                                         X86::VGATHERPF1QPDm)));
12724   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12725                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12726                                                         X86::VGATHERPF1DPDm)));
12727   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12728                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12729                                                         X86::VGATHERPF1DPSm)));
12730   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12731                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12732                                                         X86::VSCATTERPF1QPSm)));
12733   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12734                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12735                                                         X86::VSCATTERPF1QPDm)));
12736   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12737                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12738                                                         X86::VSCATTERPF1DPDm)));
12739   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12740                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12741                                                         X86::VSCATTERPF1DPSm)));
12742   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12743                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12744   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12745                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12746   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12747                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12748   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12749                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12750   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12751                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12752   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12753                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12754   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12755                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12756   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12757                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12758   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12759                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12760   Initialized = true;
12761 }
12762
12763 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12764                                       SelectionDAG &DAG) {
12765   InitIntinsicsMap();
12766   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12767   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12768   if (itr == IntrMap.end())
12769     return SDValue();
12770
12771   SDLoc dl(Op);
12772   IntrinsicData Intr = itr->second;
12773   switch(Intr.Type) {
12774   case RDSEED:
12775   case RDRAND: {
12776     // Emit the node with the right value type.
12777     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12778     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12779
12780     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12781     // Otherwise return the value from Rand, which is always 0, casted to i32.
12782     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12783                       DAG.getConstant(1, Op->getValueType(1)),
12784                       DAG.getConstant(X86::COND_B, MVT::i32),
12785                       SDValue(Result.getNode(), 1) };
12786     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12787                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12788                                   Ops);
12789
12790     // Return { result, isValid, chain }.
12791     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12792                        SDValue(Result.getNode(), 2));
12793   }
12794   case GATHER: {
12795   //gather(v1, mask, index, base, scale);
12796     SDValue Chain = Op.getOperand(0);
12797     SDValue Src   = Op.getOperand(2);
12798     SDValue Base  = Op.getOperand(3);
12799     SDValue Index = Op.getOperand(4);
12800     SDValue Mask  = Op.getOperand(5);
12801     SDValue Scale = Op.getOperand(6);
12802     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12803                           Subtarget);
12804   }
12805   case SCATTER: {
12806   //scatter(base, mask, index, v1, scale);
12807     SDValue Chain = Op.getOperand(0);
12808     SDValue Base  = Op.getOperand(2);
12809     SDValue Mask  = Op.getOperand(3);
12810     SDValue Index = Op.getOperand(4);
12811     SDValue Src   = Op.getOperand(5);
12812     SDValue Scale = Op.getOperand(6);
12813     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12814   }
12815   case PREFETCH: {
12816     SDValue Hint = Op.getOperand(6);
12817     unsigned HintVal;
12818     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12819         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12820       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12821     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12822     SDValue Chain = Op.getOperand(0);
12823     SDValue Mask  = Op.getOperand(2);
12824     SDValue Index = Op.getOperand(3);
12825     SDValue Base  = Op.getOperand(4);
12826     SDValue Scale = Op.getOperand(5);
12827     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12828   }
12829   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12830   case RDTSC: {
12831     SmallVector<SDValue, 2> Results;
12832     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12833     return DAG.getMergeValues(Results, dl);
12834   }
12835   // XTEST intrinsics.
12836   case XTEST: {
12837     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12838     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12839     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12840                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12841                                 InTrans);
12842     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12843     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12844                        Ret, SDValue(InTrans.getNode(), 1));
12845   }
12846   }
12847   llvm_unreachable("Unknown Intrinsic Type");
12848 }
12849
12850 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12851                                            SelectionDAG &DAG) const {
12852   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12853   MFI->setReturnAddressIsTaken(true);
12854
12855   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12856     return SDValue();
12857
12858   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12859   SDLoc dl(Op);
12860   EVT PtrVT = getPointerTy();
12861
12862   if (Depth > 0) {
12863     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12864     const X86RegisterInfo *RegInfo =
12865       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12866     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12867     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12868                        DAG.getNode(ISD::ADD, dl, PtrVT,
12869                                    FrameAddr, Offset),
12870                        MachinePointerInfo(), false, false, false, 0);
12871   }
12872
12873   // Just load the return address.
12874   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12875   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12876                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12877 }
12878
12879 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12880   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12881   MFI->setFrameAddressIsTaken(true);
12882
12883   EVT VT = Op.getValueType();
12884   SDLoc dl(Op);  // FIXME probably not meaningful
12885   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12886   const X86RegisterInfo *RegInfo =
12887     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12888   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12889   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12890           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12891          "Invalid Frame Register!");
12892   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12893   while (Depth--)
12894     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12895                             MachinePointerInfo(),
12896                             false, false, false, 0);
12897   return FrameAddr;
12898 }
12899
12900 // FIXME? Maybe this could be a TableGen attribute on some registers and
12901 // this table could be generated automatically from RegInfo.
12902 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12903                                               EVT VT) const {
12904   unsigned Reg = StringSwitch<unsigned>(RegName)
12905                        .Case("esp", X86::ESP)
12906                        .Case("rsp", X86::RSP)
12907                        .Default(0);
12908   if (Reg)
12909     return Reg;
12910   report_fatal_error("Invalid register name global variable");
12911 }
12912
12913 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12914                                                      SelectionDAG &DAG) const {
12915   const X86RegisterInfo *RegInfo =
12916     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12917   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12918 }
12919
12920 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12921   SDValue Chain     = Op.getOperand(0);
12922   SDValue Offset    = Op.getOperand(1);
12923   SDValue Handler   = Op.getOperand(2);
12924   SDLoc dl      (Op);
12925
12926   EVT PtrVT = getPointerTy();
12927   const X86RegisterInfo *RegInfo =
12928     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12929   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12930   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12931           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12932          "Invalid Frame Register!");
12933   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12934   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12935
12936   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12937                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12938   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12939   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12940                        false, false, 0);
12941   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12942
12943   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12944                      DAG.getRegister(StoreAddrReg, PtrVT));
12945 }
12946
12947 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12948                                                SelectionDAG &DAG) const {
12949   SDLoc DL(Op);
12950   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12951                      DAG.getVTList(MVT::i32, MVT::Other),
12952                      Op.getOperand(0), Op.getOperand(1));
12953 }
12954
12955 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12956                                                 SelectionDAG &DAG) const {
12957   SDLoc DL(Op);
12958   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12959                      Op.getOperand(0), Op.getOperand(1));
12960 }
12961
12962 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12963   return Op.getOperand(0);
12964 }
12965
12966 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12967                                                 SelectionDAG &DAG) const {
12968   SDValue Root = Op.getOperand(0);
12969   SDValue Trmp = Op.getOperand(1); // trampoline
12970   SDValue FPtr = Op.getOperand(2); // nested function
12971   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12972   SDLoc dl (Op);
12973
12974   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12975   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12976
12977   if (Subtarget->is64Bit()) {
12978     SDValue OutChains[6];
12979
12980     // Large code-model.
12981     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12982     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12983
12984     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12985     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12986
12987     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12988
12989     // Load the pointer to the nested function into R11.
12990     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12991     SDValue Addr = Trmp;
12992     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12993                                 Addr, MachinePointerInfo(TrmpAddr),
12994                                 false, false, 0);
12995
12996     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12997                        DAG.getConstant(2, MVT::i64));
12998     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12999                                 MachinePointerInfo(TrmpAddr, 2),
13000                                 false, false, 2);
13001
13002     // Load the 'nest' parameter value into R10.
13003     // R10 is specified in X86CallingConv.td
13004     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13005     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13006                        DAG.getConstant(10, MVT::i64));
13007     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13008                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13009                                 false, false, 0);
13010
13011     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13012                        DAG.getConstant(12, MVT::i64));
13013     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13014                                 MachinePointerInfo(TrmpAddr, 12),
13015                                 false, false, 2);
13016
13017     // Jump to the nested function.
13018     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13019     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13020                        DAG.getConstant(20, MVT::i64));
13021     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13022                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13023                                 false, false, 0);
13024
13025     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13027                        DAG.getConstant(22, MVT::i64));
13028     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13029                                 MachinePointerInfo(TrmpAddr, 22),
13030                                 false, false, 0);
13031
13032     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13033   } else {
13034     const Function *Func =
13035       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13036     CallingConv::ID CC = Func->getCallingConv();
13037     unsigned NestReg;
13038
13039     switch (CC) {
13040     default:
13041       llvm_unreachable("Unsupported calling convention");
13042     case CallingConv::C:
13043     case CallingConv::X86_StdCall: {
13044       // Pass 'nest' parameter in ECX.
13045       // Must be kept in sync with X86CallingConv.td
13046       NestReg = X86::ECX;
13047
13048       // Check that ECX wasn't needed by an 'inreg' parameter.
13049       FunctionType *FTy = Func->getFunctionType();
13050       const AttributeSet &Attrs = Func->getAttributes();
13051
13052       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13053         unsigned InRegCount = 0;
13054         unsigned Idx = 1;
13055
13056         for (FunctionType::param_iterator I = FTy->param_begin(),
13057              E = FTy->param_end(); I != E; ++I, ++Idx)
13058           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13059             // FIXME: should only count parameters that are lowered to integers.
13060             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13061
13062         if (InRegCount > 2) {
13063           report_fatal_error("Nest register in use - reduce number of inreg"
13064                              " parameters!");
13065         }
13066       }
13067       break;
13068     }
13069     case CallingConv::X86_FastCall:
13070     case CallingConv::X86_ThisCall:
13071     case CallingConv::Fast:
13072       // Pass 'nest' parameter in EAX.
13073       // Must be kept in sync with X86CallingConv.td
13074       NestReg = X86::EAX;
13075       break;
13076     }
13077
13078     SDValue OutChains[4];
13079     SDValue Addr, Disp;
13080
13081     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13082                        DAG.getConstant(10, MVT::i32));
13083     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13084
13085     // This is storing the opcode for MOV32ri.
13086     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13087     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13088     OutChains[0] = DAG.getStore(Root, dl,
13089                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13090                                 Trmp, MachinePointerInfo(TrmpAddr),
13091                                 false, false, 0);
13092
13093     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13094                        DAG.getConstant(1, MVT::i32));
13095     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13096                                 MachinePointerInfo(TrmpAddr, 1),
13097                                 false, false, 1);
13098
13099     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13100     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13101                        DAG.getConstant(5, MVT::i32));
13102     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13103                                 MachinePointerInfo(TrmpAddr, 5),
13104                                 false, false, 1);
13105
13106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13107                        DAG.getConstant(6, MVT::i32));
13108     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13109                                 MachinePointerInfo(TrmpAddr, 6),
13110                                 false, false, 1);
13111
13112     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13113   }
13114 }
13115
13116 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13117                                             SelectionDAG &DAG) const {
13118   /*
13119    The rounding mode is in bits 11:10 of FPSR, and has the following
13120    settings:
13121      00 Round to nearest
13122      01 Round to -inf
13123      10 Round to +inf
13124      11 Round to 0
13125
13126   FLT_ROUNDS, on the other hand, expects the following:
13127     -1 Undefined
13128      0 Round to 0
13129      1 Round to nearest
13130      2 Round to +inf
13131      3 Round to -inf
13132
13133   To perform the conversion, we do:
13134     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13135   */
13136
13137   MachineFunction &MF = DAG.getMachineFunction();
13138   const TargetMachine &TM = MF.getTarget();
13139   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13140   unsigned StackAlignment = TFI.getStackAlignment();
13141   MVT VT = Op.getSimpleValueType();
13142   SDLoc DL(Op);
13143
13144   // Save FP Control Word to stack slot
13145   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13146   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13147
13148   MachineMemOperand *MMO =
13149    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13150                            MachineMemOperand::MOStore, 2, 2);
13151
13152   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13153   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13154                                           DAG.getVTList(MVT::Other),
13155                                           Ops, MVT::i16, MMO);
13156
13157   // Load FP Control Word from stack slot
13158   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13159                             MachinePointerInfo(), false, false, false, 0);
13160
13161   // Transform as necessary
13162   SDValue CWD1 =
13163     DAG.getNode(ISD::SRL, DL, MVT::i16,
13164                 DAG.getNode(ISD::AND, DL, MVT::i16,
13165                             CWD, DAG.getConstant(0x800, MVT::i16)),
13166                 DAG.getConstant(11, MVT::i8));
13167   SDValue CWD2 =
13168     DAG.getNode(ISD::SRL, DL, MVT::i16,
13169                 DAG.getNode(ISD::AND, DL, MVT::i16,
13170                             CWD, DAG.getConstant(0x400, MVT::i16)),
13171                 DAG.getConstant(9, MVT::i8));
13172
13173   SDValue RetVal =
13174     DAG.getNode(ISD::AND, DL, MVT::i16,
13175                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13176                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13177                             DAG.getConstant(1, MVT::i16)),
13178                 DAG.getConstant(3, MVT::i16));
13179
13180   return DAG.getNode((VT.getSizeInBits() < 16 ?
13181                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13182 }
13183
13184 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13185   MVT VT = Op.getSimpleValueType();
13186   EVT OpVT = VT;
13187   unsigned NumBits = VT.getSizeInBits();
13188   SDLoc dl(Op);
13189
13190   Op = Op.getOperand(0);
13191   if (VT == MVT::i8) {
13192     // Zero extend to i32 since there is not an i8 bsr.
13193     OpVT = MVT::i32;
13194     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13195   }
13196
13197   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13198   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13199   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13200
13201   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13202   SDValue Ops[] = {
13203     Op,
13204     DAG.getConstant(NumBits+NumBits-1, OpVT),
13205     DAG.getConstant(X86::COND_E, MVT::i8),
13206     Op.getValue(1)
13207   };
13208   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13209
13210   // Finally xor with NumBits-1.
13211   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13212
13213   if (VT == MVT::i8)
13214     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13215   return Op;
13216 }
13217
13218 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13219   MVT VT = Op.getSimpleValueType();
13220   EVT OpVT = VT;
13221   unsigned NumBits = VT.getSizeInBits();
13222   SDLoc dl(Op);
13223
13224   Op = Op.getOperand(0);
13225   if (VT == MVT::i8) {
13226     // Zero extend to i32 since there is not an i8 bsr.
13227     OpVT = MVT::i32;
13228     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13229   }
13230
13231   // Issue a bsr (scan bits in reverse).
13232   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13233   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13234
13235   // And xor with NumBits-1.
13236   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13237
13238   if (VT == MVT::i8)
13239     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13240   return Op;
13241 }
13242
13243 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13244   MVT VT = Op.getSimpleValueType();
13245   unsigned NumBits = VT.getSizeInBits();
13246   SDLoc dl(Op);
13247   Op = Op.getOperand(0);
13248
13249   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13250   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13251   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13252
13253   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13254   SDValue Ops[] = {
13255     Op,
13256     DAG.getConstant(NumBits, VT),
13257     DAG.getConstant(X86::COND_E, MVT::i8),
13258     Op.getValue(1)
13259   };
13260   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13261 }
13262
13263 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13264 // ones, and then concatenate the result back.
13265 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13266   MVT VT = Op.getSimpleValueType();
13267
13268   assert(VT.is256BitVector() && VT.isInteger() &&
13269          "Unsupported value type for operation");
13270
13271   unsigned NumElems = VT.getVectorNumElements();
13272   SDLoc dl(Op);
13273
13274   // Extract the LHS vectors
13275   SDValue LHS = Op.getOperand(0);
13276   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13277   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13278
13279   // Extract the RHS vectors
13280   SDValue RHS = Op.getOperand(1);
13281   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13282   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13283
13284   MVT EltVT = VT.getVectorElementType();
13285   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13286
13287   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13288                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13289                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13290 }
13291
13292 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13293   assert(Op.getSimpleValueType().is256BitVector() &&
13294          Op.getSimpleValueType().isInteger() &&
13295          "Only handle AVX 256-bit vector integer operation");
13296   return Lower256IntArith(Op, DAG);
13297 }
13298
13299 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13300   assert(Op.getSimpleValueType().is256BitVector() &&
13301          Op.getSimpleValueType().isInteger() &&
13302          "Only handle AVX 256-bit vector integer operation");
13303   return Lower256IntArith(Op, DAG);
13304 }
13305
13306 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13307                         SelectionDAG &DAG) {
13308   SDLoc dl(Op);
13309   MVT VT = Op.getSimpleValueType();
13310
13311   // Decompose 256-bit ops into smaller 128-bit ops.
13312   if (VT.is256BitVector() && !Subtarget->hasInt256())
13313     return Lower256IntArith(Op, DAG);
13314
13315   SDValue A = Op.getOperand(0);
13316   SDValue B = Op.getOperand(1);
13317
13318   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13319   if (VT == MVT::v4i32) {
13320     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13321            "Should not custom lower when pmuldq is available!");
13322
13323     // Extract the odd parts.
13324     static const int UnpackMask[] = { 1, -1, 3, -1 };
13325     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13326     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13327
13328     // Multiply the even parts.
13329     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13330     // Now multiply odd parts.
13331     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13332
13333     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13334     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13335
13336     // Merge the two vectors back together with a shuffle. This expands into 2
13337     // shuffles.
13338     static const int ShufMask[] = { 0, 4, 2, 6 };
13339     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13340   }
13341
13342   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13343          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13344
13345   //  Ahi = psrlqi(a, 32);
13346   //  Bhi = psrlqi(b, 32);
13347   //
13348   //  AloBlo = pmuludq(a, b);
13349   //  AloBhi = pmuludq(a, Bhi);
13350   //  AhiBlo = pmuludq(Ahi, b);
13351
13352   //  AloBhi = psllqi(AloBhi, 32);
13353   //  AhiBlo = psllqi(AhiBlo, 32);
13354   //  return AloBlo + AloBhi + AhiBlo;
13355
13356   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13357   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13358
13359   // Bit cast to 32-bit vectors for MULUDQ
13360   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13361                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13362   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13363   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13364   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13365   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13366
13367   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13368   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13369   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13370
13371   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13372   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13373
13374   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13375   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13376 }
13377
13378 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13379   assert(Subtarget->isTargetWin64() && "Unexpected target");
13380   EVT VT = Op.getValueType();
13381   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13382          "Unexpected return type for lowering");
13383
13384   RTLIB::Libcall LC;
13385   bool isSigned;
13386   switch (Op->getOpcode()) {
13387   default: llvm_unreachable("Unexpected request for libcall!");
13388   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13389   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13390   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13391   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13392   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13393   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13394   }
13395
13396   SDLoc dl(Op);
13397   SDValue InChain = DAG.getEntryNode();
13398
13399   TargetLowering::ArgListTy Args;
13400   TargetLowering::ArgListEntry Entry;
13401   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13402     EVT ArgVT = Op->getOperand(i).getValueType();
13403     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13404            "Unexpected argument type for lowering");
13405     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13406     Entry.Node = StackPtr;
13407     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13408                            false, false, 16);
13409     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13410     Entry.Ty = PointerType::get(ArgTy,0);
13411     Entry.isSExt = false;
13412     Entry.isZExt = false;
13413     Args.push_back(Entry);
13414   }
13415
13416   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13417                                          getPointerTy());
13418
13419   TargetLowering::CallLoweringInfo CLI(
13420       InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13421       isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13422       /*isTailCall=*/false,
13423       /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13424       dl);
13425   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13426
13427   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13428 }
13429
13430 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13431                              SelectionDAG &DAG) {
13432   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13433   EVT VT = Op0.getValueType();
13434   SDLoc dl(Op);
13435
13436   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13437          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13438
13439   // Get the high parts.
13440   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13441   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13442   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13443
13444   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13445   // ints.
13446   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13447   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13448   unsigned Opcode =
13449       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13450   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13451                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13452   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13453                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13454
13455   // Shuffle it back into the right order.
13456   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13457   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13458   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13459   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13460
13461   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13462   // unsigned multiply.
13463   if (IsSigned && !Subtarget->hasSSE41()) {
13464     SDValue ShAmt =
13465         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13466     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13467                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13468     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13469                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13470
13471     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13472     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13473   }
13474
13475   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13476 }
13477
13478 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13479                                          const X86Subtarget *Subtarget) {
13480   MVT VT = Op.getSimpleValueType();
13481   SDLoc dl(Op);
13482   SDValue R = Op.getOperand(0);
13483   SDValue Amt = Op.getOperand(1);
13484
13485   // Optimize shl/srl/sra with constant shift amount.
13486   if (isSplatVector(Amt.getNode())) {
13487     SDValue SclrAmt = Amt->getOperand(0);
13488     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13489       uint64_t ShiftAmt = C->getZExtValue();
13490
13491       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13492           (Subtarget->hasInt256() &&
13493            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13494           (Subtarget->hasAVX512() &&
13495            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13496         if (Op.getOpcode() == ISD::SHL)
13497           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13498                                             DAG);
13499         if (Op.getOpcode() == ISD::SRL)
13500           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13501                                             DAG);
13502         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13503           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13504                                             DAG);
13505       }
13506
13507       if (VT == MVT::v16i8) {
13508         if (Op.getOpcode() == ISD::SHL) {
13509           // Make a large shift.
13510           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13511                                                    MVT::v8i16, R, ShiftAmt,
13512                                                    DAG);
13513           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13514           // Zero out the rightmost bits.
13515           SmallVector<SDValue, 16> V(16,
13516                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13517                                                      MVT::i8));
13518           return DAG.getNode(ISD::AND, dl, VT, SHL,
13519                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13520         }
13521         if (Op.getOpcode() == ISD::SRL) {
13522           // Make a large shift.
13523           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13524                                                    MVT::v8i16, R, ShiftAmt,
13525                                                    DAG);
13526           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13527           // Zero out the leftmost bits.
13528           SmallVector<SDValue, 16> V(16,
13529                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13530                                                      MVT::i8));
13531           return DAG.getNode(ISD::AND, dl, VT, SRL,
13532                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13533         }
13534         if (Op.getOpcode() == ISD::SRA) {
13535           if (ShiftAmt == 7) {
13536             // R s>> 7  ===  R s< 0
13537             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13538             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13539           }
13540
13541           // R s>> a === ((R u>> a) ^ m) - m
13542           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13543           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13544                                                          MVT::i8));
13545           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13546           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13547           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13548           return Res;
13549         }
13550         llvm_unreachable("Unknown shift opcode.");
13551       }
13552
13553       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13554         if (Op.getOpcode() == ISD::SHL) {
13555           // Make a large shift.
13556           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13557                                                    MVT::v16i16, R, ShiftAmt,
13558                                                    DAG);
13559           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13560           // Zero out the rightmost bits.
13561           SmallVector<SDValue, 32> V(32,
13562                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13563                                                      MVT::i8));
13564           return DAG.getNode(ISD::AND, dl, VT, SHL,
13565                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13566         }
13567         if (Op.getOpcode() == ISD::SRL) {
13568           // Make a large shift.
13569           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13570                                                    MVT::v16i16, R, ShiftAmt,
13571                                                    DAG);
13572           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13573           // Zero out the leftmost bits.
13574           SmallVector<SDValue, 32> V(32,
13575                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13576                                                      MVT::i8));
13577           return DAG.getNode(ISD::AND, dl, VT, SRL,
13578                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13579         }
13580         if (Op.getOpcode() == ISD::SRA) {
13581           if (ShiftAmt == 7) {
13582             // R s>> 7  ===  R s< 0
13583             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13584             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13585           }
13586
13587           // R s>> a === ((R u>> a) ^ m) - m
13588           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13589           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13590                                                          MVT::i8));
13591           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13592           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13593           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13594           return Res;
13595         }
13596         llvm_unreachable("Unknown shift opcode.");
13597       }
13598     }
13599   }
13600
13601   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13602   if (!Subtarget->is64Bit() &&
13603       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13604       Amt.getOpcode() == ISD::BITCAST &&
13605       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13606     Amt = Amt.getOperand(0);
13607     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13608                      VT.getVectorNumElements();
13609     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13610     uint64_t ShiftAmt = 0;
13611     for (unsigned i = 0; i != Ratio; ++i) {
13612       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13613       if (!C)
13614         return SDValue();
13615       // 6 == Log2(64)
13616       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13617     }
13618     // Check remaining shift amounts.
13619     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13620       uint64_t ShAmt = 0;
13621       for (unsigned j = 0; j != Ratio; ++j) {
13622         ConstantSDNode *C =
13623           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13624         if (!C)
13625           return SDValue();
13626         // 6 == Log2(64)
13627         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13628       }
13629       if (ShAmt != ShiftAmt)
13630         return SDValue();
13631     }
13632     switch (Op.getOpcode()) {
13633     default:
13634       llvm_unreachable("Unknown shift opcode!");
13635     case ISD::SHL:
13636       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13637                                         DAG);
13638     case ISD::SRL:
13639       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13640                                         DAG);
13641     case ISD::SRA:
13642       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13643                                         DAG);
13644     }
13645   }
13646
13647   return SDValue();
13648 }
13649
13650 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13651                                         const X86Subtarget* Subtarget) {
13652   MVT VT = Op.getSimpleValueType();
13653   SDLoc dl(Op);
13654   SDValue R = Op.getOperand(0);
13655   SDValue Amt = Op.getOperand(1);
13656
13657   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13658       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13659       (Subtarget->hasInt256() &&
13660        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13661         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13662        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13663     SDValue BaseShAmt;
13664     EVT EltVT = VT.getVectorElementType();
13665
13666     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13667       unsigned NumElts = VT.getVectorNumElements();
13668       unsigned i, j;
13669       for (i = 0; i != NumElts; ++i) {
13670         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13671           continue;
13672         break;
13673       }
13674       for (j = i; j != NumElts; ++j) {
13675         SDValue Arg = Amt.getOperand(j);
13676         if (Arg.getOpcode() == ISD::UNDEF) continue;
13677         if (Arg != Amt.getOperand(i))
13678           break;
13679       }
13680       if (i != NumElts && j == NumElts)
13681         BaseShAmt = Amt.getOperand(i);
13682     } else {
13683       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13684         Amt = Amt.getOperand(0);
13685       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13686                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13687         SDValue InVec = Amt.getOperand(0);
13688         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13689           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13690           unsigned i = 0;
13691           for (; i != NumElts; ++i) {
13692             SDValue Arg = InVec.getOperand(i);
13693             if (Arg.getOpcode() == ISD::UNDEF) continue;
13694             BaseShAmt = Arg;
13695             break;
13696           }
13697         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13698            if (ConstantSDNode *C =
13699                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13700              unsigned SplatIdx =
13701                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13702              if (C->getZExtValue() == SplatIdx)
13703                BaseShAmt = InVec.getOperand(1);
13704            }
13705         }
13706         if (!BaseShAmt.getNode())
13707           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13708                                   DAG.getIntPtrConstant(0));
13709       }
13710     }
13711
13712     if (BaseShAmt.getNode()) {
13713       if (EltVT.bitsGT(MVT::i32))
13714         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13715       else if (EltVT.bitsLT(MVT::i32))
13716         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13717
13718       switch (Op.getOpcode()) {
13719       default:
13720         llvm_unreachable("Unknown shift opcode!");
13721       case ISD::SHL:
13722         switch (VT.SimpleTy) {
13723         default: return SDValue();
13724         case MVT::v2i64:
13725         case MVT::v4i32:
13726         case MVT::v8i16:
13727         case MVT::v4i64:
13728         case MVT::v8i32:
13729         case MVT::v16i16:
13730         case MVT::v16i32:
13731         case MVT::v8i64:
13732           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13733         }
13734       case ISD::SRA:
13735         switch (VT.SimpleTy) {
13736         default: return SDValue();
13737         case MVT::v4i32:
13738         case MVT::v8i16:
13739         case MVT::v8i32:
13740         case MVT::v16i16:
13741         case MVT::v16i32:
13742         case MVT::v8i64:
13743           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13744         }
13745       case ISD::SRL:
13746         switch (VT.SimpleTy) {
13747         default: return SDValue();
13748         case MVT::v2i64:
13749         case MVT::v4i32:
13750         case MVT::v8i16:
13751         case MVT::v4i64:
13752         case MVT::v8i32:
13753         case MVT::v16i16:
13754         case MVT::v16i32:
13755         case MVT::v8i64:
13756           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13757         }
13758       }
13759     }
13760   }
13761
13762   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13763   if (!Subtarget->is64Bit() &&
13764       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13765       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13766       Amt.getOpcode() == ISD::BITCAST &&
13767       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13768     Amt = Amt.getOperand(0);
13769     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13770                      VT.getVectorNumElements();
13771     std::vector<SDValue> Vals(Ratio);
13772     for (unsigned i = 0; i != Ratio; ++i)
13773       Vals[i] = Amt.getOperand(i);
13774     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13775       for (unsigned j = 0; j != Ratio; ++j)
13776         if (Vals[j] != Amt.getOperand(i + j))
13777           return SDValue();
13778     }
13779     switch (Op.getOpcode()) {
13780     default:
13781       llvm_unreachable("Unknown shift opcode!");
13782     case ISD::SHL:
13783       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13784     case ISD::SRL:
13785       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13786     case ISD::SRA:
13787       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13788     }
13789   }
13790
13791   return SDValue();
13792 }
13793
13794 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13795                           SelectionDAG &DAG) {
13796
13797   MVT VT = Op.getSimpleValueType();
13798   SDLoc dl(Op);
13799   SDValue R = Op.getOperand(0);
13800   SDValue Amt = Op.getOperand(1);
13801   SDValue V;
13802
13803   if (!Subtarget->hasSSE2())
13804     return SDValue();
13805
13806   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13807   if (V.getNode())
13808     return V;
13809
13810   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13811   if (V.getNode())
13812       return V;
13813
13814   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13815     return Op;
13816   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13817   if (Subtarget->hasInt256()) {
13818     if (Op.getOpcode() == ISD::SRL &&
13819         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13820          VT == MVT::v4i64 || VT == MVT::v8i32))
13821       return Op;
13822     if (Op.getOpcode() == ISD::SHL &&
13823         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13824          VT == MVT::v4i64 || VT == MVT::v8i32))
13825       return Op;
13826     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13827       return Op;
13828   }
13829
13830   // If possible, lower this packed shift into a vector multiply instead of
13831   // expanding it into a sequence of scalar shifts.
13832   // Do this only if the vector shift count is a constant build_vector.
13833   if (Op.getOpcode() == ISD::SHL && 
13834       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13835        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13836       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13837     SmallVector<SDValue, 8> Elts;
13838     EVT SVT = VT.getScalarType();
13839     unsigned SVTBits = SVT.getSizeInBits();
13840     const APInt &One = APInt(SVTBits, 1);
13841     unsigned NumElems = VT.getVectorNumElements();
13842
13843     for (unsigned i=0; i !=NumElems; ++i) {
13844       SDValue Op = Amt->getOperand(i);
13845       if (Op->getOpcode() == ISD::UNDEF) {
13846         Elts.push_back(Op);
13847         continue;
13848       }
13849
13850       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13851       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13852       uint64_t ShAmt = C.getZExtValue();
13853       if (ShAmt >= SVTBits) {
13854         Elts.push_back(DAG.getUNDEF(SVT));
13855         continue;
13856       }
13857       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13858     }
13859     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13860     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13861   }
13862
13863   // Lower SHL with variable shift amount.
13864   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13865     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13866
13867     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13868     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13869     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13870     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13871   }
13872
13873   // If possible, lower this shift as a sequence of two shifts by
13874   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13875   // Example:
13876   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13877   //
13878   // Could be rewritten as:
13879   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13880   //
13881   // The advantage is that the two shifts from the example would be
13882   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13883   // the vector shift into four scalar shifts plus four pairs of vector
13884   // insert/extract.
13885   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13886       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13887     unsigned TargetOpcode = X86ISD::MOVSS;
13888     bool CanBeSimplified;
13889     // The splat value for the first packed shift (the 'X' from the example).
13890     SDValue Amt1 = Amt->getOperand(0);
13891     // The splat value for the second packed shift (the 'Y' from the example).
13892     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13893                                         Amt->getOperand(2);
13894
13895     // See if it is possible to replace this node with a sequence of
13896     // two shifts followed by a MOVSS/MOVSD
13897     if (VT == MVT::v4i32) {
13898       // Check if it is legal to use a MOVSS.
13899       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13900                         Amt2 == Amt->getOperand(3);
13901       if (!CanBeSimplified) {
13902         // Otherwise, check if we can still simplify this node using a MOVSD.
13903         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13904                           Amt->getOperand(2) == Amt->getOperand(3);
13905         TargetOpcode = X86ISD::MOVSD;
13906         Amt2 = Amt->getOperand(2);
13907       }
13908     } else {
13909       // Do similar checks for the case where the machine value type
13910       // is MVT::v8i16.
13911       CanBeSimplified = Amt1 == Amt->getOperand(1);
13912       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13913         CanBeSimplified = Amt2 == Amt->getOperand(i);
13914
13915       if (!CanBeSimplified) {
13916         TargetOpcode = X86ISD::MOVSD;
13917         CanBeSimplified = true;
13918         Amt2 = Amt->getOperand(4);
13919         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13920           CanBeSimplified = Amt1 == Amt->getOperand(i);
13921         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13922           CanBeSimplified = Amt2 == Amt->getOperand(j);
13923       }
13924     }
13925     
13926     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13927         isa<ConstantSDNode>(Amt2)) {
13928       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13929       EVT CastVT = MVT::v4i32;
13930       SDValue Splat1 = 
13931         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13932       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13933       SDValue Splat2 = 
13934         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13935       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13936       if (TargetOpcode == X86ISD::MOVSD)
13937         CastVT = MVT::v2i64;
13938       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13939       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13940       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13941                                             BitCast1, DAG);
13942       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13943     }
13944   }
13945
13946   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13947     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13948
13949     // a = a << 5;
13950     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13951     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13952
13953     // Turn 'a' into a mask suitable for VSELECT
13954     SDValue VSelM = DAG.getConstant(0x80, VT);
13955     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13956     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13957
13958     SDValue CM1 = DAG.getConstant(0x0f, VT);
13959     SDValue CM2 = DAG.getConstant(0x3f, VT);
13960
13961     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13962     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13963     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13964     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13965     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13966
13967     // a += a
13968     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13969     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13970     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13971
13972     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13973     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13974     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13975     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13976     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13977
13978     // a += a
13979     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13980     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13981     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13982
13983     // return VSELECT(r, r+r, a);
13984     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13985                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13986     return R;
13987   }
13988
13989   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13990   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13991   // solution better.
13992   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13993     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13994     unsigned ExtOpc =
13995         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13996     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13997     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13998     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13999                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14000     }
14001
14002   // Decompose 256-bit shifts into smaller 128-bit shifts.
14003   if (VT.is256BitVector()) {
14004     unsigned NumElems = VT.getVectorNumElements();
14005     MVT EltVT = VT.getVectorElementType();
14006     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14007
14008     // Extract the two vectors
14009     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14010     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14011
14012     // Recreate the shift amount vectors
14013     SDValue Amt1, Amt2;
14014     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14015       // Constant shift amount
14016       SmallVector<SDValue, 4> Amt1Csts;
14017       SmallVector<SDValue, 4> Amt2Csts;
14018       for (unsigned i = 0; i != NumElems/2; ++i)
14019         Amt1Csts.push_back(Amt->getOperand(i));
14020       for (unsigned i = NumElems/2; i != NumElems; ++i)
14021         Amt2Csts.push_back(Amt->getOperand(i));
14022
14023       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14024       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14025     } else {
14026       // Variable shift amount
14027       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14028       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14029     }
14030
14031     // Issue new vector shifts for the smaller types
14032     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14033     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14034
14035     // Concatenate the result back
14036     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14037   }
14038
14039   return SDValue();
14040 }
14041
14042 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14043   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14044   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14045   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14046   // has only one use.
14047   SDNode *N = Op.getNode();
14048   SDValue LHS = N->getOperand(0);
14049   SDValue RHS = N->getOperand(1);
14050   unsigned BaseOp = 0;
14051   unsigned Cond = 0;
14052   SDLoc DL(Op);
14053   switch (Op.getOpcode()) {
14054   default: llvm_unreachable("Unknown ovf instruction!");
14055   case ISD::SADDO:
14056     // A subtract of one will be selected as a INC. Note that INC doesn't
14057     // set CF, so we can't do this for UADDO.
14058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14059       if (C->isOne()) {
14060         BaseOp = X86ISD::INC;
14061         Cond = X86::COND_O;
14062         break;
14063       }
14064     BaseOp = X86ISD::ADD;
14065     Cond = X86::COND_O;
14066     break;
14067   case ISD::UADDO:
14068     BaseOp = X86ISD::ADD;
14069     Cond = X86::COND_B;
14070     break;
14071   case ISD::SSUBO:
14072     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14073     // set CF, so we can't do this for USUBO.
14074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14075       if (C->isOne()) {
14076         BaseOp = X86ISD::DEC;
14077         Cond = X86::COND_O;
14078         break;
14079       }
14080     BaseOp = X86ISD::SUB;
14081     Cond = X86::COND_O;
14082     break;
14083   case ISD::USUBO:
14084     BaseOp = X86ISD::SUB;
14085     Cond = X86::COND_B;
14086     break;
14087   case ISD::SMULO:
14088     BaseOp = X86ISD::SMUL;
14089     Cond = X86::COND_O;
14090     break;
14091   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14092     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14093                                  MVT::i32);
14094     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14095
14096     SDValue SetCC =
14097       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14098                   DAG.getConstant(X86::COND_O, MVT::i32),
14099                   SDValue(Sum.getNode(), 2));
14100
14101     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14102   }
14103   }
14104
14105   // Also sets EFLAGS.
14106   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14107   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14108
14109   SDValue SetCC =
14110     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14111                 DAG.getConstant(Cond, MVT::i32),
14112                 SDValue(Sum.getNode(), 1));
14113
14114   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14115 }
14116
14117 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14118                                                   SelectionDAG &DAG) const {
14119   SDLoc dl(Op);
14120   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14121   MVT VT = Op.getSimpleValueType();
14122
14123   if (!Subtarget->hasSSE2() || !VT.isVector())
14124     return SDValue();
14125
14126   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14127                       ExtraVT.getScalarType().getSizeInBits();
14128
14129   switch (VT.SimpleTy) {
14130     default: return SDValue();
14131     case MVT::v8i32:
14132     case MVT::v16i16:
14133       if (!Subtarget->hasFp256())
14134         return SDValue();
14135       if (!Subtarget->hasInt256()) {
14136         // needs to be split
14137         unsigned NumElems = VT.getVectorNumElements();
14138
14139         // Extract the LHS vectors
14140         SDValue LHS = Op.getOperand(0);
14141         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14142         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14143
14144         MVT EltVT = VT.getVectorElementType();
14145         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14146
14147         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14148         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14149         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14150                                    ExtraNumElems/2);
14151         SDValue Extra = DAG.getValueType(ExtraVT);
14152
14153         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14154         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14155
14156         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14157       }
14158       // fall through
14159     case MVT::v4i32:
14160     case MVT::v8i16: {
14161       SDValue Op0 = Op.getOperand(0);
14162       SDValue Op00 = Op0.getOperand(0);
14163       SDValue Tmp1;
14164       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14165       if (Op0.getOpcode() == ISD::BITCAST &&
14166           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14167         // (sext (vzext x)) -> (vsext x)
14168         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14169         if (Tmp1.getNode()) {
14170           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14171           // This folding is only valid when the in-reg type is a vector of i8,
14172           // i16, or i32.
14173           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14174               ExtraEltVT == MVT::i32) {
14175             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14176             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14177                    "This optimization is invalid without a VZEXT.");
14178             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14179           }
14180           Op0 = Tmp1;
14181         }
14182       }
14183
14184       // If the above didn't work, then just use Shift-Left + Shift-Right.
14185       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14186                                         DAG);
14187       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14188                                         DAG);
14189     }
14190   }
14191 }
14192
14193 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14194                                  SelectionDAG &DAG) {
14195   SDLoc dl(Op);
14196   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14197     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14198   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14199     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14200
14201   // The only fence that needs an instruction is a sequentially-consistent
14202   // cross-thread fence.
14203   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14204     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14205     // no-sse2). There isn't any reason to disable it if the target processor
14206     // supports it.
14207     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14208       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14209
14210     SDValue Chain = Op.getOperand(0);
14211     SDValue Zero = DAG.getConstant(0, MVT::i32);
14212     SDValue Ops[] = {
14213       DAG.getRegister(X86::ESP, MVT::i32), // Base
14214       DAG.getTargetConstant(1, MVT::i8),   // Scale
14215       DAG.getRegister(0, MVT::i32),        // Index
14216       DAG.getTargetConstant(0, MVT::i32),  // Disp
14217       DAG.getRegister(0, MVT::i32),        // Segment.
14218       Zero,
14219       Chain
14220     };
14221     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14222     return SDValue(Res, 0);
14223   }
14224
14225   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14226   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14227 }
14228
14229 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14230                              SelectionDAG &DAG) {
14231   MVT T = Op.getSimpleValueType();
14232   SDLoc DL(Op);
14233   unsigned Reg = 0;
14234   unsigned size = 0;
14235   switch(T.SimpleTy) {
14236   default: llvm_unreachable("Invalid value type!");
14237   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14238   case MVT::i16: Reg = X86::AX;  size = 2; break;
14239   case MVT::i32: Reg = X86::EAX; size = 4; break;
14240   case MVT::i64:
14241     assert(Subtarget->is64Bit() && "Node not type legal!");
14242     Reg = X86::RAX; size = 8;
14243     break;
14244   }
14245   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14246                                     Op.getOperand(2), SDValue());
14247   SDValue Ops[] = { cpIn.getValue(0),
14248                     Op.getOperand(1),
14249                     Op.getOperand(3),
14250                     DAG.getTargetConstant(size, MVT::i8),
14251                     cpIn.getValue(1) };
14252   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14253   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14254   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14255                                            Ops, T, MMO);
14256   SDValue cpOut =
14257     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14258   return cpOut;
14259 }
14260
14261 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14262                             SelectionDAG &DAG) {
14263   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14264   MVT DstVT = Op.getSimpleValueType();
14265
14266   if (SrcVT == MVT::v2i32) {
14267     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14268     if (DstVT != MVT::f64)
14269       // This conversion needs to be expanded.
14270       return SDValue();
14271
14272     SDLoc dl(Op);
14273     SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14274                                Op->getOperand(0), DAG.getIntPtrConstant(0));
14275     SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14276                                Op->getOperand(0), DAG.getIntPtrConstant(1));
14277     SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14278     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14279     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14280     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14281                        DAG.getIntPtrConstant(0));
14282   }
14283
14284   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14285          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14286   assert((DstVT == MVT::i64 ||
14287           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14288          "Unexpected custom BITCAST");
14289   // i64 <=> MMX conversions are Legal.
14290   if (SrcVT==MVT::i64 && DstVT.isVector())
14291     return Op;
14292   if (DstVT==MVT::i64 && SrcVT.isVector())
14293     return Op;
14294   // MMX <=> MMX conversions are Legal.
14295   if (SrcVT.isVector() && DstVT.isVector())
14296     return Op;
14297   // All other conversions need to be expanded.
14298   return SDValue();
14299 }
14300
14301 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14302   SDNode *Node = Op.getNode();
14303   SDLoc dl(Node);
14304   EVT T = Node->getValueType(0);
14305   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14306                               DAG.getConstant(0, T), Node->getOperand(2));
14307   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14308                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14309                        Node->getOperand(0),
14310                        Node->getOperand(1), negOp,
14311                        cast<AtomicSDNode>(Node)->getMemOperand(),
14312                        cast<AtomicSDNode>(Node)->getOrdering(),
14313                        cast<AtomicSDNode>(Node)->getSynchScope());
14314 }
14315
14316 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14317   SDNode *Node = Op.getNode();
14318   SDLoc dl(Node);
14319   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14320
14321   // Convert seq_cst store -> xchg
14322   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14323   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14324   //        (The only way to get a 16-byte store is cmpxchg16b)
14325   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14326   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14327       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14328     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14329                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14330                                  Node->getOperand(0),
14331                                  Node->getOperand(1), Node->getOperand(2),
14332                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14333                                  cast<AtomicSDNode>(Node)->getOrdering(),
14334                                  cast<AtomicSDNode>(Node)->getSynchScope());
14335     return Swap.getValue(1);
14336   }
14337   // Other atomic stores have a simple pattern.
14338   return Op;
14339 }
14340
14341 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14342   EVT VT = Op.getNode()->getSimpleValueType(0);
14343
14344   // Let legalize expand this if it isn't a legal type yet.
14345   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14346     return SDValue();
14347
14348   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14349
14350   unsigned Opc;
14351   bool ExtraOp = false;
14352   switch (Op.getOpcode()) {
14353   default: llvm_unreachable("Invalid code");
14354   case ISD::ADDC: Opc = X86ISD::ADD; break;
14355   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14356   case ISD::SUBC: Opc = X86ISD::SUB; break;
14357   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14358   }
14359
14360   if (!ExtraOp)
14361     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14362                        Op.getOperand(1));
14363   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14364                      Op.getOperand(1), Op.getOperand(2));
14365 }
14366
14367 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14368                             SelectionDAG &DAG) {
14369   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14370
14371   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14372   // which returns the values as { float, float } (in XMM0) or
14373   // { double, double } (which is returned in XMM0, XMM1).
14374   SDLoc dl(Op);
14375   SDValue Arg = Op.getOperand(0);
14376   EVT ArgVT = Arg.getValueType();
14377   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14378
14379   TargetLowering::ArgListTy Args;
14380   TargetLowering::ArgListEntry Entry;
14381
14382   Entry.Node = Arg;
14383   Entry.Ty = ArgTy;
14384   Entry.isSExt = false;
14385   Entry.isZExt = false;
14386   Args.push_back(Entry);
14387
14388   bool isF64 = ArgVT == MVT::f64;
14389   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14390   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14391   // the results are returned via SRet in memory.
14392   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14394   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14395
14396   Type *RetTy = isF64
14397     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14398     : (Type*)VectorType::get(ArgTy, 4);
14399   TargetLowering::
14400     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14401                          false, false, false, false, 0,
14402                          CallingConv::C, /*isTaillCall=*/false,
14403                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14404                          Callee, Args, DAG, dl);
14405   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14406
14407   if (isF64)
14408     // Returned in xmm0 and xmm1.
14409     return CallResult.first;
14410
14411   // Returned in bits 0:31 and 32:64 xmm0.
14412   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14413                                CallResult.first, DAG.getIntPtrConstant(0));
14414   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14415                                CallResult.first, DAG.getIntPtrConstant(1));
14416   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14417   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14418 }
14419
14420 /// LowerOperation - Provide custom lowering hooks for some operations.
14421 ///
14422 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14423   switch (Op.getOpcode()) {
14424   default: llvm_unreachable("Should not custom lower this!");
14425   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14426   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14427   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14428   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14429   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14430   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14431   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14432   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14433   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14434   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14435   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14436   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14437   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14438   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14439   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14440   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14441   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14442   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14443   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14444   case ISD::SHL_PARTS:
14445   case ISD::SRA_PARTS:
14446   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14447   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14448   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14449   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14450   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14451   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14452   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14453   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14454   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14455   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14456   case ISD::FABS:               return LowerFABS(Op, DAG);
14457   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14458   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14459   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14460   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14461   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14462   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14463   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14464   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14465   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14466   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14467   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14468   case ISD::INTRINSIC_VOID:
14469   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14470   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14471   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14472   case ISD::FRAME_TO_ARGS_OFFSET:
14473                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14474   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14475   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14476   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14477   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14478   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14479   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14480   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14481   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14482   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14483   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14484   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14485   case ISD::UMUL_LOHI:
14486   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14487   case ISD::SRA:
14488   case ISD::SRL:
14489   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14490   case ISD::SADDO:
14491   case ISD::UADDO:
14492   case ISD::SSUBO:
14493   case ISD::USUBO:
14494   case ISD::SMULO:
14495   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14496   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14497   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14498   case ISD::ADDC:
14499   case ISD::ADDE:
14500   case ISD::SUBC:
14501   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14502   case ISD::ADD:                return LowerADD(Op, DAG);
14503   case ISD::SUB:                return LowerSUB(Op, DAG);
14504   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14505   }
14506 }
14507
14508 static void ReplaceATOMIC_LOAD(SDNode *Node,
14509                                   SmallVectorImpl<SDValue> &Results,
14510                                   SelectionDAG &DAG) {
14511   SDLoc dl(Node);
14512   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14513
14514   // Convert wide load -> cmpxchg8b/cmpxchg16b
14515   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14516   //        (The only way to get a 16-byte load is cmpxchg16b)
14517   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14518   SDValue Zero = DAG.getConstant(0, VT);
14519   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14520                                Node->getOperand(0),
14521                                Node->getOperand(1), Zero, Zero,
14522                                cast<AtomicSDNode>(Node)->getMemOperand(),
14523                                cast<AtomicSDNode>(Node)->getOrdering(),
14524                                cast<AtomicSDNode>(Node)->getOrdering(),
14525                                cast<AtomicSDNode>(Node)->getSynchScope());
14526   Results.push_back(Swap.getValue(0));
14527   Results.push_back(Swap.getValue(1));
14528 }
14529
14530 static void
14531 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14532                         SelectionDAG &DAG, unsigned NewOp) {
14533   SDLoc dl(Node);
14534   assert (Node->getValueType(0) == MVT::i64 &&
14535           "Only know how to expand i64 atomics");
14536
14537   SDValue Chain = Node->getOperand(0);
14538   SDValue In1 = Node->getOperand(1);
14539   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14540                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14541   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14542                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14543   SDValue Ops[] = { Chain, In1, In2L, In2H };
14544   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14545   SDValue Result =
14546     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14547                             cast<MemSDNode>(Node)->getMemOperand());
14548   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14549   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14550   Results.push_back(Result.getValue(2));
14551 }
14552
14553 /// ReplaceNodeResults - Replace a node with an illegal result type
14554 /// with a new node built out of custom code.
14555 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14556                                            SmallVectorImpl<SDValue>&Results,
14557                                            SelectionDAG &DAG) const {
14558   SDLoc dl(N);
14559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14560   switch (N->getOpcode()) {
14561   default:
14562     llvm_unreachable("Do not know how to custom type legalize this operation!");
14563   case ISD::SIGN_EXTEND_INREG:
14564   case ISD::ADDC:
14565   case ISD::ADDE:
14566   case ISD::SUBC:
14567   case ISD::SUBE:
14568     // We don't want to expand or promote these.
14569     return;
14570   case ISD::SDIV:
14571   case ISD::UDIV:
14572   case ISD::SREM:
14573   case ISD::UREM:
14574   case ISD::SDIVREM:
14575   case ISD::UDIVREM: {
14576     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14577     Results.push_back(V);
14578     return;
14579   }
14580   case ISD::FP_TO_SINT:
14581   case ISD::FP_TO_UINT: {
14582     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14583
14584     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14585       return;
14586
14587     std::pair<SDValue,SDValue> Vals =
14588         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14589     SDValue FIST = Vals.first, StackSlot = Vals.second;
14590     if (FIST.getNode()) {
14591       EVT VT = N->getValueType(0);
14592       // Return a load from the stack slot.
14593       if (StackSlot.getNode())
14594         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14595                                       MachinePointerInfo(),
14596                                       false, false, false, 0));
14597       else
14598         Results.push_back(FIST);
14599     }
14600     return;
14601   }
14602   case ISD::UINT_TO_FP: {
14603     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14604     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14605         N->getValueType(0) != MVT::v2f32)
14606       return;
14607     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14608                                  N->getOperand(0));
14609     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14610                                      MVT::f64);
14611     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14612     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14613                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14614     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14615     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14616     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14617     return;
14618   }
14619   case ISD::FP_ROUND: {
14620     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14621         return;
14622     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14623     Results.push_back(V);
14624     return;
14625   }
14626   case ISD::INTRINSIC_W_CHAIN: {
14627     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14628     switch (IntNo) {
14629     default : llvm_unreachable("Do not know how to custom type "
14630                                "legalize this intrinsic operation!");
14631     case Intrinsic::x86_rdtsc:
14632       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14633                                      Results);
14634     case Intrinsic::x86_rdtscp:
14635       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14636                                      Results);
14637     }
14638   }
14639   case ISD::READCYCLECOUNTER: {
14640     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14641                                    Results);
14642   }
14643   case ISD::ATOMIC_CMP_SWAP: {
14644     EVT T = N->getValueType(0);
14645     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14646     bool Regs64bit = T == MVT::i128;
14647     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14648     SDValue cpInL, cpInH;
14649     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14650                         DAG.getConstant(0, HalfT));
14651     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14652                         DAG.getConstant(1, HalfT));
14653     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14654                              Regs64bit ? X86::RAX : X86::EAX,
14655                              cpInL, SDValue());
14656     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14657                              Regs64bit ? X86::RDX : X86::EDX,
14658                              cpInH, cpInL.getValue(1));
14659     SDValue swapInL, swapInH;
14660     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14661                           DAG.getConstant(0, HalfT));
14662     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14663                           DAG.getConstant(1, HalfT));
14664     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14665                                Regs64bit ? X86::RBX : X86::EBX,
14666                                swapInL, cpInH.getValue(1));
14667     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14668                                Regs64bit ? X86::RCX : X86::ECX,
14669                                swapInH, swapInL.getValue(1));
14670     SDValue Ops[] = { swapInH.getValue(0),
14671                       N->getOperand(1),
14672                       swapInH.getValue(1) };
14673     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14674     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14675     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14676                                   X86ISD::LCMPXCHG8_DAG;
14677     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14678     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14679                                         Regs64bit ? X86::RAX : X86::EAX,
14680                                         HalfT, Result.getValue(1));
14681     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14682                                         Regs64bit ? X86::RDX : X86::EDX,
14683                                         HalfT, cpOutL.getValue(2));
14684     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14685     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14686     Results.push_back(cpOutH.getValue(1));
14687     return;
14688   }
14689   case ISD::ATOMIC_LOAD_ADD:
14690   case ISD::ATOMIC_LOAD_AND:
14691   case ISD::ATOMIC_LOAD_NAND:
14692   case ISD::ATOMIC_LOAD_OR:
14693   case ISD::ATOMIC_LOAD_SUB:
14694   case ISD::ATOMIC_LOAD_XOR:
14695   case ISD::ATOMIC_LOAD_MAX:
14696   case ISD::ATOMIC_LOAD_MIN:
14697   case ISD::ATOMIC_LOAD_UMAX:
14698   case ISD::ATOMIC_LOAD_UMIN:
14699   case ISD::ATOMIC_SWAP: {
14700     unsigned Opc;
14701     switch (N->getOpcode()) {
14702     default: llvm_unreachable("Unexpected opcode");
14703     case ISD::ATOMIC_LOAD_ADD:
14704       Opc = X86ISD::ATOMADD64_DAG;
14705       break;
14706     case ISD::ATOMIC_LOAD_AND:
14707       Opc = X86ISD::ATOMAND64_DAG;
14708       break;
14709     case ISD::ATOMIC_LOAD_NAND:
14710       Opc = X86ISD::ATOMNAND64_DAG;
14711       break;
14712     case ISD::ATOMIC_LOAD_OR:
14713       Opc = X86ISD::ATOMOR64_DAG;
14714       break;
14715     case ISD::ATOMIC_LOAD_SUB:
14716       Opc = X86ISD::ATOMSUB64_DAG;
14717       break;
14718     case ISD::ATOMIC_LOAD_XOR:
14719       Opc = X86ISD::ATOMXOR64_DAG;
14720       break;
14721     case ISD::ATOMIC_LOAD_MAX:
14722       Opc = X86ISD::ATOMMAX64_DAG;
14723       break;
14724     case ISD::ATOMIC_LOAD_MIN:
14725       Opc = X86ISD::ATOMMIN64_DAG;
14726       break;
14727     case ISD::ATOMIC_LOAD_UMAX:
14728       Opc = X86ISD::ATOMUMAX64_DAG;
14729       break;
14730     case ISD::ATOMIC_LOAD_UMIN:
14731       Opc = X86ISD::ATOMUMIN64_DAG;
14732       break;
14733     case ISD::ATOMIC_SWAP:
14734       Opc = X86ISD::ATOMSWAP64_DAG;
14735       break;
14736     }
14737     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14738     return;
14739   }
14740   case ISD::ATOMIC_LOAD: {
14741     ReplaceATOMIC_LOAD(N, Results, DAG);
14742     return;
14743   }
14744   case ISD::BITCAST: {
14745     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14746     EVT DstVT = N->getValueType(0);
14747     EVT SrcVT = N->getOperand(0)->getValueType(0);
14748
14749     if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14750       SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14751                                      MVT::v2f64, N->getOperand(0));
14752       SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14753       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14754                                  ToV4I32, DAG.getIntPtrConstant(0));
14755       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14756                                  ToV4I32, DAG.getIntPtrConstant(1));
14757       SDValue Elts[] = {Elt0, Elt1};
14758       Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14759     }
14760   }
14761   }
14762 }
14763
14764 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14765   switch (Opcode) {
14766   default: return nullptr;
14767   case X86ISD::BSF:                return "X86ISD::BSF";
14768   case X86ISD::BSR:                return "X86ISD::BSR";
14769   case X86ISD::SHLD:               return "X86ISD::SHLD";
14770   case X86ISD::SHRD:               return "X86ISD::SHRD";
14771   case X86ISD::FAND:               return "X86ISD::FAND";
14772   case X86ISD::FANDN:              return "X86ISD::FANDN";
14773   case X86ISD::FOR:                return "X86ISD::FOR";
14774   case X86ISD::FXOR:               return "X86ISD::FXOR";
14775   case X86ISD::FSRL:               return "X86ISD::FSRL";
14776   case X86ISD::FILD:               return "X86ISD::FILD";
14777   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14778   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14779   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14780   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14781   case X86ISD::FLD:                return "X86ISD::FLD";
14782   case X86ISD::FST:                return "X86ISD::FST";
14783   case X86ISD::CALL:               return "X86ISD::CALL";
14784   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14785   case X86ISD::BT:                 return "X86ISD::BT";
14786   case X86ISD::CMP:                return "X86ISD::CMP";
14787   case X86ISD::COMI:               return "X86ISD::COMI";
14788   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14789   case X86ISD::CMPM:               return "X86ISD::CMPM";
14790   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14791   case X86ISD::SETCC:              return "X86ISD::SETCC";
14792   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14793   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14794   case X86ISD::CMOV:               return "X86ISD::CMOV";
14795   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14796   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14797   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14798   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14799   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14800   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14801   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14802   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14803   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14804   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14805   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14806   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14807   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14808   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14809   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14810   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14811   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14812   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14813   case X86ISD::HADD:               return "X86ISD::HADD";
14814   case X86ISD::HSUB:               return "X86ISD::HSUB";
14815   case X86ISD::FHADD:              return "X86ISD::FHADD";
14816   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14817   case X86ISD::UMAX:               return "X86ISD::UMAX";
14818   case X86ISD::UMIN:               return "X86ISD::UMIN";
14819   case X86ISD::SMAX:               return "X86ISD::SMAX";
14820   case X86ISD::SMIN:               return "X86ISD::SMIN";
14821   case X86ISD::FMAX:               return "X86ISD::FMAX";
14822   case X86ISD::FMIN:               return "X86ISD::FMIN";
14823   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14824   case X86ISD::FMINC:              return "X86ISD::FMINC";
14825   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14826   case X86ISD::FRCP:               return "X86ISD::FRCP";
14827   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14828   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14829   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14830   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14831   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14832   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14833   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14834   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14835   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14836   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14837   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14838   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14839   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14840   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14841   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14842   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14843   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14844   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14845   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14846   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14847   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14848   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14849   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14850   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14851   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14852   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14853   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14854   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14855   case X86ISD::VSHL:               return "X86ISD::VSHL";
14856   case X86ISD::VSRL:               return "X86ISD::VSRL";
14857   case X86ISD::VSRA:               return "X86ISD::VSRA";
14858   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14859   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14860   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14861   case X86ISD::CMPP:               return "X86ISD::CMPP";
14862   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14863   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14864   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14865   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14866   case X86ISD::ADD:                return "X86ISD::ADD";
14867   case X86ISD::SUB:                return "X86ISD::SUB";
14868   case X86ISD::ADC:                return "X86ISD::ADC";
14869   case X86ISD::SBB:                return "X86ISD::SBB";
14870   case X86ISD::SMUL:               return "X86ISD::SMUL";
14871   case X86ISD::UMUL:               return "X86ISD::UMUL";
14872   case X86ISD::INC:                return "X86ISD::INC";
14873   case X86ISD::DEC:                return "X86ISD::DEC";
14874   case X86ISD::OR:                 return "X86ISD::OR";
14875   case X86ISD::XOR:                return "X86ISD::XOR";
14876   case X86ISD::AND:                return "X86ISD::AND";
14877   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14878   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14879   case X86ISD::PTEST:              return "X86ISD::PTEST";
14880   case X86ISD::TESTP:              return "X86ISD::TESTP";
14881   case X86ISD::TESTM:              return "X86ISD::TESTM";
14882   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14883   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14884   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14885   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14886   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14887   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14888   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14889   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14890   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14891   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14892   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14893   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14894   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14895   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14896   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14897   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14898   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14899   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14900   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14901   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14902   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14903   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14904   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14905   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14906   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14907   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14908   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14909   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14910   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14911   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14912   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14913   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14914   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14915   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14916   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14917   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14918   case X86ISD::SAHF:               return "X86ISD::SAHF";
14919   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14920   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14921   case X86ISD::FMADD:              return "X86ISD::FMADD";
14922   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14923   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14924   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14925   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14926   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14927   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14928   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14929   case X86ISD::XTEST:              return "X86ISD::XTEST";
14930   }
14931 }
14932
14933 // isLegalAddressingMode - Return true if the addressing mode represented
14934 // by AM is legal for this target, for a load/store of the specified type.
14935 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14936                                               Type *Ty) const {
14937   // X86 supports extremely general addressing modes.
14938   CodeModel::Model M = getTargetMachine().getCodeModel();
14939   Reloc::Model R = getTargetMachine().getRelocationModel();
14940
14941   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14942   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14943     return false;
14944
14945   if (AM.BaseGV) {
14946     unsigned GVFlags =
14947       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14948
14949     // If a reference to this global requires an extra load, we can't fold it.
14950     if (isGlobalStubReference(GVFlags))
14951       return false;
14952
14953     // If BaseGV requires a register for the PIC base, we cannot also have a
14954     // BaseReg specified.
14955     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14956       return false;
14957
14958     // If lower 4G is not available, then we must use rip-relative addressing.
14959     if ((M != CodeModel::Small || R != Reloc::Static) &&
14960         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14961       return false;
14962   }
14963
14964   switch (AM.Scale) {
14965   case 0:
14966   case 1:
14967   case 2:
14968   case 4:
14969   case 8:
14970     // These scales always work.
14971     break;
14972   case 3:
14973   case 5:
14974   case 9:
14975     // These scales are formed with basereg+scalereg.  Only accept if there is
14976     // no basereg yet.
14977     if (AM.HasBaseReg)
14978       return false;
14979     break;
14980   default:  // Other stuff never works.
14981     return false;
14982   }
14983
14984   return true;
14985 }
14986
14987 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14988   unsigned Bits = Ty->getScalarSizeInBits();
14989
14990   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14991   // particularly cheaper than those without.
14992   if (Bits == 8)
14993     return false;
14994
14995   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14996   // variable shifts just as cheap as scalar ones.
14997   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14998     return false;
14999
15000   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15001   // fully general vector.
15002   return true;
15003 }
15004
15005 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15006   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15007     return false;
15008   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15009   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15010   return NumBits1 > NumBits2;
15011 }
15012
15013 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15014   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15015     return false;
15016
15017   if (!isTypeLegal(EVT::getEVT(Ty1)))
15018     return false;
15019
15020   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15021
15022   // Assuming the caller doesn't have a zeroext or signext return parameter,
15023   // truncation all the way down to i1 is valid.
15024   return true;
15025 }
15026
15027 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15028   return isInt<32>(Imm);
15029 }
15030
15031 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15032   // Can also use sub to handle negated immediates.
15033   return isInt<32>(Imm);
15034 }
15035
15036 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15037   if (!VT1.isInteger() || !VT2.isInteger())
15038     return false;
15039   unsigned NumBits1 = VT1.getSizeInBits();
15040   unsigned NumBits2 = VT2.getSizeInBits();
15041   return NumBits1 > NumBits2;
15042 }
15043
15044 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15045   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15046   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15047 }
15048
15049 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15050   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15051   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15052 }
15053
15054 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15055   EVT VT1 = Val.getValueType();
15056   if (isZExtFree(VT1, VT2))
15057     return true;
15058
15059   if (Val.getOpcode() != ISD::LOAD)
15060     return false;
15061
15062   if (!VT1.isSimple() || !VT1.isInteger() ||
15063       !VT2.isSimple() || !VT2.isInteger())
15064     return false;
15065
15066   switch (VT1.getSimpleVT().SimpleTy) {
15067   default: break;
15068   case MVT::i8:
15069   case MVT::i16:
15070   case MVT::i32:
15071     // X86 has 8, 16, and 32-bit zero-extending loads.
15072     return true;
15073   }
15074
15075   return false;
15076 }
15077
15078 bool
15079 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15080   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15081     return false;
15082
15083   VT = VT.getScalarType();
15084
15085   if (!VT.isSimple())
15086     return false;
15087
15088   switch (VT.getSimpleVT().SimpleTy) {
15089   case MVT::f32:
15090   case MVT::f64:
15091     return true;
15092   default:
15093     break;
15094   }
15095
15096   return false;
15097 }
15098
15099 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15100   // i16 instructions are longer (0x66 prefix) and potentially slower.
15101   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15102 }
15103
15104 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15105 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15106 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15107 /// are assumed to be legal.
15108 bool
15109 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15110                                       EVT VT) const {
15111   if (!VT.isSimple())
15112     return false;
15113
15114   MVT SVT = VT.getSimpleVT();
15115
15116   // Very little shuffling can be done for 64-bit vectors right now.
15117   if (VT.getSizeInBits() == 64)
15118     return false;
15119
15120   // FIXME: pshufb, blends, shifts.
15121   return (SVT.getVectorNumElements() == 2 ||
15122           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15123           isMOVLMask(M, SVT) ||
15124           isSHUFPMask(M, SVT) ||
15125           isPSHUFDMask(M, SVT) ||
15126           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15127           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15128           isPALIGNRMask(M, SVT, Subtarget) ||
15129           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15130           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15131           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15132           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15133 }
15134
15135 bool
15136 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15137                                           EVT VT) const {
15138   if (!VT.isSimple())
15139     return false;
15140
15141   MVT SVT = VT.getSimpleVT();
15142   unsigned NumElts = SVT.getVectorNumElements();
15143   // FIXME: This collection of masks seems suspect.
15144   if (NumElts == 2)
15145     return true;
15146   if (NumElts == 4 && SVT.is128BitVector()) {
15147     return (isMOVLMask(Mask, SVT)  ||
15148             isCommutedMOVLMask(Mask, SVT, true) ||
15149             isSHUFPMask(Mask, SVT) ||
15150             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15151   }
15152   return false;
15153 }
15154
15155 //===----------------------------------------------------------------------===//
15156 //                           X86 Scheduler Hooks
15157 //===----------------------------------------------------------------------===//
15158
15159 /// Utility function to emit xbegin specifying the start of an RTM region.
15160 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15161                                      const TargetInstrInfo *TII) {
15162   DebugLoc DL = MI->getDebugLoc();
15163
15164   const BasicBlock *BB = MBB->getBasicBlock();
15165   MachineFunction::iterator I = MBB;
15166   ++I;
15167
15168   // For the v = xbegin(), we generate
15169   //
15170   // thisMBB:
15171   //  xbegin sinkMBB
15172   //
15173   // mainMBB:
15174   //  eax = -1
15175   //
15176   // sinkMBB:
15177   //  v = eax
15178
15179   MachineBasicBlock *thisMBB = MBB;
15180   MachineFunction *MF = MBB->getParent();
15181   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15182   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15183   MF->insert(I, mainMBB);
15184   MF->insert(I, sinkMBB);
15185
15186   // Transfer the remainder of BB and its successor edges to sinkMBB.
15187   sinkMBB->splice(sinkMBB->begin(), MBB,
15188                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15189   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15190
15191   // thisMBB:
15192   //  xbegin sinkMBB
15193   //  # fallthrough to mainMBB
15194   //  # abortion to sinkMBB
15195   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15196   thisMBB->addSuccessor(mainMBB);
15197   thisMBB->addSuccessor(sinkMBB);
15198
15199   // mainMBB:
15200   //  EAX = -1
15201   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15202   mainMBB->addSuccessor(sinkMBB);
15203
15204   // sinkMBB:
15205   // EAX is live into the sinkMBB
15206   sinkMBB->addLiveIn(X86::EAX);
15207   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15208           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15209     .addReg(X86::EAX);
15210
15211   MI->eraseFromParent();
15212   return sinkMBB;
15213 }
15214
15215 // Get CMPXCHG opcode for the specified data type.
15216 static unsigned getCmpXChgOpcode(EVT VT) {
15217   switch (VT.getSimpleVT().SimpleTy) {
15218   case MVT::i8:  return X86::LCMPXCHG8;
15219   case MVT::i16: return X86::LCMPXCHG16;
15220   case MVT::i32: return X86::LCMPXCHG32;
15221   case MVT::i64: return X86::LCMPXCHG64;
15222   default:
15223     break;
15224   }
15225   llvm_unreachable("Invalid operand size!");
15226 }
15227
15228 // Get LOAD opcode for the specified data type.
15229 static unsigned getLoadOpcode(EVT VT) {
15230   switch (VT.getSimpleVT().SimpleTy) {
15231   case MVT::i8:  return X86::MOV8rm;
15232   case MVT::i16: return X86::MOV16rm;
15233   case MVT::i32: return X86::MOV32rm;
15234   case MVT::i64: return X86::MOV64rm;
15235   default:
15236     break;
15237   }
15238   llvm_unreachable("Invalid operand size!");
15239 }
15240
15241 // Get opcode of the non-atomic one from the specified atomic instruction.
15242 static unsigned getNonAtomicOpcode(unsigned Opc) {
15243   switch (Opc) {
15244   case X86::ATOMAND8:  return X86::AND8rr;
15245   case X86::ATOMAND16: return X86::AND16rr;
15246   case X86::ATOMAND32: return X86::AND32rr;
15247   case X86::ATOMAND64: return X86::AND64rr;
15248   case X86::ATOMOR8:   return X86::OR8rr;
15249   case X86::ATOMOR16:  return X86::OR16rr;
15250   case X86::ATOMOR32:  return X86::OR32rr;
15251   case X86::ATOMOR64:  return X86::OR64rr;
15252   case X86::ATOMXOR8:  return X86::XOR8rr;
15253   case X86::ATOMXOR16: return X86::XOR16rr;
15254   case X86::ATOMXOR32: return X86::XOR32rr;
15255   case X86::ATOMXOR64: return X86::XOR64rr;
15256   }
15257   llvm_unreachable("Unhandled atomic-load-op opcode!");
15258 }
15259
15260 // Get opcode of the non-atomic one from the specified atomic instruction with
15261 // extra opcode.
15262 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15263                                                unsigned &ExtraOpc) {
15264   switch (Opc) {
15265   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15266   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15267   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15268   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15269   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15270   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15271   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15272   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15273   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15274   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15275   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15276   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15277   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15278   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15279   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15280   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15281   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15282   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15283   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15284   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15285   }
15286   llvm_unreachable("Unhandled atomic-load-op opcode!");
15287 }
15288
15289 // Get opcode of the non-atomic one from the specified atomic instruction for
15290 // 64-bit data type on 32-bit target.
15291 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15292   switch (Opc) {
15293   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15294   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15295   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15296   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15297   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15298   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15299   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15300   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15301   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15302   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15303   }
15304   llvm_unreachable("Unhandled atomic-load-op opcode!");
15305 }
15306
15307 // Get opcode of the non-atomic one from the specified atomic instruction for
15308 // 64-bit data type on 32-bit target with extra opcode.
15309 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15310                                                    unsigned &HiOpc,
15311                                                    unsigned &ExtraOpc) {
15312   switch (Opc) {
15313   case X86::ATOMNAND6432:
15314     ExtraOpc = X86::NOT32r;
15315     HiOpc = X86::AND32rr;
15316     return X86::AND32rr;
15317   }
15318   llvm_unreachable("Unhandled atomic-load-op opcode!");
15319 }
15320
15321 // Get pseudo CMOV opcode from the specified data type.
15322 static unsigned getPseudoCMOVOpc(EVT VT) {
15323   switch (VT.getSimpleVT().SimpleTy) {
15324   case MVT::i8:  return X86::CMOV_GR8;
15325   case MVT::i16: return X86::CMOV_GR16;
15326   case MVT::i32: return X86::CMOV_GR32;
15327   default:
15328     break;
15329   }
15330   llvm_unreachable("Unknown CMOV opcode!");
15331 }
15332
15333 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15334 // They will be translated into a spin-loop or compare-exchange loop from
15335 //
15336 //    ...
15337 //    dst = atomic-fetch-op MI.addr, MI.val
15338 //    ...
15339 //
15340 // to
15341 //
15342 //    ...
15343 //    t1 = LOAD MI.addr
15344 // loop:
15345 //    t4 = phi(t1, t3 / loop)
15346 //    t2 = OP MI.val, t4
15347 //    EAX = t4
15348 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15349 //    t3 = EAX
15350 //    JNE loop
15351 // sink:
15352 //    dst = t3
15353 //    ...
15354 MachineBasicBlock *
15355 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15356                                        MachineBasicBlock *MBB) const {
15357   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15358   DebugLoc DL = MI->getDebugLoc();
15359
15360   MachineFunction *MF = MBB->getParent();
15361   MachineRegisterInfo &MRI = MF->getRegInfo();
15362
15363   const BasicBlock *BB = MBB->getBasicBlock();
15364   MachineFunction::iterator I = MBB;
15365   ++I;
15366
15367   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15368          "Unexpected number of operands");
15369
15370   assert(MI->hasOneMemOperand() &&
15371          "Expected atomic-load-op to have one memoperand");
15372
15373   // Memory Reference
15374   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15375   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15376
15377   unsigned DstReg, SrcReg;
15378   unsigned MemOpndSlot;
15379
15380   unsigned CurOp = 0;
15381
15382   DstReg = MI->getOperand(CurOp++).getReg();
15383   MemOpndSlot = CurOp;
15384   CurOp += X86::AddrNumOperands;
15385   SrcReg = MI->getOperand(CurOp++).getReg();
15386
15387   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15388   MVT::SimpleValueType VT = *RC->vt_begin();
15389   unsigned t1 = MRI.createVirtualRegister(RC);
15390   unsigned t2 = MRI.createVirtualRegister(RC);
15391   unsigned t3 = MRI.createVirtualRegister(RC);
15392   unsigned t4 = MRI.createVirtualRegister(RC);
15393   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15394
15395   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15396   unsigned LOADOpc = getLoadOpcode(VT);
15397
15398   // For the atomic load-arith operator, we generate
15399   //
15400   //  thisMBB:
15401   //    t1 = LOAD [MI.addr]
15402   //  mainMBB:
15403   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15404   //    t1 = OP MI.val, EAX
15405   //    EAX = t4
15406   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15407   //    t3 = EAX
15408   //    JNE mainMBB
15409   //  sinkMBB:
15410   //    dst = t3
15411
15412   MachineBasicBlock *thisMBB = MBB;
15413   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15414   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15415   MF->insert(I, mainMBB);
15416   MF->insert(I, sinkMBB);
15417
15418   MachineInstrBuilder MIB;
15419
15420   // Transfer the remainder of BB and its successor edges to sinkMBB.
15421   sinkMBB->splice(sinkMBB->begin(), MBB,
15422                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15423   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15424
15425   // thisMBB:
15426   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15427   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15428     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15429     if (NewMO.isReg())
15430       NewMO.setIsKill(false);
15431     MIB.addOperand(NewMO);
15432   }
15433   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15434     unsigned flags = (*MMOI)->getFlags();
15435     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15436     MachineMemOperand *MMO =
15437       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15438                                (*MMOI)->getSize(),
15439                                (*MMOI)->getBaseAlignment(),
15440                                (*MMOI)->getTBAAInfo(),
15441                                (*MMOI)->getRanges());
15442     MIB.addMemOperand(MMO);
15443   }
15444
15445   thisMBB->addSuccessor(mainMBB);
15446
15447   // mainMBB:
15448   MachineBasicBlock *origMainMBB = mainMBB;
15449
15450   // Add a PHI.
15451   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15452                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15453
15454   unsigned Opc = MI->getOpcode();
15455   switch (Opc) {
15456   default:
15457     llvm_unreachable("Unhandled atomic-load-op opcode!");
15458   case X86::ATOMAND8:
15459   case X86::ATOMAND16:
15460   case X86::ATOMAND32:
15461   case X86::ATOMAND64:
15462   case X86::ATOMOR8:
15463   case X86::ATOMOR16:
15464   case X86::ATOMOR32:
15465   case X86::ATOMOR64:
15466   case X86::ATOMXOR8:
15467   case X86::ATOMXOR16:
15468   case X86::ATOMXOR32:
15469   case X86::ATOMXOR64: {
15470     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15471     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15472       .addReg(t4);
15473     break;
15474   }
15475   case X86::ATOMNAND8:
15476   case X86::ATOMNAND16:
15477   case X86::ATOMNAND32:
15478   case X86::ATOMNAND64: {
15479     unsigned Tmp = MRI.createVirtualRegister(RC);
15480     unsigned NOTOpc;
15481     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15482     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15483       .addReg(t4);
15484     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15485     break;
15486   }
15487   case X86::ATOMMAX8:
15488   case X86::ATOMMAX16:
15489   case X86::ATOMMAX32:
15490   case X86::ATOMMAX64:
15491   case X86::ATOMMIN8:
15492   case X86::ATOMMIN16:
15493   case X86::ATOMMIN32:
15494   case X86::ATOMMIN64:
15495   case X86::ATOMUMAX8:
15496   case X86::ATOMUMAX16:
15497   case X86::ATOMUMAX32:
15498   case X86::ATOMUMAX64:
15499   case X86::ATOMUMIN8:
15500   case X86::ATOMUMIN16:
15501   case X86::ATOMUMIN32:
15502   case X86::ATOMUMIN64: {
15503     unsigned CMPOpc;
15504     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15505
15506     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15507       .addReg(SrcReg)
15508       .addReg(t4);
15509
15510     if (Subtarget->hasCMov()) {
15511       if (VT != MVT::i8) {
15512         // Native support
15513         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15514           .addReg(SrcReg)
15515           .addReg(t4);
15516       } else {
15517         // Promote i8 to i32 to use CMOV32
15518         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15519         const TargetRegisterClass *RC32 =
15520           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15521         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15522         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15523         unsigned Tmp = MRI.createVirtualRegister(RC32);
15524
15525         unsigned Undef = MRI.createVirtualRegister(RC32);
15526         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15527
15528         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15529           .addReg(Undef)
15530           .addReg(SrcReg)
15531           .addImm(X86::sub_8bit);
15532         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15533           .addReg(Undef)
15534           .addReg(t4)
15535           .addImm(X86::sub_8bit);
15536
15537         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15538           .addReg(SrcReg32)
15539           .addReg(AccReg32);
15540
15541         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15542           .addReg(Tmp, 0, X86::sub_8bit);
15543       }
15544     } else {
15545       // Use pseudo select and lower them.
15546       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15547              "Invalid atomic-load-op transformation!");
15548       unsigned SelOpc = getPseudoCMOVOpc(VT);
15549       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15550       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15551       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15552               .addReg(SrcReg).addReg(t4)
15553               .addImm(CC);
15554       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15555       // Replace the original PHI node as mainMBB is changed after CMOV
15556       // lowering.
15557       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15558         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15559       Phi->eraseFromParent();
15560     }
15561     break;
15562   }
15563   }
15564
15565   // Copy PhyReg back from virtual register.
15566   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15567     .addReg(t4);
15568
15569   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15570   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15571     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15572     if (NewMO.isReg())
15573       NewMO.setIsKill(false);
15574     MIB.addOperand(NewMO);
15575   }
15576   MIB.addReg(t2);
15577   MIB.setMemRefs(MMOBegin, MMOEnd);
15578
15579   // Copy PhyReg back to virtual register.
15580   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15581     .addReg(PhyReg);
15582
15583   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15584
15585   mainMBB->addSuccessor(origMainMBB);
15586   mainMBB->addSuccessor(sinkMBB);
15587
15588   // sinkMBB:
15589   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15590           TII->get(TargetOpcode::COPY), DstReg)
15591     .addReg(t3);
15592
15593   MI->eraseFromParent();
15594   return sinkMBB;
15595 }
15596
15597 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15598 // instructions. They will be translated into a spin-loop or compare-exchange
15599 // loop from
15600 //
15601 //    ...
15602 //    dst = atomic-fetch-op MI.addr, MI.val
15603 //    ...
15604 //
15605 // to
15606 //
15607 //    ...
15608 //    t1L = LOAD [MI.addr + 0]
15609 //    t1H = LOAD [MI.addr + 4]
15610 // loop:
15611 //    t4L = phi(t1L, t3L / loop)
15612 //    t4H = phi(t1H, t3H / loop)
15613 //    t2L = OP MI.val.lo, t4L
15614 //    t2H = OP MI.val.hi, t4H
15615 //    EAX = t4L
15616 //    EDX = t4H
15617 //    EBX = t2L
15618 //    ECX = t2H
15619 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15620 //    t3L = EAX
15621 //    t3H = EDX
15622 //    JNE loop
15623 // sink:
15624 //    dstL = t3L
15625 //    dstH = t3H
15626 //    ...
15627 MachineBasicBlock *
15628 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15629                                            MachineBasicBlock *MBB) const {
15630   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15631   DebugLoc DL = MI->getDebugLoc();
15632
15633   MachineFunction *MF = MBB->getParent();
15634   MachineRegisterInfo &MRI = MF->getRegInfo();
15635
15636   const BasicBlock *BB = MBB->getBasicBlock();
15637   MachineFunction::iterator I = MBB;
15638   ++I;
15639
15640   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15641          "Unexpected number of operands");
15642
15643   assert(MI->hasOneMemOperand() &&
15644          "Expected atomic-load-op32 to have one memoperand");
15645
15646   // Memory Reference
15647   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15648   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15649
15650   unsigned DstLoReg, DstHiReg;
15651   unsigned SrcLoReg, SrcHiReg;
15652   unsigned MemOpndSlot;
15653
15654   unsigned CurOp = 0;
15655
15656   DstLoReg = MI->getOperand(CurOp++).getReg();
15657   DstHiReg = MI->getOperand(CurOp++).getReg();
15658   MemOpndSlot = CurOp;
15659   CurOp += X86::AddrNumOperands;
15660   SrcLoReg = MI->getOperand(CurOp++).getReg();
15661   SrcHiReg = MI->getOperand(CurOp++).getReg();
15662
15663   const TargetRegisterClass *RC = &X86::GR32RegClass;
15664   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15665
15666   unsigned t1L = MRI.createVirtualRegister(RC);
15667   unsigned t1H = MRI.createVirtualRegister(RC);
15668   unsigned t2L = MRI.createVirtualRegister(RC);
15669   unsigned t2H = MRI.createVirtualRegister(RC);
15670   unsigned t3L = MRI.createVirtualRegister(RC);
15671   unsigned t3H = MRI.createVirtualRegister(RC);
15672   unsigned t4L = MRI.createVirtualRegister(RC);
15673   unsigned t4H = MRI.createVirtualRegister(RC);
15674
15675   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15676   unsigned LOADOpc = X86::MOV32rm;
15677
15678   // For the atomic load-arith operator, we generate
15679   //
15680   //  thisMBB:
15681   //    t1L = LOAD [MI.addr + 0]
15682   //    t1H = LOAD [MI.addr + 4]
15683   //  mainMBB:
15684   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15685   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15686   //    t2L = OP MI.val.lo, t4L
15687   //    t2H = OP MI.val.hi, t4H
15688   //    EBX = t2L
15689   //    ECX = t2H
15690   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15691   //    t3L = EAX
15692   //    t3H = EDX
15693   //    JNE loop
15694   //  sinkMBB:
15695   //    dstL = t3L
15696   //    dstH = t3H
15697
15698   MachineBasicBlock *thisMBB = MBB;
15699   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15700   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15701   MF->insert(I, mainMBB);
15702   MF->insert(I, sinkMBB);
15703
15704   MachineInstrBuilder MIB;
15705
15706   // Transfer the remainder of BB and its successor edges to sinkMBB.
15707   sinkMBB->splice(sinkMBB->begin(), MBB,
15708                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15709   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15710
15711   // thisMBB:
15712   // Lo
15713   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15714   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15715     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15716     if (NewMO.isReg())
15717       NewMO.setIsKill(false);
15718     MIB.addOperand(NewMO);
15719   }
15720   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15721     unsigned flags = (*MMOI)->getFlags();
15722     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15723     MachineMemOperand *MMO =
15724       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15725                                (*MMOI)->getSize(),
15726                                (*MMOI)->getBaseAlignment(),
15727                                (*MMOI)->getTBAAInfo(),
15728                                (*MMOI)->getRanges());
15729     MIB.addMemOperand(MMO);
15730   };
15731   MachineInstr *LowMI = MIB;
15732
15733   // Hi
15734   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15735   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15736     if (i == X86::AddrDisp) {
15737       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15738     } else {
15739       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15740       if (NewMO.isReg())
15741         NewMO.setIsKill(false);
15742       MIB.addOperand(NewMO);
15743     }
15744   }
15745   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15746
15747   thisMBB->addSuccessor(mainMBB);
15748
15749   // mainMBB:
15750   MachineBasicBlock *origMainMBB = mainMBB;
15751
15752   // Add PHIs.
15753   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15754                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15755   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15756                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15757
15758   unsigned Opc = MI->getOpcode();
15759   switch (Opc) {
15760   default:
15761     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15762   case X86::ATOMAND6432:
15763   case X86::ATOMOR6432:
15764   case X86::ATOMXOR6432:
15765   case X86::ATOMADD6432:
15766   case X86::ATOMSUB6432: {
15767     unsigned HiOpc;
15768     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15769     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15770       .addReg(SrcLoReg);
15771     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15772       .addReg(SrcHiReg);
15773     break;
15774   }
15775   case X86::ATOMNAND6432: {
15776     unsigned HiOpc, NOTOpc;
15777     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15778     unsigned TmpL = MRI.createVirtualRegister(RC);
15779     unsigned TmpH = MRI.createVirtualRegister(RC);
15780     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15781       .addReg(t4L);
15782     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15783       .addReg(t4H);
15784     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15785     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15786     break;
15787   }
15788   case X86::ATOMMAX6432:
15789   case X86::ATOMMIN6432:
15790   case X86::ATOMUMAX6432:
15791   case X86::ATOMUMIN6432: {
15792     unsigned HiOpc;
15793     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15794     unsigned cL = MRI.createVirtualRegister(RC8);
15795     unsigned cH = MRI.createVirtualRegister(RC8);
15796     unsigned cL32 = MRI.createVirtualRegister(RC);
15797     unsigned cH32 = MRI.createVirtualRegister(RC);
15798     unsigned cc = MRI.createVirtualRegister(RC);
15799     // cl := cmp src_lo, lo
15800     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15801       .addReg(SrcLoReg).addReg(t4L);
15802     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15803     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15804     // ch := cmp src_hi, hi
15805     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15806       .addReg(SrcHiReg).addReg(t4H);
15807     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15808     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15809     // cc := if (src_hi == hi) ? cl : ch;
15810     if (Subtarget->hasCMov()) {
15811       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15812         .addReg(cH32).addReg(cL32);
15813     } else {
15814       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15815               .addReg(cH32).addReg(cL32)
15816               .addImm(X86::COND_E);
15817       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15818     }
15819     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15820     if (Subtarget->hasCMov()) {
15821       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15822         .addReg(SrcLoReg).addReg(t4L);
15823       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15824         .addReg(SrcHiReg).addReg(t4H);
15825     } else {
15826       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15827               .addReg(SrcLoReg).addReg(t4L)
15828               .addImm(X86::COND_NE);
15829       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15830       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15831       // 2nd CMOV lowering.
15832       mainMBB->addLiveIn(X86::EFLAGS);
15833       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15834               .addReg(SrcHiReg).addReg(t4H)
15835               .addImm(X86::COND_NE);
15836       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15837       // Replace the original PHI node as mainMBB is changed after CMOV
15838       // lowering.
15839       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15840         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15841       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15842         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15843       PhiL->eraseFromParent();
15844       PhiH->eraseFromParent();
15845     }
15846     break;
15847   }
15848   case X86::ATOMSWAP6432: {
15849     unsigned HiOpc;
15850     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15851     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15852     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15853     break;
15854   }
15855   }
15856
15857   // Copy EDX:EAX back from HiReg:LoReg
15858   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15859   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15860   // Copy ECX:EBX from t1H:t1L
15861   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15862   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15863
15864   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15865   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15866     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15867     if (NewMO.isReg())
15868       NewMO.setIsKill(false);
15869     MIB.addOperand(NewMO);
15870   }
15871   MIB.setMemRefs(MMOBegin, MMOEnd);
15872
15873   // Copy EDX:EAX back to t3H:t3L
15874   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15875   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15876
15877   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15878
15879   mainMBB->addSuccessor(origMainMBB);
15880   mainMBB->addSuccessor(sinkMBB);
15881
15882   // sinkMBB:
15883   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15884           TII->get(TargetOpcode::COPY), DstLoReg)
15885     .addReg(t3L);
15886   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15887           TII->get(TargetOpcode::COPY), DstHiReg)
15888     .addReg(t3H);
15889
15890   MI->eraseFromParent();
15891   return sinkMBB;
15892 }
15893
15894 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15895 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15896 // in the .td file.
15897 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15898                                        const TargetInstrInfo *TII) {
15899   unsigned Opc;
15900   switch (MI->getOpcode()) {
15901   default: llvm_unreachable("illegal opcode!");
15902   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15903   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15904   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15905   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15906   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15907   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15908   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15909   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15910   }
15911
15912   DebugLoc dl = MI->getDebugLoc();
15913   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15914
15915   unsigned NumArgs = MI->getNumOperands();
15916   for (unsigned i = 1; i < NumArgs; ++i) {
15917     MachineOperand &Op = MI->getOperand(i);
15918     if (!(Op.isReg() && Op.isImplicit()))
15919       MIB.addOperand(Op);
15920   }
15921   if (MI->hasOneMemOperand())
15922     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15923
15924   BuildMI(*BB, MI, dl,
15925     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15926     .addReg(X86::XMM0);
15927
15928   MI->eraseFromParent();
15929   return BB;
15930 }
15931
15932 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15933 // defs in an instruction pattern
15934 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15935                                        const TargetInstrInfo *TII) {
15936   unsigned Opc;
15937   switch (MI->getOpcode()) {
15938   default: llvm_unreachable("illegal opcode!");
15939   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15940   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15941   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15942   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15943   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15944   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15945   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15946   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15947   }
15948
15949   DebugLoc dl = MI->getDebugLoc();
15950   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15951
15952   unsigned NumArgs = MI->getNumOperands(); // remove the results
15953   for (unsigned i = 1; i < NumArgs; ++i) {
15954     MachineOperand &Op = MI->getOperand(i);
15955     if (!(Op.isReg() && Op.isImplicit()))
15956       MIB.addOperand(Op);
15957   }
15958   if (MI->hasOneMemOperand())
15959     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15960
15961   BuildMI(*BB, MI, dl,
15962     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15963     .addReg(X86::ECX);
15964
15965   MI->eraseFromParent();
15966   return BB;
15967 }
15968
15969 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15970                                        const TargetInstrInfo *TII,
15971                                        const X86Subtarget* Subtarget) {
15972   DebugLoc dl = MI->getDebugLoc();
15973
15974   // Address into RAX/EAX, other two args into ECX, EDX.
15975   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15976   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15977   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15978   for (int i = 0; i < X86::AddrNumOperands; ++i)
15979     MIB.addOperand(MI->getOperand(i));
15980
15981   unsigned ValOps = X86::AddrNumOperands;
15982   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15983     .addReg(MI->getOperand(ValOps).getReg());
15984   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15985     .addReg(MI->getOperand(ValOps+1).getReg());
15986
15987   // The instruction doesn't actually take any operands though.
15988   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15989
15990   MI->eraseFromParent(); // The pseudo is gone now.
15991   return BB;
15992 }
15993
15994 MachineBasicBlock *
15995 X86TargetLowering::EmitVAARG64WithCustomInserter(
15996                    MachineInstr *MI,
15997                    MachineBasicBlock *MBB) const {
15998   // Emit va_arg instruction on X86-64.
15999
16000   // Operands to this pseudo-instruction:
16001   // 0  ) Output        : destination address (reg)
16002   // 1-5) Input         : va_list address (addr, i64mem)
16003   // 6  ) ArgSize       : Size (in bytes) of vararg type
16004   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16005   // 8  ) Align         : Alignment of type
16006   // 9  ) EFLAGS (implicit-def)
16007
16008   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16009   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16010
16011   unsigned DestReg = MI->getOperand(0).getReg();
16012   MachineOperand &Base = MI->getOperand(1);
16013   MachineOperand &Scale = MI->getOperand(2);
16014   MachineOperand &Index = MI->getOperand(3);
16015   MachineOperand &Disp = MI->getOperand(4);
16016   MachineOperand &Segment = MI->getOperand(5);
16017   unsigned ArgSize = MI->getOperand(6).getImm();
16018   unsigned ArgMode = MI->getOperand(7).getImm();
16019   unsigned Align = MI->getOperand(8).getImm();
16020
16021   // Memory Reference
16022   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16023   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16024   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16025
16026   // Machine Information
16027   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16028   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16029   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16030   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16031   DebugLoc DL = MI->getDebugLoc();
16032
16033   // struct va_list {
16034   //   i32   gp_offset
16035   //   i32   fp_offset
16036   //   i64   overflow_area (address)
16037   //   i64   reg_save_area (address)
16038   // }
16039   // sizeof(va_list) = 24
16040   // alignment(va_list) = 8
16041
16042   unsigned TotalNumIntRegs = 6;
16043   unsigned TotalNumXMMRegs = 8;
16044   bool UseGPOffset = (ArgMode == 1);
16045   bool UseFPOffset = (ArgMode == 2);
16046   unsigned MaxOffset = TotalNumIntRegs * 8 +
16047                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16048
16049   /* Align ArgSize to a multiple of 8 */
16050   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16051   bool NeedsAlign = (Align > 8);
16052
16053   MachineBasicBlock *thisMBB = MBB;
16054   MachineBasicBlock *overflowMBB;
16055   MachineBasicBlock *offsetMBB;
16056   MachineBasicBlock *endMBB;
16057
16058   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16059   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16060   unsigned OffsetReg = 0;
16061
16062   if (!UseGPOffset && !UseFPOffset) {
16063     // If we only pull from the overflow region, we don't create a branch.
16064     // We don't need to alter control flow.
16065     OffsetDestReg = 0; // unused
16066     OverflowDestReg = DestReg;
16067
16068     offsetMBB = nullptr;
16069     overflowMBB = thisMBB;
16070     endMBB = thisMBB;
16071   } else {
16072     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16073     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16074     // If not, pull from overflow_area. (branch to overflowMBB)
16075     //
16076     //       thisMBB
16077     //         |     .
16078     //         |        .
16079     //     offsetMBB   overflowMBB
16080     //         |        .
16081     //         |     .
16082     //        endMBB
16083
16084     // Registers for the PHI in endMBB
16085     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16086     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16087
16088     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16089     MachineFunction *MF = MBB->getParent();
16090     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16091     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16092     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16093
16094     MachineFunction::iterator MBBIter = MBB;
16095     ++MBBIter;
16096
16097     // Insert the new basic blocks
16098     MF->insert(MBBIter, offsetMBB);
16099     MF->insert(MBBIter, overflowMBB);
16100     MF->insert(MBBIter, endMBB);
16101
16102     // Transfer the remainder of MBB and its successor edges to endMBB.
16103     endMBB->splice(endMBB->begin(), thisMBB,
16104                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16105     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16106
16107     // Make offsetMBB and overflowMBB successors of thisMBB
16108     thisMBB->addSuccessor(offsetMBB);
16109     thisMBB->addSuccessor(overflowMBB);
16110
16111     // endMBB is a successor of both offsetMBB and overflowMBB
16112     offsetMBB->addSuccessor(endMBB);
16113     overflowMBB->addSuccessor(endMBB);
16114
16115     // Load the offset value into a register
16116     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16117     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16118       .addOperand(Base)
16119       .addOperand(Scale)
16120       .addOperand(Index)
16121       .addDisp(Disp, UseFPOffset ? 4 : 0)
16122       .addOperand(Segment)
16123       .setMemRefs(MMOBegin, MMOEnd);
16124
16125     // Check if there is enough room left to pull this argument.
16126     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16127       .addReg(OffsetReg)
16128       .addImm(MaxOffset + 8 - ArgSizeA8);
16129
16130     // Branch to "overflowMBB" if offset >= max
16131     // Fall through to "offsetMBB" otherwise
16132     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16133       .addMBB(overflowMBB);
16134   }
16135
16136   // In offsetMBB, emit code to use the reg_save_area.
16137   if (offsetMBB) {
16138     assert(OffsetReg != 0);
16139
16140     // Read the reg_save_area address.
16141     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16142     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16143       .addOperand(Base)
16144       .addOperand(Scale)
16145       .addOperand(Index)
16146       .addDisp(Disp, 16)
16147       .addOperand(Segment)
16148       .setMemRefs(MMOBegin, MMOEnd);
16149
16150     // Zero-extend the offset
16151     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16152       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16153         .addImm(0)
16154         .addReg(OffsetReg)
16155         .addImm(X86::sub_32bit);
16156
16157     // Add the offset to the reg_save_area to get the final address.
16158     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16159       .addReg(OffsetReg64)
16160       .addReg(RegSaveReg);
16161
16162     // Compute the offset for the next argument
16163     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16164     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16165       .addReg(OffsetReg)
16166       .addImm(UseFPOffset ? 16 : 8);
16167
16168     // Store it back into the va_list.
16169     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16170       .addOperand(Base)
16171       .addOperand(Scale)
16172       .addOperand(Index)
16173       .addDisp(Disp, UseFPOffset ? 4 : 0)
16174       .addOperand(Segment)
16175       .addReg(NextOffsetReg)
16176       .setMemRefs(MMOBegin, MMOEnd);
16177
16178     // Jump to endMBB
16179     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16180       .addMBB(endMBB);
16181   }
16182
16183   //
16184   // Emit code to use overflow area
16185   //
16186
16187   // Load the overflow_area address into a register.
16188   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16189   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16190     .addOperand(Base)
16191     .addOperand(Scale)
16192     .addOperand(Index)
16193     .addDisp(Disp, 8)
16194     .addOperand(Segment)
16195     .setMemRefs(MMOBegin, MMOEnd);
16196
16197   // If we need to align it, do so. Otherwise, just copy the address
16198   // to OverflowDestReg.
16199   if (NeedsAlign) {
16200     // Align the overflow address
16201     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16202     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16203
16204     // aligned_addr = (addr + (align-1)) & ~(align-1)
16205     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16206       .addReg(OverflowAddrReg)
16207       .addImm(Align-1);
16208
16209     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16210       .addReg(TmpReg)
16211       .addImm(~(uint64_t)(Align-1));
16212   } else {
16213     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16214       .addReg(OverflowAddrReg);
16215   }
16216
16217   // Compute the next overflow address after this argument.
16218   // (the overflow address should be kept 8-byte aligned)
16219   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16220   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16221     .addReg(OverflowDestReg)
16222     .addImm(ArgSizeA8);
16223
16224   // Store the new overflow address.
16225   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16226     .addOperand(Base)
16227     .addOperand(Scale)
16228     .addOperand(Index)
16229     .addDisp(Disp, 8)
16230     .addOperand(Segment)
16231     .addReg(NextAddrReg)
16232     .setMemRefs(MMOBegin, MMOEnd);
16233
16234   // If we branched, emit the PHI to the front of endMBB.
16235   if (offsetMBB) {
16236     BuildMI(*endMBB, endMBB->begin(), DL,
16237             TII->get(X86::PHI), DestReg)
16238       .addReg(OffsetDestReg).addMBB(offsetMBB)
16239       .addReg(OverflowDestReg).addMBB(overflowMBB);
16240   }
16241
16242   // Erase the pseudo instruction
16243   MI->eraseFromParent();
16244
16245   return endMBB;
16246 }
16247
16248 MachineBasicBlock *
16249 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16250                                                  MachineInstr *MI,
16251                                                  MachineBasicBlock *MBB) const {
16252   // Emit code to save XMM registers to the stack. The ABI says that the
16253   // number of registers to save is given in %al, so it's theoretically
16254   // possible to do an indirect jump trick to avoid saving all of them,
16255   // however this code takes a simpler approach and just executes all
16256   // of the stores if %al is non-zero. It's less code, and it's probably
16257   // easier on the hardware branch predictor, and stores aren't all that
16258   // expensive anyway.
16259
16260   // Create the new basic blocks. One block contains all the XMM stores,
16261   // and one block is the final destination regardless of whether any
16262   // stores were performed.
16263   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16264   MachineFunction *F = MBB->getParent();
16265   MachineFunction::iterator MBBIter = MBB;
16266   ++MBBIter;
16267   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16268   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16269   F->insert(MBBIter, XMMSaveMBB);
16270   F->insert(MBBIter, EndMBB);
16271
16272   // Transfer the remainder of MBB and its successor edges to EndMBB.
16273   EndMBB->splice(EndMBB->begin(), MBB,
16274                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16275   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16276
16277   // The original block will now fall through to the XMM save block.
16278   MBB->addSuccessor(XMMSaveMBB);
16279   // The XMMSaveMBB will fall through to the end block.
16280   XMMSaveMBB->addSuccessor(EndMBB);
16281
16282   // Now add the instructions.
16283   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16284   DebugLoc DL = MI->getDebugLoc();
16285
16286   unsigned CountReg = MI->getOperand(0).getReg();
16287   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16288   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16289
16290   if (!Subtarget->isTargetWin64()) {
16291     // If %al is 0, branch around the XMM save block.
16292     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16293     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16294     MBB->addSuccessor(EndMBB);
16295   }
16296
16297   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16298   // that was just emitted, but clearly shouldn't be "saved".
16299   assert((MI->getNumOperands() <= 3 ||
16300           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16301           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16302          && "Expected last argument to be EFLAGS");
16303   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16304   // In the XMM save block, save all the XMM argument registers.
16305   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16306     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16307     MachineMemOperand *MMO =
16308       F->getMachineMemOperand(
16309           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16310         MachineMemOperand::MOStore,
16311         /*Size=*/16, /*Align=*/16);
16312     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16313       .addFrameIndex(RegSaveFrameIndex)
16314       .addImm(/*Scale=*/1)
16315       .addReg(/*IndexReg=*/0)
16316       .addImm(/*Disp=*/Offset)
16317       .addReg(/*Segment=*/0)
16318       .addReg(MI->getOperand(i).getReg())
16319       .addMemOperand(MMO);
16320   }
16321
16322   MI->eraseFromParent();   // The pseudo instruction is gone now.
16323
16324   return EndMBB;
16325 }
16326
16327 // The EFLAGS operand of SelectItr might be missing a kill marker
16328 // because there were multiple uses of EFLAGS, and ISel didn't know
16329 // which to mark. Figure out whether SelectItr should have had a
16330 // kill marker, and set it if it should. Returns the correct kill
16331 // marker value.
16332 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16333                                      MachineBasicBlock* BB,
16334                                      const TargetRegisterInfo* TRI) {
16335   // Scan forward through BB for a use/def of EFLAGS.
16336   MachineBasicBlock::iterator miI(std::next(SelectItr));
16337   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16338     const MachineInstr& mi = *miI;
16339     if (mi.readsRegister(X86::EFLAGS))
16340       return false;
16341     if (mi.definesRegister(X86::EFLAGS))
16342       break; // Should have kill-flag - update below.
16343   }
16344
16345   // If we hit the end of the block, check whether EFLAGS is live into a
16346   // successor.
16347   if (miI == BB->end()) {
16348     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16349                                           sEnd = BB->succ_end();
16350          sItr != sEnd; ++sItr) {
16351       MachineBasicBlock* succ = *sItr;
16352       if (succ->isLiveIn(X86::EFLAGS))
16353         return false;
16354     }
16355   }
16356
16357   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16358   // out. SelectMI should have a kill flag on EFLAGS.
16359   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16360   return true;
16361 }
16362
16363 MachineBasicBlock *
16364 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16365                                      MachineBasicBlock *BB) const {
16366   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16367   DebugLoc DL = MI->getDebugLoc();
16368
16369   // To "insert" a SELECT_CC instruction, we actually have to insert the
16370   // diamond control-flow pattern.  The incoming instruction knows the
16371   // destination vreg to set, the condition code register to branch on, the
16372   // true/false values to select between, and a branch opcode to use.
16373   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16374   MachineFunction::iterator It = BB;
16375   ++It;
16376
16377   //  thisMBB:
16378   //  ...
16379   //   TrueVal = ...
16380   //   cmpTY ccX, r1, r2
16381   //   bCC copy1MBB
16382   //   fallthrough --> copy0MBB
16383   MachineBasicBlock *thisMBB = BB;
16384   MachineFunction *F = BB->getParent();
16385   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16386   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16387   F->insert(It, copy0MBB);
16388   F->insert(It, sinkMBB);
16389
16390   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16391   // live into the sink and copy blocks.
16392   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16393   if (!MI->killsRegister(X86::EFLAGS) &&
16394       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16395     copy0MBB->addLiveIn(X86::EFLAGS);
16396     sinkMBB->addLiveIn(X86::EFLAGS);
16397   }
16398
16399   // Transfer the remainder of BB and its successor edges to sinkMBB.
16400   sinkMBB->splice(sinkMBB->begin(), BB,
16401                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16402   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16403
16404   // Add the true and fallthrough blocks as its successors.
16405   BB->addSuccessor(copy0MBB);
16406   BB->addSuccessor(sinkMBB);
16407
16408   // Create the conditional branch instruction.
16409   unsigned Opc =
16410     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16411   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16412
16413   //  copy0MBB:
16414   //   %FalseValue = ...
16415   //   # fallthrough to sinkMBB
16416   copy0MBB->addSuccessor(sinkMBB);
16417
16418   //  sinkMBB:
16419   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16420   //  ...
16421   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16422           TII->get(X86::PHI), MI->getOperand(0).getReg())
16423     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16424     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16425
16426   MI->eraseFromParent();   // The pseudo instruction is gone now.
16427   return sinkMBB;
16428 }
16429
16430 MachineBasicBlock *
16431 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16432                                         bool Is64Bit) const {
16433   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16434   DebugLoc DL = MI->getDebugLoc();
16435   MachineFunction *MF = BB->getParent();
16436   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16437
16438   assert(MF->shouldSplitStack());
16439
16440   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16441   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16442
16443   // BB:
16444   //  ... [Till the alloca]
16445   // If stacklet is not large enough, jump to mallocMBB
16446   //
16447   // bumpMBB:
16448   //  Allocate by subtracting from RSP
16449   //  Jump to continueMBB
16450   //
16451   // mallocMBB:
16452   //  Allocate by call to runtime
16453   //
16454   // continueMBB:
16455   //  ...
16456   //  [rest of original BB]
16457   //
16458
16459   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16460   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16461   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16462
16463   MachineRegisterInfo &MRI = MF->getRegInfo();
16464   const TargetRegisterClass *AddrRegClass =
16465     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16466
16467   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16468     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16469     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16470     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16471     sizeVReg = MI->getOperand(1).getReg(),
16472     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16473
16474   MachineFunction::iterator MBBIter = BB;
16475   ++MBBIter;
16476
16477   MF->insert(MBBIter, bumpMBB);
16478   MF->insert(MBBIter, mallocMBB);
16479   MF->insert(MBBIter, continueMBB);
16480
16481   continueMBB->splice(continueMBB->begin(), BB,
16482                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16483   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16484
16485   // Add code to the main basic block to check if the stack limit has been hit,
16486   // and if so, jump to mallocMBB otherwise to bumpMBB.
16487   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16488   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16489     .addReg(tmpSPVReg).addReg(sizeVReg);
16490   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16491     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16492     .addReg(SPLimitVReg);
16493   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16494
16495   // bumpMBB simply decreases the stack pointer, since we know the current
16496   // stacklet has enough space.
16497   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16498     .addReg(SPLimitVReg);
16499   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16500     .addReg(SPLimitVReg);
16501   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16502
16503   // Calls into a routine in libgcc to allocate more space from the heap.
16504   const uint32_t *RegMask =
16505     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16506   if (Is64Bit) {
16507     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16508       .addReg(sizeVReg);
16509     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16510       .addExternalSymbol("__morestack_allocate_stack_space")
16511       .addRegMask(RegMask)
16512       .addReg(X86::RDI, RegState::Implicit)
16513       .addReg(X86::RAX, RegState::ImplicitDefine);
16514   } else {
16515     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16516       .addImm(12);
16517     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16518     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16519       .addExternalSymbol("__morestack_allocate_stack_space")
16520       .addRegMask(RegMask)
16521       .addReg(X86::EAX, RegState::ImplicitDefine);
16522   }
16523
16524   if (!Is64Bit)
16525     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16526       .addImm(16);
16527
16528   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16529     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16530   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16531
16532   // Set up the CFG correctly.
16533   BB->addSuccessor(bumpMBB);
16534   BB->addSuccessor(mallocMBB);
16535   mallocMBB->addSuccessor(continueMBB);
16536   bumpMBB->addSuccessor(continueMBB);
16537
16538   // Take care of the PHI nodes.
16539   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16540           MI->getOperand(0).getReg())
16541     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16542     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16543
16544   // Delete the original pseudo instruction.
16545   MI->eraseFromParent();
16546
16547   // And we're done.
16548   return continueMBB;
16549 }
16550
16551 MachineBasicBlock *
16552 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16553                                           MachineBasicBlock *BB) const {
16554   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16555   DebugLoc DL = MI->getDebugLoc();
16556
16557   assert(!Subtarget->isTargetMacho());
16558
16559   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16560   // non-trivial part is impdef of ESP.
16561
16562   if (Subtarget->isTargetWin64()) {
16563     if (Subtarget->isTargetCygMing()) {
16564       // ___chkstk(Mingw64):
16565       // Clobbers R10, R11, RAX and EFLAGS.
16566       // Updates RSP.
16567       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16568         .addExternalSymbol("___chkstk")
16569         .addReg(X86::RAX, RegState::Implicit)
16570         .addReg(X86::RSP, RegState::Implicit)
16571         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16572         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16573         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16574     } else {
16575       // __chkstk(MSVCRT): does not update stack pointer.
16576       // Clobbers R10, R11 and EFLAGS.
16577       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16578         .addExternalSymbol("__chkstk")
16579         .addReg(X86::RAX, RegState::Implicit)
16580         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16581       // RAX has the offset to be subtracted from RSP.
16582       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16583         .addReg(X86::RSP)
16584         .addReg(X86::RAX);
16585     }
16586   } else {
16587     const char *StackProbeSymbol =
16588       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16589
16590     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16591       .addExternalSymbol(StackProbeSymbol)
16592       .addReg(X86::EAX, RegState::Implicit)
16593       .addReg(X86::ESP, RegState::Implicit)
16594       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16595       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16596       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16597   }
16598
16599   MI->eraseFromParent();   // The pseudo instruction is gone now.
16600   return BB;
16601 }
16602
16603 MachineBasicBlock *
16604 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16605                                       MachineBasicBlock *BB) const {
16606   // This is pretty easy.  We're taking the value that we received from
16607   // our load from the relocation, sticking it in either RDI (x86-64)
16608   // or EAX and doing an indirect call.  The return value will then
16609   // be in the normal return register.
16610   const X86InstrInfo *TII
16611     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16612   DebugLoc DL = MI->getDebugLoc();
16613   MachineFunction *F = BB->getParent();
16614
16615   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16616   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16617
16618   // Get a register mask for the lowered call.
16619   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16620   // proper register mask.
16621   const uint32_t *RegMask =
16622     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16623   if (Subtarget->is64Bit()) {
16624     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16625                                       TII->get(X86::MOV64rm), X86::RDI)
16626     .addReg(X86::RIP)
16627     .addImm(0).addReg(0)
16628     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16629                       MI->getOperand(3).getTargetFlags())
16630     .addReg(0);
16631     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16632     addDirectMem(MIB, X86::RDI);
16633     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16634   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16635     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16636                                       TII->get(X86::MOV32rm), X86::EAX)
16637     .addReg(0)
16638     .addImm(0).addReg(0)
16639     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16640                       MI->getOperand(3).getTargetFlags())
16641     .addReg(0);
16642     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16643     addDirectMem(MIB, X86::EAX);
16644     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16645   } else {
16646     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16647                                       TII->get(X86::MOV32rm), X86::EAX)
16648     .addReg(TII->getGlobalBaseReg(F))
16649     .addImm(0).addReg(0)
16650     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16651                       MI->getOperand(3).getTargetFlags())
16652     .addReg(0);
16653     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16654     addDirectMem(MIB, X86::EAX);
16655     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16656   }
16657
16658   MI->eraseFromParent(); // The pseudo instruction is gone now.
16659   return BB;
16660 }
16661
16662 MachineBasicBlock *
16663 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16664                                     MachineBasicBlock *MBB) const {
16665   DebugLoc DL = MI->getDebugLoc();
16666   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16667
16668   MachineFunction *MF = MBB->getParent();
16669   MachineRegisterInfo &MRI = MF->getRegInfo();
16670
16671   const BasicBlock *BB = MBB->getBasicBlock();
16672   MachineFunction::iterator I = MBB;
16673   ++I;
16674
16675   // Memory Reference
16676   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16677   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16678
16679   unsigned DstReg;
16680   unsigned MemOpndSlot = 0;
16681
16682   unsigned CurOp = 0;
16683
16684   DstReg = MI->getOperand(CurOp++).getReg();
16685   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16686   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16687   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16688   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16689
16690   MemOpndSlot = CurOp;
16691
16692   MVT PVT = getPointerTy();
16693   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16694          "Invalid Pointer Size!");
16695
16696   // For v = setjmp(buf), we generate
16697   //
16698   // thisMBB:
16699   //  buf[LabelOffset] = restoreMBB
16700   //  SjLjSetup restoreMBB
16701   //
16702   // mainMBB:
16703   //  v_main = 0
16704   //
16705   // sinkMBB:
16706   //  v = phi(main, restore)
16707   //
16708   // restoreMBB:
16709   //  v_restore = 1
16710
16711   MachineBasicBlock *thisMBB = MBB;
16712   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16713   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16714   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16715   MF->insert(I, mainMBB);
16716   MF->insert(I, sinkMBB);
16717   MF->push_back(restoreMBB);
16718
16719   MachineInstrBuilder MIB;
16720
16721   // Transfer the remainder of BB and its successor edges to sinkMBB.
16722   sinkMBB->splice(sinkMBB->begin(), MBB,
16723                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16724   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16725
16726   // thisMBB:
16727   unsigned PtrStoreOpc = 0;
16728   unsigned LabelReg = 0;
16729   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16730   Reloc::Model RM = getTargetMachine().getRelocationModel();
16731   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16732                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16733
16734   // Prepare IP either in reg or imm.
16735   if (!UseImmLabel) {
16736     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16737     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16738     LabelReg = MRI.createVirtualRegister(PtrRC);
16739     if (Subtarget->is64Bit()) {
16740       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16741               .addReg(X86::RIP)
16742               .addImm(0)
16743               .addReg(0)
16744               .addMBB(restoreMBB)
16745               .addReg(0);
16746     } else {
16747       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16748       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16749               .addReg(XII->getGlobalBaseReg(MF))
16750               .addImm(0)
16751               .addReg(0)
16752               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16753               .addReg(0);
16754     }
16755   } else
16756     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16757   // Store IP
16758   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16759   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16760     if (i == X86::AddrDisp)
16761       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16762     else
16763       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16764   }
16765   if (!UseImmLabel)
16766     MIB.addReg(LabelReg);
16767   else
16768     MIB.addMBB(restoreMBB);
16769   MIB.setMemRefs(MMOBegin, MMOEnd);
16770   // Setup
16771   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16772           .addMBB(restoreMBB);
16773
16774   const X86RegisterInfo *RegInfo =
16775     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16776   MIB.addRegMask(RegInfo->getNoPreservedMask());
16777   thisMBB->addSuccessor(mainMBB);
16778   thisMBB->addSuccessor(restoreMBB);
16779
16780   // mainMBB:
16781   //  EAX = 0
16782   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16783   mainMBB->addSuccessor(sinkMBB);
16784
16785   // sinkMBB:
16786   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16787           TII->get(X86::PHI), DstReg)
16788     .addReg(mainDstReg).addMBB(mainMBB)
16789     .addReg(restoreDstReg).addMBB(restoreMBB);
16790
16791   // restoreMBB:
16792   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16793   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16794   restoreMBB->addSuccessor(sinkMBB);
16795
16796   MI->eraseFromParent();
16797   return sinkMBB;
16798 }
16799
16800 MachineBasicBlock *
16801 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16802                                      MachineBasicBlock *MBB) const {
16803   DebugLoc DL = MI->getDebugLoc();
16804   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16805
16806   MachineFunction *MF = MBB->getParent();
16807   MachineRegisterInfo &MRI = MF->getRegInfo();
16808
16809   // Memory Reference
16810   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16811   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16812
16813   MVT PVT = getPointerTy();
16814   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16815          "Invalid Pointer Size!");
16816
16817   const TargetRegisterClass *RC =
16818     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16819   unsigned Tmp = MRI.createVirtualRegister(RC);
16820   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16821   const X86RegisterInfo *RegInfo =
16822     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16823   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16824   unsigned SP = RegInfo->getStackRegister();
16825
16826   MachineInstrBuilder MIB;
16827
16828   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16829   const int64_t SPOffset = 2 * PVT.getStoreSize();
16830
16831   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16832   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16833
16834   // Reload FP
16835   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16836   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16837     MIB.addOperand(MI->getOperand(i));
16838   MIB.setMemRefs(MMOBegin, MMOEnd);
16839   // Reload IP
16840   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16841   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16842     if (i == X86::AddrDisp)
16843       MIB.addDisp(MI->getOperand(i), LabelOffset);
16844     else
16845       MIB.addOperand(MI->getOperand(i));
16846   }
16847   MIB.setMemRefs(MMOBegin, MMOEnd);
16848   // Reload SP
16849   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16850   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16851     if (i == X86::AddrDisp)
16852       MIB.addDisp(MI->getOperand(i), SPOffset);
16853     else
16854       MIB.addOperand(MI->getOperand(i));
16855   }
16856   MIB.setMemRefs(MMOBegin, MMOEnd);
16857   // Jump
16858   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16859
16860   MI->eraseFromParent();
16861   return MBB;
16862 }
16863
16864 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16865 // accumulator loops. Writing back to the accumulator allows the coalescer
16866 // to remove extra copies in the loop.   
16867 MachineBasicBlock *
16868 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16869                                  MachineBasicBlock *MBB) const {
16870   MachineOperand &AddendOp = MI->getOperand(3);
16871
16872   // Bail out early if the addend isn't a register - we can't switch these.
16873   if (!AddendOp.isReg())
16874     return MBB;
16875
16876   MachineFunction &MF = *MBB->getParent();
16877   MachineRegisterInfo &MRI = MF.getRegInfo();
16878
16879   // Check whether the addend is defined by a PHI:
16880   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16881   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16882   if (!AddendDef.isPHI())
16883     return MBB;
16884
16885   // Look for the following pattern:
16886   // loop:
16887   //   %addend = phi [%entry, 0], [%loop, %result]
16888   //   ...
16889   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16890
16891   // Replace with:
16892   //   loop:
16893   //   %addend = phi [%entry, 0], [%loop, %result]
16894   //   ...
16895   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16896
16897   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16898     assert(AddendDef.getOperand(i).isReg());
16899     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16900     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16901     if (&PHISrcInst == MI) {
16902       // Found a matching instruction.
16903       unsigned NewFMAOpc = 0;
16904       switch (MI->getOpcode()) {
16905         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16906         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16907         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16908         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16909         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16910         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16911         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16912         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16913         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16914         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16915         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16916         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16917         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16918         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16919         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16920         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16921         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16922         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16923         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16924         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16925         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16926         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16927         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16928         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16929         default: llvm_unreachable("Unrecognized FMA variant.");
16930       }
16931
16932       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16933       MachineInstrBuilder MIB =
16934         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16935         .addOperand(MI->getOperand(0))
16936         .addOperand(MI->getOperand(3))
16937         .addOperand(MI->getOperand(2))
16938         .addOperand(MI->getOperand(1));
16939       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16940       MI->eraseFromParent();
16941     }
16942   }
16943
16944   return MBB;
16945 }
16946
16947 MachineBasicBlock *
16948 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16949                                                MachineBasicBlock *BB) const {
16950   switch (MI->getOpcode()) {
16951   default: llvm_unreachable("Unexpected instr type to insert");
16952   case X86::TAILJMPd64:
16953   case X86::TAILJMPr64:
16954   case X86::TAILJMPm64:
16955     llvm_unreachable("TAILJMP64 would not be touched here.");
16956   case X86::TCRETURNdi64:
16957   case X86::TCRETURNri64:
16958   case X86::TCRETURNmi64:
16959     return BB;
16960   case X86::WIN_ALLOCA:
16961     return EmitLoweredWinAlloca(MI, BB);
16962   case X86::SEG_ALLOCA_32:
16963     return EmitLoweredSegAlloca(MI, BB, false);
16964   case X86::SEG_ALLOCA_64:
16965     return EmitLoweredSegAlloca(MI, BB, true);
16966   case X86::TLSCall_32:
16967   case X86::TLSCall_64:
16968     return EmitLoweredTLSCall(MI, BB);
16969   case X86::CMOV_GR8:
16970   case X86::CMOV_FR32:
16971   case X86::CMOV_FR64:
16972   case X86::CMOV_V4F32:
16973   case X86::CMOV_V2F64:
16974   case X86::CMOV_V2I64:
16975   case X86::CMOV_V8F32:
16976   case X86::CMOV_V4F64:
16977   case X86::CMOV_V4I64:
16978   case X86::CMOV_V16F32:
16979   case X86::CMOV_V8F64:
16980   case X86::CMOV_V8I64:
16981   case X86::CMOV_GR16:
16982   case X86::CMOV_GR32:
16983   case X86::CMOV_RFP32:
16984   case X86::CMOV_RFP64:
16985   case X86::CMOV_RFP80:
16986     return EmitLoweredSelect(MI, BB);
16987
16988   case X86::FP32_TO_INT16_IN_MEM:
16989   case X86::FP32_TO_INT32_IN_MEM:
16990   case X86::FP32_TO_INT64_IN_MEM:
16991   case X86::FP64_TO_INT16_IN_MEM:
16992   case X86::FP64_TO_INT32_IN_MEM:
16993   case X86::FP64_TO_INT64_IN_MEM:
16994   case X86::FP80_TO_INT16_IN_MEM:
16995   case X86::FP80_TO_INT32_IN_MEM:
16996   case X86::FP80_TO_INT64_IN_MEM: {
16997     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16998     DebugLoc DL = MI->getDebugLoc();
16999
17000     // Change the floating point control register to use "round towards zero"
17001     // mode when truncating to an integer value.
17002     MachineFunction *F = BB->getParent();
17003     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17004     addFrameReference(BuildMI(*BB, MI, DL,
17005                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17006
17007     // Load the old value of the high byte of the control word...
17008     unsigned OldCW =
17009       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17010     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17011                       CWFrameIdx);
17012
17013     // Set the high part to be round to zero...
17014     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17015       .addImm(0xC7F);
17016
17017     // Reload the modified control word now...
17018     addFrameReference(BuildMI(*BB, MI, DL,
17019                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17020
17021     // Restore the memory image of control word to original value
17022     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17023       .addReg(OldCW);
17024
17025     // Get the X86 opcode to use.
17026     unsigned Opc;
17027     switch (MI->getOpcode()) {
17028     default: llvm_unreachable("illegal opcode!");
17029     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17030     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17031     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17032     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17033     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17034     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17035     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17036     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17037     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17038     }
17039
17040     X86AddressMode AM;
17041     MachineOperand &Op = MI->getOperand(0);
17042     if (Op.isReg()) {
17043       AM.BaseType = X86AddressMode::RegBase;
17044       AM.Base.Reg = Op.getReg();
17045     } else {
17046       AM.BaseType = X86AddressMode::FrameIndexBase;
17047       AM.Base.FrameIndex = Op.getIndex();
17048     }
17049     Op = MI->getOperand(1);
17050     if (Op.isImm())
17051       AM.Scale = Op.getImm();
17052     Op = MI->getOperand(2);
17053     if (Op.isImm())
17054       AM.IndexReg = Op.getImm();
17055     Op = MI->getOperand(3);
17056     if (Op.isGlobal()) {
17057       AM.GV = Op.getGlobal();
17058     } else {
17059       AM.Disp = Op.getImm();
17060     }
17061     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17062                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17063
17064     // Reload the original control word now.
17065     addFrameReference(BuildMI(*BB, MI, DL,
17066                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17067
17068     MI->eraseFromParent();   // The pseudo instruction is gone now.
17069     return BB;
17070   }
17071     // String/text processing lowering.
17072   case X86::PCMPISTRM128REG:
17073   case X86::VPCMPISTRM128REG:
17074   case X86::PCMPISTRM128MEM:
17075   case X86::VPCMPISTRM128MEM:
17076   case X86::PCMPESTRM128REG:
17077   case X86::VPCMPESTRM128REG:
17078   case X86::PCMPESTRM128MEM:
17079   case X86::VPCMPESTRM128MEM:
17080     assert(Subtarget->hasSSE42() &&
17081            "Target must have SSE4.2 or AVX features enabled");
17082     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17083
17084   // String/text processing lowering.
17085   case X86::PCMPISTRIREG:
17086   case X86::VPCMPISTRIREG:
17087   case X86::PCMPISTRIMEM:
17088   case X86::VPCMPISTRIMEM:
17089   case X86::PCMPESTRIREG:
17090   case X86::VPCMPESTRIREG:
17091   case X86::PCMPESTRIMEM:
17092   case X86::VPCMPESTRIMEM:
17093     assert(Subtarget->hasSSE42() &&
17094            "Target must have SSE4.2 or AVX features enabled");
17095     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17096
17097   // Thread synchronization.
17098   case X86::MONITOR:
17099     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17100
17101   // xbegin
17102   case X86::XBEGIN:
17103     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17104
17105   // Atomic Lowering.
17106   case X86::ATOMAND8:
17107   case X86::ATOMAND16:
17108   case X86::ATOMAND32:
17109   case X86::ATOMAND64:
17110     // Fall through
17111   case X86::ATOMOR8:
17112   case X86::ATOMOR16:
17113   case X86::ATOMOR32:
17114   case X86::ATOMOR64:
17115     // Fall through
17116   case X86::ATOMXOR16:
17117   case X86::ATOMXOR8:
17118   case X86::ATOMXOR32:
17119   case X86::ATOMXOR64:
17120     // Fall through
17121   case X86::ATOMNAND8:
17122   case X86::ATOMNAND16:
17123   case X86::ATOMNAND32:
17124   case X86::ATOMNAND64:
17125     // Fall through
17126   case X86::ATOMMAX8:
17127   case X86::ATOMMAX16:
17128   case X86::ATOMMAX32:
17129   case X86::ATOMMAX64:
17130     // Fall through
17131   case X86::ATOMMIN8:
17132   case X86::ATOMMIN16:
17133   case X86::ATOMMIN32:
17134   case X86::ATOMMIN64:
17135     // Fall through
17136   case X86::ATOMUMAX8:
17137   case X86::ATOMUMAX16:
17138   case X86::ATOMUMAX32:
17139   case X86::ATOMUMAX64:
17140     // Fall through
17141   case X86::ATOMUMIN8:
17142   case X86::ATOMUMIN16:
17143   case X86::ATOMUMIN32:
17144   case X86::ATOMUMIN64:
17145     return EmitAtomicLoadArith(MI, BB);
17146
17147   // This group does 64-bit operations on a 32-bit host.
17148   case X86::ATOMAND6432:
17149   case X86::ATOMOR6432:
17150   case X86::ATOMXOR6432:
17151   case X86::ATOMNAND6432:
17152   case X86::ATOMADD6432:
17153   case X86::ATOMSUB6432:
17154   case X86::ATOMMAX6432:
17155   case X86::ATOMMIN6432:
17156   case X86::ATOMUMAX6432:
17157   case X86::ATOMUMIN6432:
17158   case X86::ATOMSWAP6432:
17159     return EmitAtomicLoadArith6432(MI, BB);
17160
17161   case X86::VASTART_SAVE_XMM_REGS:
17162     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17163
17164   case X86::VAARG_64:
17165     return EmitVAARG64WithCustomInserter(MI, BB);
17166
17167   case X86::EH_SjLj_SetJmp32:
17168   case X86::EH_SjLj_SetJmp64:
17169     return emitEHSjLjSetJmp(MI, BB);
17170
17171   case X86::EH_SjLj_LongJmp32:
17172   case X86::EH_SjLj_LongJmp64:
17173     return emitEHSjLjLongJmp(MI, BB);
17174
17175   case TargetOpcode::STACKMAP:
17176   case TargetOpcode::PATCHPOINT:
17177     return emitPatchPoint(MI, BB);
17178
17179   case X86::VFMADDPDr213r:
17180   case X86::VFMADDPSr213r:
17181   case X86::VFMADDSDr213r:
17182   case X86::VFMADDSSr213r:
17183   case X86::VFMSUBPDr213r:
17184   case X86::VFMSUBPSr213r:
17185   case X86::VFMSUBSDr213r:
17186   case X86::VFMSUBSSr213r:
17187   case X86::VFNMADDPDr213r:
17188   case X86::VFNMADDPSr213r:
17189   case X86::VFNMADDSDr213r:
17190   case X86::VFNMADDSSr213r:
17191   case X86::VFNMSUBPDr213r:
17192   case X86::VFNMSUBPSr213r:
17193   case X86::VFNMSUBSDr213r:
17194   case X86::VFNMSUBSSr213r:
17195   case X86::VFMADDPDr213rY:
17196   case X86::VFMADDPSr213rY:
17197   case X86::VFMSUBPDr213rY:
17198   case X86::VFMSUBPSr213rY:
17199   case X86::VFNMADDPDr213rY:
17200   case X86::VFNMADDPSr213rY:
17201   case X86::VFNMSUBPDr213rY:
17202   case X86::VFNMSUBPSr213rY:
17203     return emitFMA3Instr(MI, BB);
17204   }
17205 }
17206
17207 //===----------------------------------------------------------------------===//
17208 //                           X86 Optimization Hooks
17209 //===----------------------------------------------------------------------===//
17210
17211 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17212                                                       APInt &KnownZero,
17213                                                       APInt &KnownOne,
17214                                                       const SelectionDAG &DAG,
17215                                                       unsigned Depth) const {
17216   unsigned BitWidth = KnownZero.getBitWidth();
17217   unsigned Opc = Op.getOpcode();
17218   assert((Opc >= ISD::BUILTIN_OP_END ||
17219           Opc == ISD::INTRINSIC_WO_CHAIN ||
17220           Opc == ISD::INTRINSIC_W_CHAIN ||
17221           Opc == ISD::INTRINSIC_VOID) &&
17222          "Should use MaskedValueIsZero if you don't know whether Op"
17223          " is a target node!");
17224
17225   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17226   switch (Opc) {
17227   default: break;
17228   case X86ISD::ADD:
17229   case X86ISD::SUB:
17230   case X86ISD::ADC:
17231   case X86ISD::SBB:
17232   case X86ISD::SMUL:
17233   case X86ISD::UMUL:
17234   case X86ISD::INC:
17235   case X86ISD::DEC:
17236   case X86ISD::OR:
17237   case X86ISD::XOR:
17238   case X86ISD::AND:
17239     // These nodes' second result is a boolean.
17240     if (Op.getResNo() == 0)
17241       break;
17242     // Fallthrough
17243   case X86ISD::SETCC:
17244     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17245     break;
17246   case ISD::INTRINSIC_WO_CHAIN: {
17247     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17248     unsigned NumLoBits = 0;
17249     switch (IntId) {
17250     default: break;
17251     case Intrinsic::x86_sse_movmsk_ps:
17252     case Intrinsic::x86_avx_movmsk_ps_256:
17253     case Intrinsic::x86_sse2_movmsk_pd:
17254     case Intrinsic::x86_avx_movmsk_pd_256:
17255     case Intrinsic::x86_mmx_pmovmskb:
17256     case Intrinsic::x86_sse2_pmovmskb_128:
17257     case Intrinsic::x86_avx2_pmovmskb: {
17258       // High bits of movmskp{s|d}, pmovmskb are known zero.
17259       switch (IntId) {
17260         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17261         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17262         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17263         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17264         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17265         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17266         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17267         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17268       }
17269       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17270       break;
17271     }
17272     }
17273     break;
17274   }
17275   }
17276 }
17277
17278 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17279   SDValue Op,
17280   const SelectionDAG &,
17281   unsigned Depth) const {
17282   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17283   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17284     return Op.getValueType().getScalarType().getSizeInBits();
17285
17286   // Fallback case.
17287   return 1;
17288 }
17289
17290 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17291 /// node is a GlobalAddress + offset.
17292 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17293                                        const GlobalValue* &GA,
17294                                        int64_t &Offset) const {
17295   if (N->getOpcode() == X86ISD::Wrapper) {
17296     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17297       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17298       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17299       return true;
17300     }
17301   }
17302   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17303 }
17304
17305 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17306 /// same as extracting the high 128-bit part of 256-bit vector and then
17307 /// inserting the result into the low part of a new 256-bit vector
17308 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17309   EVT VT = SVOp->getValueType(0);
17310   unsigned NumElems = VT.getVectorNumElements();
17311
17312   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17313   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17314     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17315         SVOp->getMaskElt(j) >= 0)
17316       return false;
17317
17318   return true;
17319 }
17320
17321 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17322 /// same as extracting the low 128-bit part of 256-bit vector and then
17323 /// inserting the result into the high part of a new 256-bit vector
17324 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17325   EVT VT = SVOp->getValueType(0);
17326   unsigned NumElems = VT.getVectorNumElements();
17327
17328   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17329   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17330     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17331         SVOp->getMaskElt(j) >= 0)
17332       return false;
17333
17334   return true;
17335 }
17336
17337 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17338 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17339                                         TargetLowering::DAGCombinerInfo &DCI,
17340                                         const X86Subtarget* Subtarget) {
17341   SDLoc dl(N);
17342   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17343   SDValue V1 = SVOp->getOperand(0);
17344   SDValue V2 = SVOp->getOperand(1);
17345   EVT VT = SVOp->getValueType(0);
17346   unsigned NumElems = VT.getVectorNumElements();
17347
17348   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17349       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17350     //
17351     //                   0,0,0,...
17352     //                      |
17353     //    V      UNDEF    BUILD_VECTOR    UNDEF
17354     //     \      /           \           /
17355     //  CONCAT_VECTOR         CONCAT_VECTOR
17356     //         \                  /
17357     //          \                /
17358     //          RESULT: V + zero extended
17359     //
17360     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17361         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17362         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17363       return SDValue();
17364
17365     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17366       return SDValue();
17367
17368     // To match the shuffle mask, the first half of the mask should
17369     // be exactly the first vector, and all the rest a splat with the
17370     // first element of the second one.
17371     for (unsigned i = 0; i != NumElems/2; ++i)
17372       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17373           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17374         return SDValue();
17375
17376     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17377     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17378       if (Ld->hasNUsesOfValue(1, 0)) {
17379         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17380         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17381         SDValue ResNode =
17382           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17383                                   Ld->getMemoryVT(),
17384                                   Ld->getPointerInfo(),
17385                                   Ld->getAlignment(),
17386                                   false/*isVolatile*/, true/*ReadMem*/,
17387                                   false/*WriteMem*/);
17388
17389         // Make sure the newly-created LOAD is in the same position as Ld in
17390         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17391         // and update uses of Ld's output chain to use the TokenFactor.
17392         if (Ld->hasAnyUseOfValue(1)) {
17393           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17394                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17395           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17396           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17397                                  SDValue(ResNode.getNode(), 1));
17398         }
17399
17400         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17401       }
17402     }
17403
17404     // Emit a zeroed vector and insert the desired subvector on its
17405     // first half.
17406     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17407     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17408     return DCI.CombineTo(N, InsV);
17409   }
17410
17411   //===--------------------------------------------------------------------===//
17412   // Combine some shuffles into subvector extracts and inserts:
17413   //
17414
17415   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17416   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17417     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17418     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17419     return DCI.CombineTo(N, InsV);
17420   }
17421
17422   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17423   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17424     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17425     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17426     return DCI.CombineTo(N, InsV);
17427   }
17428
17429   return SDValue();
17430 }
17431
17432 /// PerformShuffleCombine - Performs several different shuffle combines.
17433 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17434                                      TargetLowering::DAGCombinerInfo &DCI,
17435                                      const X86Subtarget *Subtarget) {
17436   SDLoc dl(N);
17437   EVT VT = N->getValueType(0);
17438
17439   // Don't create instructions with illegal types after legalize types has run.
17440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17441   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17442     return SDValue();
17443
17444   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17445   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17446       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17447     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17448
17449   // Only handle 128 wide vector from here on.
17450   if (!VT.is128BitVector())
17451     return SDValue();
17452
17453   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17454   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17455   // consecutive, non-overlapping, and in the right order.
17456   SmallVector<SDValue, 16> Elts;
17457   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17458     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17459
17460   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17461 }
17462
17463 /// PerformTruncateCombine - Converts truncate operation to
17464 /// a sequence of vector shuffle operations.
17465 /// It is possible when we truncate 256-bit vector to 128-bit vector
17466 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17467                                       TargetLowering::DAGCombinerInfo &DCI,
17468                                       const X86Subtarget *Subtarget)  {
17469   return SDValue();
17470 }
17471
17472 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17473 /// specific shuffle of a load can be folded into a single element load.
17474 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17475 /// shuffles have been customed lowered so we need to handle those here.
17476 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17477                                          TargetLowering::DAGCombinerInfo &DCI) {
17478   if (DCI.isBeforeLegalizeOps())
17479     return SDValue();
17480
17481   SDValue InVec = N->getOperand(0);
17482   SDValue EltNo = N->getOperand(1);
17483
17484   if (!isa<ConstantSDNode>(EltNo))
17485     return SDValue();
17486
17487   EVT VT = InVec.getValueType();
17488
17489   bool HasShuffleIntoBitcast = false;
17490   if (InVec.getOpcode() == ISD::BITCAST) {
17491     // Don't duplicate a load with other uses.
17492     if (!InVec.hasOneUse())
17493       return SDValue();
17494     EVT BCVT = InVec.getOperand(0).getValueType();
17495     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17496       return SDValue();
17497     InVec = InVec.getOperand(0);
17498     HasShuffleIntoBitcast = true;
17499   }
17500
17501   if (!isTargetShuffle(InVec.getOpcode()))
17502     return SDValue();
17503
17504   // Don't duplicate a load with other uses.
17505   if (!InVec.hasOneUse())
17506     return SDValue();
17507
17508   SmallVector<int, 16> ShuffleMask;
17509   bool UnaryShuffle;
17510   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17511                             UnaryShuffle))
17512     return SDValue();
17513
17514   // Select the input vector, guarding against out of range extract vector.
17515   unsigned NumElems = VT.getVectorNumElements();
17516   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17517   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17518   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17519                                          : InVec.getOperand(1);
17520
17521   // If inputs to shuffle are the same for both ops, then allow 2 uses
17522   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17523
17524   if (LdNode.getOpcode() == ISD::BITCAST) {
17525     // Don't duplicate a load with other uses.
17526     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17527       return SDValue();
17528
17529     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17530     LdNode = LdNode.getOperand(0);
17531   }
17532
17533   if (!ISD::isNormalLoad(LdNode.getNode()))
17534     return SDValue();
17535
17536   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17537
17538   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17539     return SDValue();
17540
17541   if (HasShuffleIntoBitcast) {
17542     // If there's a bitcast before the shuffle, check if the load type and
17543     // alignment is valid.
17544     unsigned Align = LN0->getAlignment();
17545     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17546     unsigned NewAlign = TLI.getDataLayout()->
17547       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17548
17549     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17550       return SDValue();
17551   }
17552
17553   // All checks match so transform back to vector_shuffle so that DAG combiner
17554   // can finish the job
17555   SDLoc dl(N);
17556
17557   // Create shuffle node taking into account the case that its a unary shuffle
17558   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17559   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17560                                  InVec.getOperand(0), Shuffle,
17561                                  &ShuffleMask[0]);
17562   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17563   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17564                      EltNo);
17565 }
17566
17567 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17568 /// generation and convert it from being a bunch of shuffles and extracts
17569 /// to a simple store and scalar loads to extract the elements.
17570 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17571                                          TargetLowering::DAGCombinerInfo &DCI) {
17572   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17573   if (NewOp.getNode())
17574     return NewOp;
17575
17576   SDValue InputVector = N->getOperand(0);
17577
17578   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17579   // from mmx to v2i32 has a single usage.
17580   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17581       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17582       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17583     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17584                        N->getValueType(0),
17585                        InputVector.getNode()->getOperand(0));
17586
17587   // Only operate on vectors of 4 elements, where the alternative shuffling
17588   // gets to be more expensive.
17589   if (InputVector.getValueType() != MVT::v4i32)
17590     return SDValue();
17591
17592   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17593   // single use which is a sign-extend or zero-extend, and all elements are
17594   // used.
17595   SmallVector<SDNode *, 4> Uses;
17596   unsigned ExtractedElements = 0;
17597   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17598        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17599     if (UI.getUse().getResNo() != InputVector.getResNo())
17600       return SDValue();
17601
17602     SDNode *Extract = *UI;
17603     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17604       return SDValue();
17605
17606     if (Extract->getValueType(0) != MVT::i32)
17607       return SDValue();
17608     if (!Extract->hasOneUse())
17609       return SDValue();
17610     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17611         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17612       return SDValue();
17613     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17614       return SDValue();
17615
17616     // Record which element was extracted.
17617     ExtractedElements |=
17618       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17619
17620     Uses.push_back(Extract);
17621   }
17622
17623   // If not all the elements were used, this may not be worthwhile.
17624   if (ExtractedElements != 15)
17625     return SDValue();
17626
17627   // Ok, we've now decided to do the transformation.
17628   SDLoc dl(InputVector);
17629
17630   // Store the value to a temporary stack slot.
17631   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17632   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17633                             MachinePointerInfo(), false, false, 0);
17634
17635   // Replace each use (extract) with a load of the appropriate element.
17636   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17637        UE = Uses.end(); UI != UE; ++UI) {
17638     SDNode *Extract = *UI;
17639
17640     // cOMpute the element's address.
17641     SDValue Idx = Extract->getOperand(1);
17642     unsigned EltSize =
17643         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17644     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17645     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17646     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17647
17648     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17649                                      StackPtr, OffsetVal);
17650
17651     // Load the scalar.
17652     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17653                                      ScalarAddr, MachinePointerInfo(),
17654                                      false, false, false, 0);
17655
17656     // Replace the exact with the load.
17657     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17658   }
17659
17660   // The replacement was made in place; don't return anything.
17661   return SDValue();
17662 }
17663
17664 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17665 static std::pair<unsigned, bool>
17666 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17667                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17668   if (!VT.isVector())
17669     return std::make_pair(0, false);
17670
17671   bool NeedSplit = false;
17672   switch (VT.getSimpleVT().SimpleTy) {
17673   default: return std::make_pair(0, false);
17674   case MVT::v32i8:
17675   case MVT::v16i16:
17676   case MVT::v8i32:
17677     if (!Subtarget->hasAVX2())
17678       NeedSplit = true;
17679     if (!Subtarget->hasAVX())
17680       return std::make_pair(0, false);
17681     break;
17682   case MVT::v16i8:
17683   case MVT::v8i16:
17684   case MVT::v4i32:
17685     if (!Subtarget->hasSSE2())
17686       return std::make_pair(0, false);
17687   }
17688
17689   // SSE2 has only a small subset of the operations.
17690   bool hasUnsigned = Subtarget->hasSSE41() ||
17691                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17692   bool hasSigned = Subtarget->hasSSE41() ||
17693                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17694
17695   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17696
17697   unsigned Opc = 0;
17698   // Check for x CC y ? x : y.
17699   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17700       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17701     switch (CC) {
17702     default: break;
17703     case ISD::SETULT:
17704     case ISD::SETULE:
17705       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17706     case ISD::SETUGT:
17707     case ISD::SETUGE:
17708       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17709     case ISD::SETLT:
17710     case ISD::SETLE:
17711       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17712     case ISD::SETGT:
17713     case ISD::SETGE:
17714       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17715     }
17716   // Check for x CC y ? y : x -- a min/max with reversed arms.
17717   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17718              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17719     switch (CC) {
17720     default: break;
17721     case ISD::SETULT:
17722     case ISD::SETULE:
17723       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17724     case ISD::SETUGT:
17725     case ISD::SETUGE:
17726       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17727     case ISD::SETLT:
17728     case ISD::SETLE:
17729       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17730     case ISD::SETGT:
17731     case ISD::SETGE:
17732       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17733     }
17734   }
17735
17736   return std::make_pair(Opc, NeedSplit);
17737 }
17738
17739 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17740 /// nodes.
17741 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17742                                     TargetLowering::DAGCombinerInfo &DCI,
17743                                     const X86Subtarget *Subtarget) {
17744   SDLoc DL(N);
17745   SDValue Cond = N->getOperand(0);
17746   // Get the LHS/RHS of the select.
17747   SDValue LHS = N->getOperand(1);
17748   SDValue RHS = N->getOperand(2);
17749   EVT VT = LHS.getValueType();
17750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17751
17752   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17753   // instructions match the semantics of the common C idiom x<y?x:y but not
17754   // x<=y?x:y, because of how they handle negative zero (which can be
17755   // ignored in unsafe-math mode).
17756   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17757       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17758       (Subtarget->hasSSE2() ||
17759        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17760     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17761
17762     unsigned Opcode = 0;
17763     // Check for x CC y ? x : y.
17764     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17765         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17766       switch (CC) {
17767       default: break;
17768       case ISD::SETULT:
17769         // Converting this to a min would handle NaNs incorrectly, and swapping
17770         // the operands would cause it to handle comparisons between positive
17771         // and negative zero incorrectly.
17772         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17773           if (!DAG.getTarget().Options.UnsafeFPMath &&
17774               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17775             break;
17776           std::swap(LHS, RHS);
17777         }
17778         Opcode = X86ISD::FMIN;
17779         break;
17780       case ISD::SETOLE:
17781         // Converting this to a min would handle comparisons between positive
17782         // and negative zero incorrectly.
17783         if (!DAG.getTarget().Options.UnsafeFPMath &&
17784             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17785           break;
17786         Opcode = X86ISD::FMIN;
17787         break;
17788       case ISD::SETULE:
17789         // Converting this to a min would handle both negative zeros and NaNs
17790         // incorrectly, but we can swap the operands to fix both.
17791         std::swap(LHS, RHS);
17792       case ISD::SETOLT:
17793       case ISD::SETLT:
17794       case ISD::SETLE:
17795         Opcode = X86ISD::FMIN;
17796         break;
17797
17798       case ISD::SETOGE:
17799         // Converting this to a max would handle comparisons between positive
17800         // and negative zero incorrectly.
17801         if (!DAG.getTarget().Options.UnsafeFPMath &&
17802             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17803           break;
17804         Opcode = X86ISD::FMAX;
17805         break;
17806       case ISD::SETUGT:
17807         // Converting this to a max would handle NaNs incorrectly, and swapping
17808         // the operands would cause it to handle comparisons between positive
17809         // and negative zero incorrectly.
17810         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17811           if (!DAG.getTarget().Options.UnsafeFPMath &&
17812               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17813             break;
17814           std::swap(LHS, RHS);
17815         }
17816         Opcode = X86ISD::FMAX;
17817         break;
17818       case ISD::SETUGE:
17819         // Converting this to a max would handle both negative zeros and NaNs
17820         // incorrectly, but we can swap the operands to fix both.
17821         std::swap(LHS, RHS);
17822       case ISD::SETOGT:
17823       case ISD::SETGT:
17824       case ISD::SETGE:
17825         Opcode = X86ISD::FMAX;
17826         break;
17827       }
17828     // Check for x CC y ? y : x -- a min/max with reversed arms.
17829     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17830                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17831       switch (CC) {
17832       default: break;
17833       case ISD::SETOGE:
17834         // Converting this to a min would handle comparisons between positive
17835         // and negative zero incorrectly, and swapping the operands would
17836         // cause it to handle NaNs incorrectly.
17837         if (!DAG.getTarget().Options.UnsafeFPMath &&
17838             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17839           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17840             break;
17841           std::swap(LHS, RHS);
17842         }
17843         Opcode = X86ISD::FMIN;
17844         break;
17845       case ISD::SETUGT:
17846         // Converting this to a min would handle NaNs incorrectly.
17847         if (!DAG.getTarget().Options.UnsafeFPMath &&
17848             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17849           break;
17850         Opcode = X86ISD::FMIN;
17851         break;
17852       case ISD::SETUGE:
17853         // Converting this to a min would handle both negative zeros and NaNs
17854         // incorrectly, but we can swap the operands to fix both.
17855         std::swap(LHS, RHS);
17856       case ISD::SETOGT:
17857       case ISD::SETGT:
17858       case ISD::SETGE:
17859         Opcode = X86ISD::FMIN;
17860         break;
17861
17862       case ISD::SETULT:
17863         // Converting this to a max would handle NaNs incorrectly.
17864         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17865           break;
17866         Opcode = X86ISD::FMAX;
17867         break;
17868       case ISD::SETOLE:
17869         // Converting this to a max would handle comparisons between positive
17870         // and negative zero incorrectly, and swapping the operands would
17871         // cause it to handle NaNs incorrectly.
17872         if (!DAG.getTarget().Options.UnsafeFPMath &&
17873             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17874           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17875             break;
17876           std::swap(LHS, RHS);
17877         }
17878         Opcode = X86ISD::FMAX;
17879         break;
17880       case ISD::SETULE:
17881         // Converting this to a max would handle both negative zeros and NaNs
17882         // incorrectly, but we can swap the operands to fix both.
17883         std::swap(LHS, RHS);
17884       case ISD::SETOLT:
17885       case ISD::SETLT:
17886       case ISD::SETLE:
17887         Opcode = X86ISD::FMAX;
17888         break;
17889       }
17890     }
17891
17892     if (Opcode)
17893       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17894   }
17895
17896   EVT CondVT = Cond.getValueType();
17897   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17898       CondVT.getVectorElementType() == MVT::i1) {
17899     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17900     // lowering on AVX-512. In this case we convert it to
17901     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17902     // The same situation for all 128 and 256-bit vectors of i8 and i16
17903     EVT OpVT = LHS.getValueType();
17904     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17905         (OpVT.getVectorElementType() == MVT::i8 ||
17906          OpVT.getVectorElementType() == MVT::i16)) {
17907       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17908       DCI.AddToWorklist(Cond.getNode());
17909       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17910     }
17911   }
17912   // If this is a select between two integer constants, try to do some
17913   // optimizations.
17914   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17915     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17916       // Don't do this for crazy integer types.
17917       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17918         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17919         // so that TrueC (the true value) is larger than FalseC.
17920         bool NeedsCondInvert = false;
17921
17922         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17923             // Efficiently invertible.
17924             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17925              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17926               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17927           NeedsCondInvert = true;
17928           std::swap(TrueC, FalseC);
17929         }
17930
17931         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17932         if (FalseC->getAPIntValue() == 0 &&
17933             TrueC->getAPIntValue().isPowerOf2()) {
17934           if (NeedsCondInvert) // Invert the condition if needed.
17935             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17936                                DAG.getConstant(1, Cond.getValueType()));
17937
17938           // Zero extend the condition if needed.
17939           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17940
17941           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17942           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17943                              DAG.getConstant(ShAmt, MVT::i8));
17944         }
17945
17946         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17947         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17948           if (NeedsCondInvert) // Invert the condition if needed.
17949             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17950                                DAG.getConstant(1, Cond.getValueType()));
17951
17952           // Zero extend the condition if needed.
17953           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17954                              FalseC->getValueType(0), Cond);
17955           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17956                              SDValue(FalseC, 0));
17957         }
17958
17959         // Optimize cases that will turn into an LEA instruction.  This requires
17960         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17961         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17962           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17963           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17964
17965           bool isFastMultiplier = false;
17966           if (Diff < 10) {
17967             switch ((unsigned char)Diff) {
17968               default: break;
17969               case 1:  // result = add base, cond
17970               case 2:  // result = lea base(    , cond*2)
17971               case 3:  // result = lea base(cond, cond*2)
17972               case 4:  // result = lea base(    , cond*4)
17973               case 5:  // result = lea base(cond, cond*4)
17974               case 8:  // result = lea base(    , cond*8)
17975               case 9:  // result = lea base(cond, cond*8)
17976                 isFastMultiplier = true;
17977                 break;
17978             }
17979           }
17980
17981           if (isFastMultiplier) {
17982             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17983             if (NeedsCondInvert) // Invert the condition if needed.
17984               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17985                                  DAG.getConstant(1, Cond.getValueType()));
17986
17987             // Zero extend the condition if needed.
17988             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17989                                Cond);
17990             // Scale the condition by the difference.
17991             if (Diff != 1)
17992               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17993                                  DAG.getConstant(Diff, Cond.getValueType()));
17994
17995             // Add the base if non-zero.
17996             if (FalseC->getAPIntValue() != 0)
17997               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17998                                  SDValue(FalseC, 0));
17999             return Cond;
18000           }
18001         }
18002       }
18003   }
18004
18005   // Canonicalize max and min:
18006   // (x > y) ? x : y -> (x >= y) ? x : y
18007   // (x < y) ? x : y -> (x <= y) ? x : y
18008   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18009   // the need for an extra compare
18010   // against zero. e.g.
18011   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18012   // subl   %esi, %edi
18013   // testl  %edi, %edi
18014   // movl   $0, %eax
18015   // cmovgl %edi, %eax
18016   // =>
18017   // xorl   %eax, %eax
18018   // subl   %esi, $edi
18019   // cmovsl %eax, %edi
18020   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18021       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18022       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18023     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18024     switch (CC) {
18025     default: break;
18026     case ISD::SETLT:
18027     case ISD::SETGT: {
18028       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18029       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18030                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18031       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18032     }
18033     }
18034   }
18035
18036   // Early exit check
18037   if (!TLI.isTypeLegal(VT))
18038     return SDValue();
18039
18040   // Match VSELECTs into subs with unsigned saturation.
18041   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18042       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18043       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18044        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18045     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18046
18047     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18048     // left side invert the predicate to simplify logic below.
18049     SDValue Other;
18050     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18051       Other = RHS;
18052       CC = ISD::getSetCCInverse(CC, true);
18053     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18054       Other = LHS;
18055     }
18056
18057     if (Other.getNode() && Other->getNumOperands() == 2 &&
18058         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18059       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18060       SDValue CondRHS = Cond->getOperand(1);
18061
18062       // Look for a general sub with unsigned saturation first.
18063       // x >= y ? x-y : 0 --> subus x, y
18064       // x >  y ? x-y : 0 --> subus x, y
18065       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18066           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18067         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18068
18069       // If the RHS is a constant we have to reverse the const canonicalization.
18070       // x > C-1 ? x+-C : 0 --> subus x, C
18071       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18072           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18073         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18074         if (CondRHS.getConstantOperandVal(0) == -A-1)
18075           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18076                              DAG.getConstant(-A, VT));
18077       }
18078
18079       // Another special case: If C was a sign bit, the sub has been
18080       // canonicalized into a xor.
18081       // FIXME: Would it be better to use computeKnownBits to determine whether
18082       //        it's safe to decanonicalize the xor?
18083       // x s< 0 ? x^C : 0 --> subus x, C
18084       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18085           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18086           isSplatVector(OpRHS.getNode())) {
18087         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18088         if (A.isSignBit())
18089           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18090       }
18091     }
18092   }
18093
18094   // Try to match a min/max vector operation.
18095   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18096     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18097     unsigned Opc = ret.first;
18098     bool NeedSplit = ret.second;
18099
18100     if (Opc && NeedSplit) {
18101       unsigned NumElems = VT.getVectorNumElements();
18102       // Extract the LHS vectors
18103       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18104       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18105
18106       // Extract the RHS vectors
18107       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18108       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18109
18110       // Create min/max for each subvector
18111       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18112       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18113
18114       // Merge the result
18115       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18116     } else if (Opc)
18117       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18118   }
18119
18120   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18121   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18122       // Check if SETCC has already been promoted
18123       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18124       // Check that condition value type matches vselect operand type
18125       CondVT == VT) { 
18126
18127     assert(Cond.getValueType().isVector() &&
18128            "vector select expects a vector selector!");
18129
18130     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18131     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18132
18133     if (!TValIsAllOnes && !FValIsAllZeros) {
18134       // Try invert the condition if true value is not all 1s and false value
18135       // is not all 0s.
18136       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18137       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18138
18139       if (TValIsAllZeros || FValIsAllOnes) {
18140         SDValue CC = Cond.getOperand(2);
18141         ISD::CondCode NewCC =
18142           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18143                                Cond.getOperand(0).getValueType().isInteger());
18144         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18145         std::swap(LHS, RHS);
18146         TValIsAllOnes = FValIsAllOnes;
18147         FValIsAllZeros = TValIsAllZeros;
18148       }
18149     }
18150
18151     if (TValIsAllOnes || FValIsAllZeros) {
18152       SDValue Ret;
18153
18154       if (TValIsAllOnes && FValIsAllZeros)
18155         Ret = Cond;
18156       else if (TValIsAllOnes)
18157         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18158                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18159       else if (FValIsAllZeros)
18160         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18161                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18162
18163       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18164     }
18165   }
18166
18167   // Try to fold this VSELECT into a MOVSS/MOVSD
18168   if (N->getOpcode() == ISD::VSELECT &&
18169       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18170     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18171         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18172       bool CanFold = false;
18173       unsigned NumElems = Cond.getNumOperands();
18174       SDValue A = LHS;
18175       SDValue B = RHS;
18176       
18177       if (isZero(Cond.getOperand(0))) {
18178         CanFold = true;
18179
18180         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18181         // fold (vselect <0,-1> -> (movsd A, B)
18182         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18183           CanFold = isAllOnes(Cond.getOperand(i));
18184       } else if (isAllOnes(Cond.getOperand(0))) {
18185         CanFold = true;
18186         std::swap(A, B);
18187
18188         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18189         // fold (vselect <-1,0> -> (movsd B, A)
18190         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18191           CanFold = isZero(Cond.getOperand(i));
18192       }
18193
18194       if (CanFold) {
18195         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18196           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18197         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18198       }
18199
18200       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18201         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18202         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18203         //                             (v2i64 (bitcast B)))))
18204         //
18205         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18206         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18207         //                             (v2f64 (bitcast B)))))
18208         //
18209         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18210         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18211         //                             (v2i64 (bitcast A)))))
18212         //
18213         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18214         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18215         //                             (v2f64 (bitcast A)))))
18216
18217         CanFold = (isZero(Cond.getOperand(0)) &&
18218                    isZero(Cond.getOperand(1)) &&
18219                    isAllOnes(Cond.getOperand(2)) &&
18220                    isAllOnes(Cond.getOperand(3)));
18221
18222         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18223             isAllOnes(Cond.getOperand(1)) &&
18224             isZero(Cond.getOperand(2)) &&
18225             isZero(Cond.getOperand(3))) {
18226           CanFold = true;
18227           std::swap(LHS, RHS);
18228         }
18229
18230         if (CanFold) {
18231           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18232           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18233           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18234           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18235                                                 NewB, DAG);
18236           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18237         }
18238       }
18239     }
18240   }
18241
18242   // If we know that this node is legal then we know that it is going to be
18243   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18244   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18245   // to simplify previous instructions.
18246   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18247       !DCI.isBeforeLegalize() &&
18248       // We explicitly check against v8i16 and v16i16 because, although
18249       // they're marked as Custom, they might only be legal when Cond is a
18250       // build_vector of constants. This will be taken care in a later
18251       // condition.
18252       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18253        VT != MVT::v8i16)) {
18254     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18255
18256     // Don't optimize vector selects that map to mask-registers.
18257     if (BitWidth == 1)
18258       return SDValue();
18259
18260     // Check all uses of that condition operand to check whether it will be
18261     // consumed by non-BLEND instructions, which may depend on all bits are set
18262     // properly.
18263     for (SDNode::use_iterator I = Cond->use_begin(),
18264                               E = Cond->use_end(); I != E; ++I)
18265       if (I->getOpcode() != ISD::VSELECT)
18266         // TODO: Add other opcodes eventually lowered into BLEND.
18267         return SDValue();
18268
18269     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18270     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18271
18272     APInt KnownZero, KnownOne;
18273     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18274                                           DCI.isBeforeLegalizeOps());
18275     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18276         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18277       DCI.CommitTargetLoweringOpt(TLO);
18278   }
18279
18280   return SDValue();
18281 }
18282
18283 // Check whether a boolean test is testing a boolean value generated by
18284 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18285 // code.
18286 //
18287 // Simplify the following patterns:
18288 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18289 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18290 // to (Op EFLAGS Cond)
18291 //
18292 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18293 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18294 // to (Op EFLAGS !Cond)
18295 //
18296 // where Op could be BRCOND or CMOV.
18297 //
18298 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18299   // Quit if not CMP and SUB with its value result used.
18300   if (Cmp.getOpcode() != X86ISD::CMP &&
18301       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18302       return SDValue();
18303
18304   // Quit if not used as a boolean value.
18305   if (CC != X86::COND_E && CC != X86::COND_NE)
18306     return SDValue();
18307
18308   // Check CMP operands. One of them should be 0 or 1 and the other should be
18309   // an SetCC or extended from it.
18310   SDValue Op1 = Cmp.getOperand(0);
18311   SDValue Op2 = Cmp.getOperand(1);
18312
18313   SDValue SetCC;
18314   const ConstantSDNode* C = nullptr;
18315   bool needOppositeCond = (CC == X86::COND_E);
18316   bool checkAgainstTrue = false; // Is it a comparison against 1?
18317
18318   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18319     SetCC = Op2;
18320   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18321     SetCC = Op1;
18322   else // Quit if all operands are not constants.
18323     return SDValue();
18324
18325   if (C->getZExtValue() == 1) {
18326     needOppositeCond = !needOppositeCond;
18327     checkAgainstTrue = true;
18328   } else if (C->getZExtValue() != 0)
18329     // Quit if the constant is neither 0 or 1.
18330     return SDValue();
18331
18332   bool truncatedToBoolWithAnd = false;
18333   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18334   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18335          SetCC.getOpcode() == ISD::TRUNCATE ||
18336          SetCC.getOpcode() == ISD::AND) {
18337     if (SetCC.getOpcode() == ISD::AND) {
18338       int OpIdx = -1;
18339       ConstantSDNode *CS;
18340       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18341           CS->getZExtValue() == 1)
18342         OpIdx = 1;
18343       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18344           CS->getZExtValue() == 1)
18345         OpIdx = 0;
18346       if (OpIdx == -1)
18347         break;
18348       SetCC = SetCC.getOperand(OpIdx);
18349       truncatedToBoolWithAnd = true;
18350     } else
18351       SetCC = SetCC.getOperand(0);
18352   }
18353
18354   switch (SetCC.getOpcode()) {
18355   case X86ISD::SETCC_CARRY:
18356     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18357     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18358     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18359     // truncated to i1 using 'and'.
18360     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18361       break;
18362     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18363            "Invalid use of SETCC_CARRY!");
18364     // FALL THROUGH
18365   case X86ISD::SETCC:
18366     // Set the condition code or opposite one if necessary.
18367     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18368     if (needOppositeCond)
18369       CC = X86::GetOppositeBranchCondition(CC);
18370     return SetCC.getOperand(1);
18371   case X86ISD::CMOV: {
18372     // Check whether false/true value has canonical one, i.e. 0 or 1.
18373     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18374     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18375     // Quit if true value is not a constant.
18376     if (!TVal)
18377       return SDValue();
18378     // Quit if false value is not a constant.
18379     if (!FVal) {
18380       SDValue Op = SetCC.getOperand(0);
18381       // Skip 'zext' or 'trunc' node.
18382       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18383           Op.getOpcode() == ISD::TRUNCATE)
18384         Op = Op.getOperand(0);
18385       // A special case for rdrand/rdseed, where 0 is set if false cond is
18386       // found.
18387       if ((Op.getOpcode() != X86ISD::RDRAND &&
18388            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18389         return SDValue();
18390     }
18391     // Quit if false value is not the constant 0 or 1.
18392     bool FValIsFalse = true;
18393     if (FVal && FVal->getZExtValue() != 0) {
18394       if (FVal->getZExtValue() != 1)
18395         return SDValue();
18396       // If FVal is 1, opposite cond is needed.
18397       needOppositeCond = !needOppositeCond;
18398       FValIsFalse = false;
18399     }
18400     // Quit if TVal is not the constant opposite of FVal.
18401     if (FValIsFalse && TVal->getZExtValue() != 1)
18402       return SDValue();
18403     if (!FValIsFalse && TVal->getZExtValue() != 0)
18404       return SDValue();
18405     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18406     if (needOppositeCond)
18407       CC = X86::GetOppositeBranchCondition(CC);
18408     return SetCC.getOperand(3);
18409   }
18410   }
18411
18412   return SDValue();
18413 }
18414
18415 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18416 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18417                                   TargetLowering::DAGCombinerInfo &DCI,
18418                                   const X86Subtarget *Subtarget) {
18419   SDLoc DL(N);
18420
18421   // If the flag operand isn't dead, don't touch this CMOV.
18422   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18423     return SDValue();
18424
18425   SDValue FalseOp = N->getOperand(0);
18426   SDValue TrueOp = N->getOperand(1);
18427   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18428   SDValue Cond = N->getOperand(3);
18429
18430   if (CC == X86::COND_E || CC == X86::COND_NE) {
18431     switch (Cond.getOpcode()) {
18432     default: break;
18433     case X86ISD::BSR:
18434     case X86ISD::BSF:
18435       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18436       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18437         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18438     }
18439   }
18440
18441   SDValue Flags;
18442
18443   Flags = checkBoolTestSetCCCombine(Cond, CC);
18444   if (Flags.getNode() &&
18445       // Extra check as FCMOV only supports a subset of X86 cond.
18446       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18447     SDValue Ops[] = { FalseOp, TrueOp,
18448                       DAG.getConstant(CC, MVT::i8), Flags };
18449     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18450   }
18451
18452   // If this is a select between two integer constants, try to do some
18453   // optimizations.  Note that the operands are ordered the opposite of SELECT
18454   // operands.
18455   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18456     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18457       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18458       // larger than FalseC (the false value).
18459       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18460         CC = X86::GetOppositeBranchCondition(CC);
18461         std::swap(TrueC, FalseC);
18462         std::swap(TrueOp, FalseOp);
18463       }
18464
18465       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18466       // This is efficient for any integer data type (including i8/i16) and
18467       // shift amount.
18468       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18469         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18470                            DAG.getConstant(CC, MVT::i8), Cond);
18471
18472         // Zero extend the condition if needed.
18473         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18474
18475         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18476         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18477                            DAG.getConstant(ShAmt, MVT::i8));
18478         if (N->getNumValues() == 2)  // Dead flag value?
18479           return DCI.CombineTo(N, Cond, SDValue());
18480         return Cond;
18481       }
18482
18483       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18484       // for any integer data type, including i8/i16.
18485       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18486         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18487                            DAG.getConstant(CC, MVT::i8), Cond);
18488
18489         // Zero extend the condition if needed.
18490         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18491                            FalseC->getValueType(0), Cond);
18492         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18493                            SDValue(FalseC, 0));
18494
18495         if (N->getNumValues() == 2)  // Dead flag value?
18496           return DCI.CombineTo(N, Cond, SDValue());
18497         return Cond;
18498       }
18499
18500       // Optimize cases that will turn into an LEA instruction.  This requires
18501       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18502       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18503         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18504         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18505
18506         bool isFastMultiplier = false;
18507         if (Diff < 10) {
18508           switch ((unsigned char)Diff) {
18509           default: break;
18510           case 1:  // result = add base, cond
18511           case 2:  // result = lea base(    , cond*2)
18512           case 3:  // result = lea base(cond, cond*2)
18513           case 4:  // result = lea base(    , cond*4)
18514           case 5:  // result = lea base(cond, cond*4)
18515           case 8:  // result = lea base(    , cond*8)
18516           case 9:  // result = lea base(cond, cond*8)
18517             isFastMultiplier = true;
18518             break;
18519           }
18520         }
18521
18522         if (isFastMultiplier) {
18523           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18524           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18525                              DAG.getConstant(CC, MVT::i8), Cond);
18526           // Zero extend the condition if needed.
18527           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18528                              Cond);
18529           // Scale the condition by the difference.
18530           if (Diff != 1)
18531             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18532                                DAG.getConstant(Diff, Cond.getValueType()));
18533
18534           // Add the base if non-zero.
18535           if (FalseC->getAPIntValue() != 0)
18536             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18537                                SDValue(FalseC, 0));
18538           if (N->getNumValues() == 2)  // Dead flag value?
18539             return DCI.CombineTo(N, Cond, SDValue());
18540           return Cond;
18541         }
18542       }
18543     }
18544   }
18545
18546   // Handle these cases:
18547   //   (select (x != c), e, c) -> select (x != c), e, x),
18548   //   (select (x == c), c, e) -> select (x == c), x, e)
18549   // where the c is an integer constant, and the "select" is the combination
18550   // of CMOV and CMP.
18551   //
18552   // The rationale for this change is that the conditional-move from a constant
18553   // needs two instructions, however, conditional-move from a register needs
18554   // only one instruction.
18555   //
18556   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18557   //  some instruction-combining opportunities. This opt needs to be
18558   //  postponed as late as possible.
18559   //
18560   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18561     // the DCI.xxxx conditions are provided to postpone the optimization as
18562     // late as possible.
18563
18564     ConstantSDNode *CmpAgainst = nullptr;
18565     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18566         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18567         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18568
18569       if (CC == X86::COND_NE &&
18570           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18571         CC = X86::GetOppositeBranchCondition(CC);
18572         std::swap(TrueOp, FalseOp);
18573       }
18574
18575       if (CC == X86::COND_E &&
18576           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18577         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18578                           DAG.getConstant(CC, MVT::i8), Cond };
18579         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18580       }
18581     }
18582   }
18583
18584   return SDValue();
18585 }
18586
18587 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18588                                                 const X86Subtarget *Subtarget) {
18589   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18590   switch (IntNo) {
18591   default: return SDValue();
18592   // SSE/AVX/AVX2 blend intrinsics.
18593   case Intrinsic::x86_avx2_pblendvb:
18594   case Intrinsic::x86_avx2_pblendw:
18595   case Intrinsic::x86_avx2_pblendd_128:
18596   case Intrinsic::x86_avx2_pblendd_256:
18597     // Don't try to simplify this intrinsic if we don't have AVX2.
18598     if (!Subtarget->hasAVX2())
18599       return SDValue();
18600     // FALL-THROUGH
18601   case Intrinsic::x86_avx_blend_pd_256:
18602   case Intrinsic::x86_avx_blend_ps_256:
18603   case Intrinsic::x86_avx_blendv_pd_256:
18604   case Intrinsic::x86_avx_blendv_ps_256:
18605     // Don't try to simplify this intrinsic if we don't have AVX.
18606     if (!Subtarget->hasAVX())
18607       return SDValue();
18608     // FALL-THROUGH
18609   case Intrinsic::x86_sse41_pblendw:
18610   case Intrinsic::x86_sse41_blendpd:
18611   case Intrinsic::x86_sse41_blendps:
18612   case Intrinsic::x86_sse41_blendvps:
18613   case Intrinsic::x86_sse41_blendvpd:
18614   case Intrinsic::x86_sse41_pblendvb: {
18615     SDValue Op0 = N->getOperand(1);
18616     SDValue Op1 = N->getOperand(2);
18617     SDValue Mask = N->getOperand(3);
18618
18619     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18620     if (!Subtarget->hasSSE41())
18621       return SDValue();
18622
18623     // fold (blend A, A, Mask) -> A
18624     if (Op0 == Op1)
18625       return Op0;
18626     // fold (blend A, B, allZeros) -> A
18627     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18628       return Op0;
18629     // fold (blend A, B, allOnes) -> B
18630     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18631       return Op1;
18632     
18633     // Simplify the case where the mask is a constant i32 value.
18634     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18635       if (C->isNullValue())
18636         return Op0;
18637       if (C->isAllOnesValue())
18638         return Op1;
18639     }
18640   }
18641
18642   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18643   case Intrinsic::x86_sse2_psrai_w:
18644   case Intrinsic::x86_sse2_psrai_d:
18645   case Intrinsic::x86_avx2_psrai_w:
18646   case Intrinsic::x86_avx2_psrai_d:
18647   case Intrinsic::x86_sse2_psra_w:
18648   case Intrinsic::x86_sse2_psra_d:
18649   case Intrinsic::x86_avx2_psra_w:
18650   case Intrinsic::x86_avx2_psra_d: {
18651     SDValue Op0 = N->getOperand(1);
18652     SDValue Op1 = N->getOperand(2);
18653     EVT VT = Op0.getValueType();
18654     assert(VT.isVector() && "Expected a vector type!");
18655
18656     if (isa<BuildVectorSDNode>(Op1))
18657       Op1 = Op1.getOperand(0);
18658
18659     if (!isa<ConstantSDNode>(Op1))
18660       return SDValue();
18661
18662     EVT SVT = VT.getVectorElementType();
18663     unsigned SVTBits = SVT.getSizeInBits();
18664
18665     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18666     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18667     uint64_t ShAmt = C.getZExtValue();
18668
18669     // Don't try to convert this shift into a ISD::SRA if the shift
18670     // count is bigger than or equal to the element size.
18671     if (ShAmt >= SVTBits)
18672       return SDValue();
18673
18674     // Trivial case: if the shift count is zero, then fold this
18675     // into the first operand.
18676     if (ShAmt == 0)
18677       return Op0;
18678
18679     // Replace this packed shift intrinsic with a target independent
18680     // shift dag node.
18681     SDValue Splat = DAG.getConstant(C, VT);
18682     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18683   }
18684   }
18685 }
18686
18687 /// PerformMulCombine - Optimize a single multiply with constant into two
18688 /// in order to implement it with two cheaper instructions, e.g.
18689 /// LEA + SHL, LEA + LEA.
18690 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18691                                  TargetLowering::DAGCombinerInfo &DCI) {
18692   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18693     return SDValue();
18694
18695   EVT VT = N->getValueType(0);
18696   if (VT != MVT::i64)
18697     return SDValue();
18698
18699   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18700   if (!C)
18701     return SDValue();
18702   uint64_t MulAmt = C->getZExtValue();
18703   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18704     return SDValue();
18705
18706   uint64_t MulAmt1 = 0;
18707   uint64_t MulAmt2 = 0;
18708   if ((MulAmt % 9) == 0) {
18709     MulAmt1 = 9;
18710     MulAmt2 = MulAmt / 9;
18711   } else if ((MulAmt % 5) == 0) {
18712     MulAmt1 = 5;
18713     MulAmt2 = MulAmt / 5;
18714   } else if ((MulAmt % 3) == 0) {
18715     MulAmt1 = 3;
18716     MulAmt2 = MulAmt / 3;
18717   }
18718   if (MulAmt2 &&
18719       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18720     SDLoc DL(N);
18721
18722     if (isPowerOf2_64(MulAmt2) &&
18723         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18724       // If second multiplifer is pow2, issue it first. We want the multiply by
18725       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18726       // is an add.
18727       std::swap(MulAmt1, MulAmt2);
18728
18729     SDValue NewMul;
18730     if (isPowerOf2_64(MulAmt1))
18731       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18732                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18733     else
18734       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18735                            DAG.getConstant(MulAmt1, VT));
18736
18737     if (isPowerOf2_64(MulAmt2))
18738       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18739                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18740     else
18741       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18742                            DAG.getConstant(MulAmt2, VT));
18743
18744     // Do not add new nodes to DAG combiner worklist.
18745     DCI.CombineTo(N, NewMul, false);
18746   }
18747   return SDValue();
18748 }
18749
18750 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18751   SDValue N0 = N->getOperand(0);
18752   SDValue N1 = N->getOperand(1);
18753   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18754   EVT VT = N0.getValueType();
18755
18756   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18757   // since the result of setcc_c is all zero's or all ones.
18758   if (VT.isInteger() && !VT.isVector() &&
18759       N1C && N0.getOpcode() == ISD::AND &&
18760       N0.getOperand(1).getOpcode() == ISD::Constant) {
18761     SDValue N00 = N0.getOperand(0);
18762     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18763         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18764           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18765          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18766       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18767       APInt ShAmt = N1C->getAPIntValue();
18768       Mask = Mask.shl(ShAmt);
18769       if (Mask != 0)
18770         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18771                            N00, DAG.getConstant(Mask, VT));
18772     }
18773   }
18774
18775   // Hardware support for vector shifts is sparse which makes us scalarize the
18776   // vector operations in many cases. Also, on sandybridge ADD is faster than
18777   // shl.
18778   // (shl V, 1) -> add V,V
18779   if (isSplatVector(N1.getNode())) {
18780     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18781     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18782     // We shift all of the values by one. In many cases we do not have
18783     // hardware support for this operation. This is better expressed as an ADD
18784     // of two values.
18785     if (N1C && (1 == N1C->getZExtValue())) {
18786       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18787     }
18788   }
18789
18790   return SDValue();
18791 }
18792
18793 /// \brief Returns a vector of 0s if the node in input is a vector logical
18794 /// shift by a constant amount which is known to be bigger than or equal
18795 /// to the vector element size in bits.
18796 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18797                                       const X86Subtarget *Subtarget) {
18798   EVT VT = N->getValueType(0);
18799
18800   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18801       (!Subtarget->hasInt256() ||
18802        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18803     return SDValue();
18804
18805   SDValue Amt = N->getOperand(1);
18806   SDLoc DL(N);
18807   if (isSplatVector(Amt.getNode())) {
18808     SDValue SclrAmt = Amt->getOperand(0);
18809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18810       APInt ShiftAmt = C->getAPIntValue();
18811       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18812
18813       // SSE2/AVX2 logical shifts always return a vector of 0s
18814       // if the shift amount is bigger than or equal to
18815       // the element size. The constant shift amount will be
18816       // encoded as a 8-bit immediate.
18817       if (ShiftAmt.trunc(8).uge(MaxAmount))
18818         return getZeroVector(VT, Subtarget, DAG, DL);
18819     }
18820   }
18821
18822   return SDValue();
18823 }
18824
18825 /// PerformShiftCombine - Combine shifts.
18826 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18827                                    TargetLowering::DAGCombinerInfo &DCI,
18828                                    const X86Subtarget *Subtarget) {
18829   if (N->getOpcode() == ISD::SHL) {
18830     SDValue V = PerformSHLCombine(N, DAG);
18831     if (V.getNode()) return V;
18832   }
18833
18834   if (N->getOpcode() != ISD::SRA) {
18835     // Try to fold this logical shift into a zero vector.
18836     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18837     if (V.getNode()) return V;
18838   }
18839
18840   return SDValue();
18841 }
18842
18843 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18844 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18845 // and friends.  Likewise for OR -> CMPNEQSS.
18846 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18847                             TargetLowering::DAGCombinerInfo &DCI,
18848                             const X86Subtarget *Subtarget) {
18849   unsigned opcode;
18850
18851   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18852   // we're requiring SSE2 for both.
18853   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18854     SDValue N0 = N->getOperand(0);
18855     SDValue N1 = N->getOperand(1);
18856     SDValue CMP0 = N0->getOperand(1);
18857     SDValue CMP1 = N1->getOperand(1);
18858     SDLoc DL(N);
18859
18860     // The SETCCs should both refer to the same CMP.
18861     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18862       return SDValue();
18863
18864     SDValue CMP00 = CMP0->getOperand(0);
18865     SDValue CMP01 = CMP0->getOperand(1);
18866     EVT     VT    = CMP00.getValueType();
18867
18868     if (VT == MVT::f32 || VT == MVT::f64) {
18869       bool ExpectingFlags = false;
18870       // Check for any users that want flags:
18871       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18872            !ExpectingFlags && UI != UE; ++UI)
18873         switch (UI->getOpcode()) {
18874         default:
18875         case ISD::BR_CC:
18876         case ISD::BRCOND:
18877         case ISD::SELECT:
18878           ExpectingFlags = true;
18879           break;
18880         case ISD::CopyToReg:
18881         case ISD::SIGN_EXTEND:
18882         case ISD::ZERO_EXTEND:
18883         case ISD::ANY_EXTEND:
18884           break;
18885         }
18886
18887       if (!ExpectingFlags) {
18888         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18889         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18890
18891         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18892           X86::CondCode tmp = cc0;
18893           cc0 = cc1;
18894           cc1 = tmp;
18895         }
18896
18897         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18898             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18899           // FIXME: need symbolic constants for these magic numbers.
18900           // See X86ATTInstPrinter.cpp:printSSECC().
18901           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18902           if (Subtarget->hasAVX512()) {
18903             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18904                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18905             if (N->getValueType(0) != MVT::i1)
18906               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18907                                  FSetCC);
18908             return FSetCC;
18909           }
18910           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18911                                               CMP00.getValueType(), CMP00, CMP01,
18912                                               DAG.getConstant(x86cc, MVT::i8));
18913
18914           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18915           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18916
18917           if (is64BitFP && !Subtarget->is64Bit()) {
18918             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18919             // 64-bit integer, since that's not a legal type. Since
18920             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18921             // bits, but can do this little dance to extract the lowest 32 bits
18922             // and work with those going forward.
18923             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18924                                            OnesOrZeroesF);
18925             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18926                                            Vector64);
18927             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18928                                         Vector32, DAG.getIntPtrConstant(0));
18929             IntVT = MVT::i32;
18930           }
18931
18932           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18933           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18934                                       DAG.getConstant(1, IntVT));
18935           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18936           return OneBitOfTruth;
18937         }
18938       }
18939     }
18940   }
18941   return SDValue();
18942 }
18943
18944 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18945 /// so it can be folded inside ANDNP.
18946 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18947   EVT VT = N->getValueType(0);
18948
18949   // Match direct AllOnes for 128 and 256-bit vectors
18950   if (ISD::isBuildVectorAllOnes(N))
18951     return true;
18952
18953   // Look through a bit convert.
18954   if (N->getOpcode() == ISD::BITCAST)
18955     N = N->getOperand(0).getNode();
18956
18957   // Sometimes the operand may come from a insert_subvector building a 256-bit
18958   // allones vector
18959   if (VT.is256BitVector() &&
18960       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18961     SDValue V1 = N->getOperand(0);
18962     SDValue V2 = N->getOperand(1);
18963
18964     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18965         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18966         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18967         ISD::isBuildVectorAllOnes(V2.getNode()))
18968       return true;
18969   }
18970
18971   return false;
18972 }
18973
18974 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18975 // register. In most cases we actually compare or select YMM-sized registers
18976 // and mixing the two types creates horrible code. This method optimizes
18977 // some of the transition sequences.
18978 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18979                                  TargetLowering::DAGCombinerInfo &DCI,
18980                                  const X86Subtarget *Subtarget) {
18981   EVT VT = N->getValueType(0);
18982   if (!VT.is256BitVector())
18983     return SDValue();
18984
18985   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18986           N->getOpcode() == ISD::ZERO_EXTEND ||
18987           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18988
18989   SDValue Narrow = N->getOperand(0);
18990   EVT NarrowVT = Narrow->getValueType(0);
18991   if (!NarrowVT.is128BitVector())
18992     return SDValue();
18993
18994   if (Narrow->getOpcode() != ISD::XOR &&
18995       Narrow->getOpcode() != ISD::AND &&
18996       Narrow->getOpcode() != ISD::OR)
18997     return SDValue();
18998
18999   SDValue N0  = Narrow->getOperand(0);
19000   SDValue N1  = Narrow->getOperand(1);
19001   SDLoc DL(Narrow);
19002
19003   // The Left side has to be a trunc.
19004   if (N0.getOpcode() != ISD::TRUNCATE)
19005     return SDValue();
19006
19007   // The type of the truncated inputs.
19008   EVT WideVT = N0->getOperand(0)->getValueType(0);
19009   if (WideVT != VT)
19010     return SDValue();
19011
19012   // The right side has to be a 'trunc' or a constant vector.
19013   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19014   bool RHSConst = (isSplatVector(N1.getNode()) &&
19015                    isa<ConstantSDNode>(N1->getOperand(0)));
19016   if (!RHSTrunc && !RHSConst)
19017     return SDValue();
19018
19019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19020
19021   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19022     return SDValue();
19023
19024   // Set N0 and N1 to hold the inputs to the new wide operation.
19025   N0 = N0->getOperand(0);
19026   if (RHSConst) {
19027     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19028                      N1->getOperand(0));
19029     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19030     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19031   } else if (RHSTrunc) {
19032     N1 = N1->getOperand(0);
19033   }
19034
19035   // Generate the wide operation.
19036   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19037   unsigned Opcode = N->getOpcode();
19038   switch (Opcode) {
19039   case ISD::ANY_EXTEND:
19040     return Op;
19041   case ISD::ZERO_EXTEND: {
19042     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19043     APInt Mask = APInt::getAllOnesValue(InBits);
19044     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19045     return DAG.getNode(ISD::AND, DL, VT,
19046                        Op, DAG.getConstant(Mask, VT));
19047   }
19048   case ISD::SIGN_EXTEND:
19049     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19050                        Op, DAG.getValueType(NarrowVT));
19051   default:
19052     llvm_unreachable("Unexpected opcode");
19053   }
19054 }
19055
19056 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19057                                  TargetLowering::DAGCombinerInfo &DCI,
19058                                  const X86Subtarget *Subtarget) {
19059   EVT VT = N->getValueType(0);
19060   if (DCI.isBeforeLegalizeOps())
19061     return SDValue();
19062
19063   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19064   if (R.getNode())
19065     return R;
19066
19067   // Create BEXTR instructions
19068   // BEXTR is ((X >> imm) & (2**size-1))
19069   if (VT == MVT::i32 || VT == MVT::i64) {
19070     SDValue N0 = N->getOperand(0);
19071     SDValue N1 = N->getOperand(1);
19072     SDLoc DL(N);
19073
19074     // Check for BEXTR.
19075     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19076         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19077       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19078       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19079       if (MaskNode && ShiftNode) {
19080         uint64_t Mask = MaskNode->getZExtValue();
19081         uint64_t Shift = ShiftNode->getZExtValue();
19082         if (isMask_64(Mask)) {
19083           uint64_t MaskSize = CountPopulation_64(Mask);
19084           if (Shift + MaskSize <= VT.getSizeInBits())
19085             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19086                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19087         }
19088       }
19089     } // BEXTR
19090
19091     return SDValue();
19092   }
19093
19094   // Want to form ANDNP nodes:
19095   // 1) In the hopes of then easily combining them with OR and AND nodes
19096   //    to form PBLEND/PSIGN.
19097   // 2) To match ANDN packed intrinsics
19098   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19099     return SDValue();
19100
19101   SDValue N0 = N->getOperand(0);
19102   SDValue N1 = N->getOperand(1);
19103   SDLoc DL(N);
19104
19105   // Check LHS for vnot
19106   if (N0.getOpcode() == ISD::XOR &&
19107       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19108       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19109     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19110
19111   // Check RHS for vnot
19112   if (N1.getOpcode() == ISD::XOR &&
19113       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19114       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19115     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19116
19117   return SDValue();
19118 }
19119
19120 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19121                                 TargetLowering::DAGCombinerInfo &DCI,
19122                                 const X86Subtarget *Subtarget) {
19123   if (DCI.isBeforeLegalizeOps())
19124     return SDValue();
19125
19126   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19127   if (R.getNode())
19128     return R;
19129
19130   SDValue N0 = N->getOperand(0);
19131   SDValue N1 = N->getOperand(1);
19132   EVT VT = N->getValueType(0);
19133
19134   // look for psign/blend
19135   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19136     if (!Subtarget->hasSSSE3() ||
19137         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19138       return SDValue();
19139
19140     // Canonicalize pandn to RHS
19141     if (N0.getOpcode() == X86ISD::ANDNP)
19142       std::swap(N0, N1);
19143     // or (and (m, y), (pandn m, x))
19144     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19145       SDValue Mask = N1.getOperand(0);
19146       SDValue X    = N1.getOperand(1);
19147       SDValue Y;
19148       if (N0.getOperand(0) == Mask)
19149         Y = N0.getOperand(1);
19150       if (N0.getOperand(1) == Mask)
19151         Y = N0.getOperand(0);
19152
19153       // Check to see if the mask appeared in both the AND and ANDNP and
19154       if (!Y.getNode())
19155         return SDValue();
19156
19157       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19158       // Look through mask bitcast.
19159       if (Mask.getOpcode() == ISD::BITCAST)
19160         Mask = Mask.getOperand(0);
19161       if (X.getOpcode() == ISD::BITCAST)
19162         X = X.getOperand(0);
19163       if (Y.getOpcode() == ISD::BITCAST)
19164         Y = Y.getOperand(0);
19165
19166       EVT MaskVT = Mask.getValueType();
19167
19168       // Validate that the Mask operand is a vector sra node.
19169       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19170       // there is no psrai.b
19171       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19172       unsigned SraAmt = ~0;
19173       if (Mask.getOpcode() == ISD::SRA) {
19174         SDValue Amt = Mask.getOperand(1);
19175         if (isSplatVector(Amt.getNode())) {
19176           SDValue SclrAmt = Amt->getOperand(0);
19177           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19178             SraAmt = C->getZExtValue();
19179         }
19180       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19181         SDValue SraC = Mask.getOperand(1);
19182         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19183       }
19184       if ((SraAmt + 1) != EltBits)
19185         return SDValue();
19186
19187       SDLoc DL(N);
19188
19189       // Now we know we at least have a plendvb with the mask val.  See if
19190       // we can form a psignb/w/d.
19191       // psign = x.type == y.type == mask.type && y = sub(0, x);
19192       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19193           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19194           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19195         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19196                "Unsupported VT for PSIGN");
19197         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19198         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19199       }
19200       // PBLENDVB only available on SSE 4.1
19201       if (!Subtarget->hasSSE41())
19202         return SDValue();
19203
19204       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19205
19206       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19207       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19208       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19209       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19210       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19211     }
19212   }
19213
19214   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19215     return SDValue();
19216
19217   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19218   MachineFunction &MF = DAG.getMachineFunction();
19219   bool OptForSize = MF.getFunction()->getAttributes().
19220     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19221
19222   // SHLD/SHRD instructions have lower register pressure, but on some
19223   // platforms they have higher latency than the equivalent
19224   // series of shifts/or that would otherwise be generated.
19225   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19226   // have higher latencies and we are not optimizing for size.
19227   if (!OptForSize && Subtarget->isSHLDSlow())
19228     return SDValue();
19229
19230   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19231     std::swap(N0, N1);
19232   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19233     return SDValue();
19234   if (!N0.hasOneUse() || !N1.hasOneUse())
19235     return SDValue();
19236
19237   SDValue ShAmt0 = N0.getOperand(1);
19238   if (ShAmt0.getValueType() != MVT::i8)
19239     return SDValue();
19240   SDValue ShAmt1 = N1.getOperand(1);
19241   if (ShAmt1.getValueType() != MVT::i8)
19242     return SDValue();
19243   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19244     ShAmt0 = ShAmt0.getOperand(0);
19245   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19246     ShAmt1 = ShAmt1.getOperand(0);
19247
19248   SDLoc DL(N);
19249   unsigned Opc = X86ISD::SHLD;
19250   SDValue Op0 = N0.getOperand(0);
19251   SDValue Op1 = N1.getOperand(0);
19252   if (ShAmt0.getOpcode() == ISD::SUB) {
19253     Opc = X86ISD::SHRD;
19254     std::swap(Op0, Op1);
19255     std::swap(ShAmt0, ShAmt1);
19256   }
19257
19258   unsigned Bits = VT.getSizeInBits();
19259   if (ShAmt1.getOpcode() == ISD::SUB) {
19260     SDValue Sum = ShAmt1.getOperand(0);
19261     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19262       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19263       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19264         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19265       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19266         return DAG.getNode(Opc, DL, VT,
19267                            Op0, Op1,
19268                            DAG.getNode(ISD::TRUNCATE, DL,
19269                                        MVT::i8, ShAmt0));
19270     }
19271   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19272     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19273     if (ShAmt0C &&
19274         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19275       return DAG.getNode(Opc, DL, VT,
19276                          N0.getOperand(0), N1.getOperand(0),
19277                          DAG.getNode(ISD::TRUNCATE, DL,
19278                                        MVT::i8, ShAmt0));
19279   }
19280
19281   return SDValue();
19282 }
19283
19284 // Generate NEG and CMOV for integer abs.
19285 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19286   EVT VT = N->getValueType(0);
19287
19288   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19289   // 8-bit integer abs to NEG and CMOV.
19290   if (VT.isInteger() && VT.getSizeInBits() == 8)
19291     return SDValue();
19292
19293   SDValue N0 = N->getOperand(0);
19294   SDValue N1 = N->getOperand(1);
19295   SDLoc DL(N);
19296
19297   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19298   // and change it to SUB and CMOV.
19299   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19300       N0.getOpcode() == ISD::ADD &&
19301       N0.getOperand(1) == N1 &&
19302       N1.getOpcode() == ISD::SRA &&
19303       N1.getOperand(0) == N0.getOperand(0))
19304     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19305       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19306         // Generate SUB & CMOV.
19307         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19308                                   DAG.getConstant(0, VT), N0.getOperand(0));
19309
19310         SDValue Ops[] = { N0.getOperand(0), Neg,
19311                           DAG.getConstant(X86::COND_GE, MVT::i8),
19312                           SDValue(Neg.getNode(), 1) };
19313         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19314       }
19315   return SDValue();
19316 }
19317
19318 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19319 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19320                                  TargetLowering::DAGCombinerInfo &DCI,
19321                                  const X86Subtarget *Subtarget) {
19322   if (DCI.isBeforeLegalizeOps())
19323     return SDValue();
19324
19325   if (Subtarget->hasCMov()) {
19326     SDValue RV = performIntegerAbsCombine(N, DAG);
19327     if (RV.getNode())
19328       return RV;
19329   }
19330
19331   return SDValue();
19332 }
19333
19334 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19335 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19336                                   TargetLowering::DAGCombinerInfo &DCI,
19337                                   const X86Subtarget *Subtarget) {
19338   LoadSDNode *Ld = cast<LoadSDNode>(N);
19339   EVT RegVT = Ld->getValueType(0);
19340   EVT MemVT = Ld->getMemoryVT();
19341   SDLoc dl(Ld);
19342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19343   unsigned RegSz = RegVT.getSizeInBits();
19344
19345   // On Sandybridge unaligned 256bit loads are inefficient.
19346   ISD::LoadExtType Ext = Ld->getExtensionType();
19347   unsigned Alignment = Ld->getAlignment();
19348   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19349   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19350       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19351     unsigned NumElems = RegVT.getVectorNumElements();
19352     if (NumElems < 2)
19353       return SDValue();
19354
19355     SDValue Ptr = Ld->getBasePtr();
19356     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19357
19358     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19359                                   NumElems/2);
19360     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19361                                 Ld->getPointerInfo(), Ld->isVolatile(),
19362                                 Ld->isNonTemporal(), Ld->isInvariant(),
19363                                 Alignment);
19364     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19365     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19366                                 Ld->getPointerInfo(), Ld->isVolatile(),
19367                                 Ld->isNonTemporal(), Ld->isInvariant(),
19368                                 std::min(16U, Alignment));
19369     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19370                              Load1.getValue(1),
19371                              Load2.getValue(1));
19372
19373     SDValue NewVec = DAG.getUNDEF(RegVT);
19374     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19375     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19376     return DCI.CombineTo(N, NewVec, TF, true);
19377   }
19378
19379   // If this is a vector EXT Load then attempt to optimize it using a
19380   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19381   // expansion is still better than scalar code.
19382   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19383   // emit a shuffle and a arithmetic shift.
19384   // TODO: It is possible to support ZExt by zeroing the undef values
19385   // during the shuffle phase or after the shuffle.
19386   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19387       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19388     assert(MemVT != RegVT && "Cannot extend to the same type");
19389     assert(MemVT.isVector() && "Must load a vector from memory");
19390
19391     unsigned NumElems = RegVT.getVectorNumElements();
19392     unsigned MemSz = MemVT.getSizeInBits();
19393     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19394
19395     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19396       return SDValue();
19397
19398     // All sizes must be a power of two.
19399     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19400       return SDValue();
19401
19402     // Attempt to load the original value using scalar loads.
19403     // Find the largest scalar type that divides the total loaded size.
19404     MVT SclrLoadTy = MVT::i8;
19405     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19406          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19407       MVT Tp = (MVT::SimpleValueType)tp;
19408       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19409         SclrLoadTy = Tp;
19410       }
19411     }
19412
19413     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19414     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19415         (64 <= MemSz))
19416       SclrLoadTy = MVT::f64;
19417
19418     // Calculate the number of scalar loads that we need to perform
19419     // in order to load our vector from memory.
19420     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19421     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19422       return SDValue();
19423
19424     unsigned loadRegZize = RegSz;
19425     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19426       loadRegZize /= 2;
19427
19428     // Represent our vector as a sequence of elements which are the
19429     // largest scalar that we can load.
19430     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19431       loadRegZize/SclrLoadTy.getSizeInBits());
19432
19433     // Represent the data using the same element type that is stored in
19434     // memory. In practice, we ''widen'' MemVT.
19435     EVT WideVecVT =
19436           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19437                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19438
19439     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19440       "Invalid vector type");
19441
19442     // We can't shuffle using an illegal type.
19443     if (!TLI.isTypeLegal(WideVecVT))
19444       return SDValue();
19445
19446     SmallVector<SDValue, 8> Chains;
19447     SDValue Ptr = Ld->getBasePtr();
19448     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19449                                         TLI.getPointerTy());
19450     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19451
19452     for (unsigned i = 0; i < NumLoads; ++i) {
19453       // Perform a single load.
19454       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19455                                        Ptr, Ld->getPointerInfo(),
19456                                        Ld->isVolatile(), Ld->isNonTemporal(),
19457                                        Ld->isInvariant(), Ld->getAlignment());
19458       Chains.push_back(ScalarLoad.getValue(1));
19459       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19460       // another round of DAGCombining.
19461       if (i == 0)
19462         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19463       else
19464         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19465                           ScalarLoad, DAG.getIntPtrConstant(i));
19466
19467       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19468     }
19469
19470     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19471
19472     // Bitcast the loaded value to a vector of the original element type, in
19473     // the size of the target vector type.
19474     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19475     unsigned SizeRatio = RegSz/MemSz;
19476
19477     if (Ext == ISD::SEXTLOAD) {
19478       // If we have SSE4.1 we can directly emit a VSEXT node.
19479       if (Subtarget->hasSSE41()) {
19480         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19481         return DCI.CombineTo(N, Sext, TF, true);
19482       }
19483
19484       // Otherwise we'll shuffle the small elements in the high bits of the
19485       // larger type and perform an arithmetic shift. If the shift is not legal
19486       // it's better to scalarize.
19487       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19488         return SDValue();
19489
19490       // Redistribute the loaded elements into the different locations.
19491       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19492       for (unsigned i = 0; i != NumElems; ++i)
19493         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19494
19495       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19496                                            DAG.getUNDEF(WideVecVT),
19497                                            &ShuffleVec[0]);
19498
19499       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19500
19501       // Build the arithmetic shift.
19502       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19503                      MemVT.getVectorElementType().getSizeInBits();
19504       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19505                           DAG.getConstant(Amt, RegVT));
19506
19507       return DCI.CombineTo(N, Shuff, TF, true);
19508     }
19509
19510     // Redistribute the loaded elements into the different locations.
19511     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19512     for (unsigned i = 0; i != NumElems; ++i)
19513       ShuffleVec[i*SizeRatio] = i;
19514
19515     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19516                                          DAG.getUNDEF(WideVecVT),
19517                                          &ShuffleVec[0]);
19518
19519     // Bitcast to the requested type.
19520     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19521     // Replace the original load with the new sequence
19522     // and return the new chain.
19523     return DCI.CombineTo(N, Shuff, TF, true);
19524   }
19525
19526   return SDValue();
19527 }
19528
19529 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19530 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19531                                    const X86Subtarget *Subtarget) {
19532   StoreSDNode *St = cast<StoreSDNode>(N);
19533   EVT VT = St->getValue().getValueType();
19534   EVT StVT = St->getMemoryVT();
19535   SDLoc dl(St);
19536   SDValue StoredVal = St->getOperand(1);
19537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19538
19539   // If we are saving a concatenation of two XMM registers, perform two stores.
19540   // On Sandy Bridge, 256-bit memory operations are executed by two
19541   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19542   // memory  operation.
19543   unsigned Alignment = St->getAlignment();
19544   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19545   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19546       StVT == VT && !IsAligned) {
19547     unsigned NumElems = VT.getVectorNumElements();
19548     if (NumElems < 2)
19549       return SDValue();
19550
19551     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19552     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19553
19554     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19555     SDValue Ptr0 = St->getBasePtr();
19556     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19557
19558     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19559                                 St->getPointerInfo(), St->isVolatile(),
19560                                 St->isNonTemporal(), Alignment);
19561     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19562                                 St->getPointerInfo(), St->isVolatile(),
19563                                 St->isNonTemporal(),
19564                                 std::min(16U, Alignment));
19565     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19566   }
19567
19568   // Optimize trunc store (of multiple scalars) to shuffle and store.
19569   // First, pack all of the elements in one place. Next, store to memory
19570   // in fewer chunks.
19571   if (St->isTruncatingStore() && VT.isVector()) {
19572     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19573     unsigned NumElems = VT.getVectorNumElements();
19574     assert(StVT != VT && "Cannot truncate to the same type");
19575     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19576     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19577
19578     // From, To sizes and ElemCount must be pow of two
19579     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19580     // We are going to use the original vector elt for storing.
19581     // Accumulated smaller vector elements must be a multiple of the store size.
19582     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19583
19584     unsigned SizeRatio  = FromSz / ToSz;
19585
19586     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19587
19588     // Create a type on which we perform the shuffle
19589     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19590             StVT.getScalarType(), NumElems*SizeRatio);
19591
19592     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19593
19594     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19595     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19596     for (unsigned i = 0; i != NumElems; ++i)
19597       ShuffleVec[i] = i * SizeRatio;
19598
19599     // Can't shuffle using an illegal type.
19600     if (!TLI.isTypeLegal(WideVecVT))
19601       return SDValue();
19602
19603     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19604                                          DAG.getUNDEF(WideVecVT),
19605                                          &ShuffleVec[0]);
19606     // At this point all of the data is stored at the bottom of the
19607     // register. We now need to save it to mem.
19608
19609     // Find the largest store unit
19610     MVT StoreType = MVT::i8;
19611     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19612          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19613       MVT Tp = (MVT::SimpleValueType)tp;
19614       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19615         StoreType = Tp;
19616     }
19617
19618     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19619     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19620         (64 <= NumElems * ToSz))
19621       StoreType = MVT::f64;
19622
19623     // Bitcast the original vector into a vector of store-size units
19624     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19625             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19626     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19627     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19628     SmallVector<SDValue, 8> Chains;
19629     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19630                                         TLI.getPointerTy());
19631     SDValue Ptr = St->getBasePtr();
19632
19633     // Perform one or more big stores into memory.
19634     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19635       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19636                                    StoreType, ShuffWide,
19637                                    DAG.getIntPtrConstant(i));
19638       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19639                                 St->getPointerInfo(), St->isVolatile(),
19640                                 St->isNonTemporal(), St->getAlignment());
19641       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19642       Chains.push_back(Ch);
19643     }
19644
19645     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19646   }
19647
19648   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19649   // the FP state in cases where an emms may be missing.
19650   // A preferable solution to the general problem is to figure out the right
19651   // places to insert EMMS.  This qualifies as a quick hack.
19652
19653   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19654   if (VT.getSizeInBits() != 64)
19655     return SDValue();
19656
19657   const Function *F = DAG.getMachineFunction().getFunction();
19658   bool NoImplicitFloatOps = F->getAttributes().
19659     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19660   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19661                      && Subtarget->hasSSE2();
19662   if ((VT.isVector() ||
19663        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19664       isa<LoadSDNode>(St->getValue()) &&
19665       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19666       St->getChain().hasOneUse() && !St->isVolatile()) {
19667     SDNode* LdVal = St->getValue().getNode();
19668     LoadSDNode *Ld = nullptr;
19669     int TokenFactorIndex = -1;
19670     SmallVector<SDValue, 8> Ops;
19671     SDNode* ChainVal = St->getChain().getNode();
19672     // Must be a store of a load.  We currently handle two cases:  the load
19673     // is a direct child, and it's under an intervening TokenFactor.  It is
19674     // possible to dig deeper under nested TokenFactors.
19675     if (ChainVal == LdVal)
19676       Ld = cast<LoadSDNode>(St->getChain());
19677     else if (St->getValue().hasOneUse() &&
19678              ChainVal->getOpcode() == ISD::TokenFactor) {
19679       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19680         if (ChainVal->getOperand(i).getNode() == LdVal) {
19681           TokenFactorIndex = i;
19682           Ld = cast<LoadSDNode>(St->getValue());
19683         } else
19684           Ops.push_back(ChainVal->getOperand(i));
19685       }
19686     }
19687
19688     if (!Ld || !ISD::isNormalLoad(Ld))
19689       return SDValue();
19690
19691     // If this is not the MMX case, i.e. we are just turning i64 load/store
19692     // into f64 load/store, avoid the transformation if there are multiple
19693     // uses of the loaded value.
19694     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19695       return SDValue();
19696
19697     SDLoc LdDL(Ld);
19698     SDLoc StDL(N);
19699     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19700     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19701     // pair instead.
19702     if (Subtarget->is64Bit() || F64IsLegal) {
19703       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19704       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19705                                   Ld->getPointerInfo(), Ld->isVolatile(),
19706                                   Ld->isNonTemporal(), Ld->isInvariant(),
19707                                   Ld->getAlignment());
19708       SDValue NewChain = NewLd.getValue(1);
19709       if (TokenFactorIndex != -1) {
19710         Ops.push_back(NewChain);
19711         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19712       }
19713       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19714                           St->getPointerInfo(),
19715                           St->isVolatile(), St->isNonTemporal(),
19716                           St->getAlignment());
19717     }
19718
19719     // Otherwise, lower to two pairs of 32-bit loads / stores.
19720     SDValue LoAddr = Ld->getBasePtr();
19721     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19722                                  DAG.getConstant(4, MVT::i32));
19723
19724     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19725                                Ld->getPointerInfo(),
19726                                Ld->isVolatile(), Ld->isNonTemporal(),
19727                                Ld->isInvariant(), Ld->getAlignment());
19728     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19729                                Ld->getPointerInfo().getWithOffset(4),
19730                                Ld->isVolatile(), Ld->isNonTemporal(),
19731                                Ld->isInvariant(),
19732                                MinAlign(Ld->getAlignment(), 4));
19733
19734     SDValue NewChain = LoLd.getValue(1);
19735     if (TokenFactorIndex != -1) {
19736       Ops.push_back(LoLd);
19737       Ops.push_back(HiLd);
19738       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19739     }
19740
19741     LoAddr = St->getBasePtr();
19742     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19743                          DAG.getConstant(4, MVT::i32));
19744
19745     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19746                                 St->getPointerInfo(),
19747                                 St->isVolatile(), St->isNonTemporal(),
19748                                 St->getAlignment());
19749     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19750                                 St->getPointerInfo().getWithOffset(4),
19751                                 St->isVolatile(),
19752                                 St->isNonTemporal(),
19753                                 MinAlign(St->getAlignment(), 4));
19754     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19755   }
19756   return SDValue();
19757 }
19758
19759 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19760 /// and return the operands for the horizontal operation in LHS and RHS.  A
19761 /// horizontal operation performs the binary operation on successive elements
19762 /// of its first operand, then on successive elements of its second operand,
19763 /// returning the resulting values in a vector.  For example, if
19764 ///   A = < float a0, float a1, float a2, float a3 >
19765 /// and
19766 ///   B = < float b0, float b1, float b2, float b3 >
19767 /// then the result of doing a horizontal operation on A and B is
19768 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19769 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19770 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19771 /// set to A, RHS to B, and the routine returns 'true'.
19772 /// Note that the binary operation should have the property that if one of the
19773 /// operands is UNDEF then the result is UNDEF.
19774 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19775   // Look for the following pattern: if
19776   //   A = < float a0, float a1, float a2, float a3 >
19777   //   B = < float b0, float b1, float b2, float b3 >
19778   // and
19779   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19780   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19781   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19782   // which is A horizontal-op B.
19783
19784   // At least one of the operands should be a vector shuffle.
19785   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19786       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19787     return false;
19788
19789   MVT VT = LHS.getSimpleValueType();
19790
19791   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19792          "Unsupported vector type for horizontal add/sub");
19793
19794   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19795   // operate independently on 128-bit lanes.
19796   unsigned NumElts = VT.getVectorNumElements();
19797   unsigned NumLanes = VT.getSizeInBits()/128;
19798   unsigned NumLaneElts = NumElts / NumLanes;
19799   assert((NumLaneElts % 2 == 0) &&
19800          "Vector type should have an even number of elements in each lane");
19801   unsigned HalfLaneElts = NumLaneElts/2;
19802
19803   // View LHS in the form
19804   //   LHS = VECTOR_SHUFFLE A, B, LMask
19805   // If LHS is not a shuffle then pretend it is the shuffle
19806   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19807   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19808   // type VT.
19809   SDValue A, B;
19810   SmallVector<int, 16> LMask(NumElts);
19811   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19812     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19813       A = LHS.getOperand(0);
19814     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19815       B = LHS.getOperand(1);
19816     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19817     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19818   } else {
19819     if (LHS.getOpcode() != ISD::UNDEF)
19820       A = LHS;
19821     for (unsigned i = 0; i != NumElts; ++i)
19822       LMask[i] = i;
19823   }
19824
19825   // Likewise, view RHS in the form
19826   //   RHS = VECTOR_SHUFFLE C, D, RMask
19827   SDValue C, D;
19828   SmallVector<int, 16> RMask(NumElts);
19829   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19830     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19831       C = RHS.getOperand(0);
19832     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19833       D = RHS.getOperand(1);
19834     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19835     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19836   } else {
19837     if (RHS.getOpcode() != ISD::UNDEF)
19838       C = RHS;
19839     for (unsigned i = 0; i != NumElts; ++i)
19840       RMask[i] = i;
19841   }
19842
19843   // Check that the shuffles are both shuffling the same vectors.
19844   if (!(A == C && B == D) && !(A == D && B == C))
19845     return false;
19846
19847   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19848   if (!A.getNode() && !B.getNode())
19849     return false;
19850
19851   // If A and B occur in reverse order in RHS, then "swap" them (which means
19852   // rewriting the mask).
19853   if (A != C)
19854     CommuteVectorShuffleMask(RMask, NumElts);
19855
19856   // At this point LHS and RHS are equivalent to
19857   //   LHS = VECTOR_SHUFFLE A, B, LMask
19858   //   RHS = VECTOR_SHUFFLE A, B, RMask
19859   // Check that the masks correspond to performing a horizontal operation.
19860   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19861     for (unsigned i = 0; i != NumLaneElts; ++i) {
19862       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19863
19864       // Ignore any UNDEF components.
19865       if (LIdx < 0 || RIdx < 0 ||
19866           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19867           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19868         continue;
19869
19870       // Check that successive elements are being operated on.  If not, this is
19871       // not a horizontal operation.
19872       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19873       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19874       if (!(LIdx == Index && RIdx == Index + 1) &&
19875           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19876         return false;
19877     }
19878   }
19879
19880   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19881   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19882   return true;
19883 }
19884
19885 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19886 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19887                                   const X86Subtarget *Subtarget) {
19888   EVT VT = N->getValueType(0);
19889   SDValue LHS = N->getOperand(0);
19890   SDValue RHS = N->getOperand(1);
19891
19892   // Try to synthesize horizontal adds from adds of shuffles.
19893   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19894        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19895       isHorizontalBinOp(LHS, RHS, true))
19896     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19897   return SDValue();
19898 }
19899
19900 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19901 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19902                                   const X86Subtarget *Subtarget) {
19903   EVT VT = N->getValueType(0);
19904   SDValue LHS = N->getOperand(0);
19905   SDValue RHS = N->getOperand(1);
19906
19907   // Try to synthesize horizontal subs from subs of shuffles.
19908   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19909        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19910       isHorizontalBinOp(LHS, RHS, false))
19911     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19912   return SDValue();
19913 }
19914
19915 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19916 /// X86ISD::FXOR nodes.
19917 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19918   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19919   // F[X]OR(0.0, x) -> x
19920   // F[X]OR(x, 0.0) -> x
19921   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19922     if (C->getValueAPF().isPosZero())
19923       return N->getOperand(1);
19924   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19925     if (C->getValueAPF().isPosZero())
19926       return N->getOperand(0);
19927   return SDValue();
19928 }
19929
19930 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19931 /// X86ISD::FMAX nodes.
19932 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19933   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19934
19935   // Only perform optimizations if UnsafeMath is used.
19936   if (!DAG.getTarget().Options.UnsafeFPMath)
19937     return SDValue();
19938
19939   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19940   // into FMINC and FMAXC, which are Commutative operations.
19941   unsigned NewOp = 0;
19942   switch (N->getOpcode()) {
19943     default: llvm_unreachable("unknown opcode");
19944     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19945     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19946   }
19947
19948   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19949                      N->getOperand(0), N->getOperand(1));
19950 }
19951
19952 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19953 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19954   // FAND(0.0, x) -> 0.0
19955   // FAND(x, 0.0) -> 0.0
19956   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19957     if (C->getValueAPF().isPosZero())
19958       return N->getOperand(0);
19959   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19960     if (C->getValueAPF().isPosZero())
19961       return N->getOperand(1);
19962   return SDValue();
19963 }
19964
19965 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19966 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19967   // FANDN(x, 0.0) -> 0.0
19968   // FANDN(0.0, x) -> x
19969   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19970     if (C->getValueAPF().isPosZero())
19971       return N->getOperand(1);
19972   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19973     if (C->getValueAPF().isPosZero())
19974       return N->getOperand(1);
19975   return SDValue();
19976 }
19977
19978 static SDValue PerformBTCombine(SDNode *N,
19979                                 SelectionDAG &DAG,
19980                                 TargetLowering::DAGCombinerInfo &DCI) {
19981   // BT ignores high bits in the bit index operand.
19982   SDValue Op1 = N->getOperand(1);
19983   if (Op1.hasOneUse()) {
19984     unsigned BitWidth = Op1.getValueSizeInBits();
19985     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19986     APInt KnownZero, KnownOne;
19987     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19988                                           !DCI.isBeforeLegalizeOps());
19989     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19990     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19991         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19992       DCI.CommitTargetLoweringOpt(TLO);
19993   }
19994   return SDValue();
19995 }
19996
19997 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19998   SDValue Op = N->getOperand(0);
19999   if (Op.getOpcode() == ISD::BITCAST)
20000     Op = Op.getOperand(0);
20001   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20002   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20003       VT.getVectorElementType().getSizeInBits() ==
20004       OpVT.getVectorElementType().getSizeInBits()) {
20005     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20006   }
20007   return SDValue();
20008 }
20009
20010 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20011                                                const X86Subtarget *Subtarget) {
20012   EVT VT = N->getValueType(0);
20013   if (!VT.isVector())
20014     return SDValue();
20015
20016   SDValue N0 = N->getOperand(0);
20017   SDValue N1 = N->getOperand(1);
20018   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20019   SDLoc dl(N);
20020
20021   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20022   // both SSE and AVX2 since there is no sign-extended shift right
20023   // operation on a vector with 64-bit elements.
20024   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20025   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20026   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20027       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20028     SDValue N00 = N0.getOperand(0);
20029
20030     // EXTLOAD has a better solution on AVX2,
20031     // it may be replaced with X86ISD::VSEXT node.
20032     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20033       if (!ISD::isNormalLoad(N00.getNode()))
20034         return SDValue();
20035
20036     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20037         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20038                                   N00, N1);
20039       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20040     }
20041   }
20042   return SDValue();
20043 }
20044
20045 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20046                                   TargetLowering::DAGCombinerInfo &DCI,
20047                                   const X86Subtarget *Subtarget) {
20048   if (!DCI.isBeforeLegalizeOps())
20049     return SDValue();
20050
20051   if (!Subtarget->hasFp256())
20052     return SDValue();
20053
20054   EVT VT = N->getValueType(0);
20055   if (VT.isVector() && VT.getSizeInBits() == 256) {
20056     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20057     if (R.getNode())
20058       return R;
20059   }
20060
20061   return SDValue();
20062 }
20063
20064 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20065                                  const X86Subtarget* Subtarget) {
20066   SDLoc dl(N);
20067   EVT VT = N->getValueType(0);
20068
20069   // Let legalize expand this if it isn't a legal type yet.
20070   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20071     return SDValue();
20072
20073   EVT ScalarVT = VT.getScalarType();
20074   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20075       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20076     return SDValue();
20077
20078   SDValue A = N->getOperand(0);
20079   SDValue B = N->getOperand(1);
20080   SDValue C = N->getOperand(2);
20081
20082   bool NegA = (A.getOpcode() == ISD::FNEG);
20083   bool NegB = (B.getOpcode() == ISD::FNEG);
20084   bool NegC = (C.getOpcode() == ISD::FNEG);
20085
20086   // Negative multiplication when NegA xor NegB
20087   bool NegMul = (NegA != NegB);
20088   if (NegA)
20089     A = A.getOperand(0);
20090   if (NegB)
20091     B = B.getOperand(0);
20092   if (NegC)
20093     C = C.getOperand(0);
20094
20095   unsigned Opcode;
20096   if (!NegMul)
20097     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20098   else
20099     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20100
20101   return DAG.getNode(Opcode, dl, VT, A, B, C);
20102 }
20103
20104 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20105                                   TargetLowering::DAGCombinerInfo &DCI,
20106                                   const X86Subtarget *Subtarget) {
20107   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20108   //           (and (i32 x86isd::setcc_carry), 1)
20109   // This eliminates the zext. This transformation is necessary because
20110   // ISD::SETCC is always legalized to i8.
20111   SDLoc dl(N);
20112   SDValue N0 = N->getOperand(0);
20113   EVT VT = N->getValueType(0);
20114
20115   if (N0.getOpcode() == ISD::AND &&
20116       N0.hasOneUse() &&
20117       N0.getOperand(0).hasOneUse()) {
20118     SDValue N00 = N0.getOperand(0);
20119     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20120       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20121       if (!C || C->getZExtValue() != 1)
20122         return SDValue();
20123       return DAG.getNode(ISD::AND, dl, VT,
20124                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20125                                      N00.getOperand(0), N00.getOperand(1)),
20126                          DAG.getConstant(1, VT));
20127     }
20128   }
20129
20130   if (N0.getOpcode() == ISD::TRUNCATE &&
20131       N0.hasOneUse() &&
20132       N0.getOperand(0).hasOneUse()) {
20133     SDValue N00 = N0.getOperand(0);
20134     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20135       return DAG.getNode(ISD::AND, dl, VT,
20136                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20137                                      N00.getOperand(0), N00.getOperand(1)),
20138                          DAG.getConstant(1, VT));
20139     }
20140   }
20141   if (VT.is256BitVector()) {
20142     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20143     if (R.getNode())
20144       return R;
20145   }
20146
20147   return SDValue();
20148 }
20149
20150 // Optimize x == -y --> x+y == 0
20151 //          x != -y --> x+y != 0
20152 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20153                                       const X86Subtarget* Subtarget) {
20154   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20155   SDValue LHS = N->getOperand(0);
20156   SDValue RHS = N->getOperand(1);
20157   EVT VT = N->getValueType(0);
20158   SDLoc DL(N);
20159
20160   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20161     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20162       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20163         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20164                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20165         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20166                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20167       }
20168   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20169     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20170       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20171         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20172                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20173         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20174                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20175       }
20176
20177   if (VT.getScalarType() == MVT::i1) {
20178     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20179       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20180     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20181     if (!IsSEXT0 && !IsVZero0)
20182       return SDValue();
20183     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20184       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20185     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20186
20187     if (!IsSEXT1 && !IsVZero1)
20188       return SDValue();
20189
20190     if (IsSEXT0 && IsVZero1) {
20191       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20192       if (CC == ISD::SETEQ)
20193         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20194       return LHS.getOperand(0);
20195     }
20196     if (IsSEXT1 && IsVZero0) {
20197       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20198       if (CC == ISD::SETEQ)
20199         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20200       return RHS.getOperand(0);
20201     }
20202   }
20203
20204   return SDValue();
20205 }
20206
20207 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20208 // as "sbb reg,reg", since it can be extended without zext and produces
20209 // an all-ones bit which is more useful than 0/1 in some cases.
20210 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20211                                MVT VT) {
20212   if (VT == MVT::i8)
20213     return DAG.getNode(ISD::AND, DL, VT,
20214                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20215                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20216                        DAG.getConstant(1, VT));
20217   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20218   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20219                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20220                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20221 }
20222
20223 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20224 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20225                                    TargetLowering::DAGCombinerInfo &DCI,
20226                                    const X86Subtarget *Subtarget) {
20227   SDLoc DL(N);
20228   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20229   SDValue EFLAGS = N->getOperand(1);
20230
20231   if (CC == X86::COND_A) {
20232     // Try to convert COND_A into COND_B in an attempt to facilitate
20233     // materializing "setb reg".
20234     //
20235     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20236     // cannot take an immediate as its first operand.
20237     //
20238     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20239         EFLAGS.getValueType().isInteger() &&
20240         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20241       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20242                                    EFLAGS.getNode()->getVTList(),
20243                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20244       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20245       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20246     }
20247   }
20248
20249   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20250   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20251   // cases.
20252   if (CC == X86::COND_B)
20253     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20254
20255   SDValue Flags;
20256
20257   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20258   if (Flags.getNode()) {
20259     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20260     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20261   }
20262
20263   return SDValue();
20264 }
20265
20266 // Optimize branch condition evaluation.
20267 //
20268 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20269                                     TargetLowering::DAGCombinerInfo &DCI,
20270                                     const X86Subtarget *Subtarget) {
20271   SDLoc DL(N);
20272   SDValue Chain = N->getOperand(0);
20273   SDValue Dest = N->getOperand(1);
20274   SDValue EFLAGS = N->getOperand(3);
20275   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20276
20277   SDValue Flags;
20278
20279   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20280   if (Flags.getNode()) {
20281     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20282     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20283                        Flags);
20284   }
20285
20286   return SDValue();
20287 }
20288
20289 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20290                                         const X86TargetLowering *XTLI) {
20291   SDValue Op0 = N->getOperand(0);
20292   EVT InVT = Op0->getValueType(0);
20293
20294   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20295   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20296     SDLoc dl(N);
20297     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20298     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20299     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20300   }
20301
20302   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20303   // a 32-bit target where SSE doesn't support i64->FP operations.
20304   if (Op0.getOpcode() == ISD::LOAD) {
20305     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20306     EVT VT = Ld->getValueType(0);
20307     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20308         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20309         !XTLI->getSubtarget()->is64Bit() &&
20310         VT == MVT::i64) {
20311       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20312                                           Ld->getChain(), Op0, DAG);
20313       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20314       return FILDChain;
20315     }
20316   }
20317   return SDValue();
20318 }
20319
20320 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20321 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20322                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20323   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20324   // the result is either zero or one (depending on the input carry bit).
20325   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20326   if (X86::isZeroNode(N->getOperand(0)) &&
20327       X86::isZeroNode(N->getOperand(1)) &&
20328       // We don't have a good way to replace an EFLAGS use, so only do this when
20329       // dead right now.
20330       SDValue(N, 1).use_empty()) {
20331     SDLoc DL(N);
20332     EVT VT = N->getValueType(0);
20333     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20334     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20335                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20336                                            DAG.getConstant(X86::COND_B,MVT::i8),
20337                                            N->getOperand(2)),
20338                                DAG.getConstant(1, VT));
20339     return DCI.CombineTo(N, Res1, CarryOut);
20340   }
20341
20342   return SDValue();
20343 }
20344
20345 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20346 //      (add Y, (setne X, 0)) -> sbb -1, Y
20347 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20348 //      (sub (setne X, 0), Y) -> adc -1, Y
20349 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20350   SDLoc DL(N);
20351
20352   // Look through ZExts.
20353   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20354   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20355     return SDValue();
20356
20357   SDValue SetCC = Ext.getOperand(0);
20358   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20359     return SDValue();
20360
20361   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20362   if (CC != X86::COND_E && CC != X86::COND_NE)
20363     return SDValue();
20364
20365   SDValue Cmp = SetCC.getOperand(1);
20366   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20367       !X86::isZeroNode(Cmp.getOperand(1)) ||
20368       !Cmp.getOperand(0).getValueType().isInteger())
20369     return SDValue();
20370
20371   SDValue CmpOp0 = Cmp.getOperand(0);
20372   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20373                                DAG.getConstant(1, CmpOp0.getValueType()));
20374
20375   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20376   if (CC == X86::COND_NE)
20377     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20378                        DL, OtherVal.getValueType(), OtherVal,
20379                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20380   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20381                      DL, OtherVal.getValueType(), OtherVal,
20382                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20383 }
20384
20385 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20386 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20387                                  const X86Subtarget *Subtarget) {
20388   EVT VT = N->getValueType(0);
20389   SDValue Op0 = N->getOperand(0);
20390   SDValue Op1 = N->getOperand(1);
20391
20392   // Try to synthesize horizontal adds from adds of shuffles.
20393   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20394        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20395       isHorizontalBinOp(Op0, Op1, true))
20396     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20397
20398   return OptimizeConditionalInDecrement(N, DAG);
20399 }
20400
20401 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20402                                  const X86Subtarget *Subtarget) {
20403   SDValue Op0 = N->getOperand(0);
20404   SDValue Op1 = N->getOperand(1);
20405
20406   // X86 can't encode an immediate LHS of a sub. See if we can push the
20407   // negation into a preceding instruction.
20408   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20409     // If the RHS of the sub is a XOR with one use and a constant, invert the
20410     // immediate. Then add one to the LHS of the sub so we can turn
20411     // X-Y -> X+~Y+1, saving one register.
20412     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20413         isa<ConstantSDNode>(Op1.getOperand(1))) {
20414       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20415       EVT VT = Op0.getValueType();
20416       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20417                                    Op1.getOperand(0),
20418                                    DAG.getConstant(~XorC, VT));
20419       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20420                          DAG.getConstant(C->getAPIntValue()+1, VT));
20421     }
20422   }
20423
20424   // Try to synthesize horizontal adds from adds of shuffles.
20425   EVT VT = N->getValueType(0);
20426   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20427        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20428       isHorizontalBinOp(Op0, Op1, true))
20429     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20430
20431   return OptimizeConditionalInDecrement(N, DAG);
20432 }
20433
20434 /// performVZEXTCombine - Performs build vector combines
20435 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20436                                         TargetLowering::DAGCombinerInfo &DCI,
20437                                         const X86Subtarget *Subtarget) {
20438   // (vzext (bitcast (vzext (x)) -> (vzext x)
20439   SDValue In = N->getOperand(0);
20440   while (In.getOpcode() == ISD::BITCAST)
20441     In = In.getOperand(0);
20442
20443   if (In.getOpcode() != X86ISD::VZEXT)
20444     return SDValue();
20445
20446   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20447                      In.getOperand(0));
20448 }
20449
20450 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20451                                              DAGCombinerInfo &DCI) const {
20452   SelectionDAG &DAG = DCI.DAG;
20453   switch (N->getOpcode()) {
20454   default: break;
20455   case ISD::EXTRACT_VECTOR_ELT:
20456     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20457   case ISD::VSELECT:
20458   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20459   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20460   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20461   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20462   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20463   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20464   case ISD::SHL:
20465   case ISD::SRA:
20466   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20467   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20468   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20469   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20470   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20471   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20472   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20473   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20474   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20475   case X86ISD::FXOR:
20476   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20477   case X86ISD::FMIN:
20478   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20479   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20480   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20481   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20482   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20483   case ISD::ANY_EXTEND:
20484   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20485   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20486   case ISD::SIGN_EXTEND_INREG:
20487     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20488   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20489   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20490   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20491   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20492   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20493   case X86ISD::SHUFP:       // Handle all target specific shuffles
20494   case X86ISD::PALIGNR:
20495   case X86ISD::UNPCKH:
20496   case X86ISD::UNPCKL:
20497   case X86ISD::MOVHLPS:
20498   case X86ISD::MOVLHPS:
20499   case X86ISD::PSHUFD:
20500   case X86ISD::PSHUFHW:
20501   case X86ISD::PSHUFLW:
20502   case X86ISD::MOVSS:
20503   case X86ISD::MOVSD:
20504   case X86ISD::VPERMILP:
20505   case X86ISD::VPERM2X128:
20506   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20507   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20508   case ISD::INTRINSIC_WO_CHAIN:
20509     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20510   }
20511
20512   return SDValue();
20513 }
20514
20515 /// isTypeDesirableForOp - Return true if the target has native support for
20516 /// the specified value type and it is 'desirable' to use the type for the
20517 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20518 /// instruction encodings are longer and some i16 instructions are slow.
20519 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20520   if (!isTypeLegal(VT))
20521     return false;
20522   if (VT != MVT::i16)
20523     return true;
20524
20525   switch (Opc) {
20526   default:
20527     return true;
20528   case ISD::LOAD:
20529   case ISD::SIGN_EXTEND:
20530   case ISD::ZERO_EXTEND:
20531   case ISD::ANY_EXTEND:
20532   case ISD::SHL:
20533   case ISD::SRL:
20534   case ISD::SUB:
20535   case ISD::ADD:
20536   case ISD::MUL:
20537   case ISD::AND:
20538   case ISD::OR:
20539   case ISD::XOR:
20540     return false;
20541   }
20542 }
20543
20544 /// IsDesirableToPromoteOp - This method query the target whether it is
20545 /// beneficial for dag combiner to promote the specified node. If true, it
20546 /// should return the desired promotion type by reference.
20547 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20548   EVT VT = Op.getValueType();
20549   if (VT != MVT::i16)
20550     return false;
20551
20552   bool Promote = false;
20553   bool Commute = false;
20554   switch (Op.getOpcode()) {
20555   default: break;
20556   case ISD::LOAD: {
20557     LoadSDNode *LD = cast<LoadSDNode>(Op);
20558     // If the non-extending load has a single use and it's not live out, then it
20559     // might be folded.
20560     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20561                                                      Op.hasOneUse()*/) {
20562       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20563              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20564         // The only case where we'd want to promote LOAD (rather then it being
20565         // promoted as an operand is when it's only use is liveout.
20566         if (UI->getOpcode() != ISD::CopyToReg)
20567           return false;
20568       }
20569     }
20570     Promote = true;
20571     break;
20572   }
20573   case ISD::SIGN_EXTEND:
20574   case ISD::ZERO_EXTEND:
20575   case ISD::ANY_EXTEND:
20576     Promote = true;
20577     break;
20578   case ISD::SHL:
20579   case ISD::SRL: {
20580     SDValue N0 = Op.getOperand(0);
20581     // Look out for (store (shl (load), x)).
20582     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20583       return false;
20584     Promote = true;
20585     break;
20586   }
20587   case ISD::ADD:
20588   case ISD::MUL:
20589   case ISD::AND:
20590   case ISD::OR:
20591   case ISD::XOR:
20592     Commute = true;
20593     // fallthrough
20594   case ISD::SUB: {
20595     SDValue N0 = Op.getOperand(0);
20596     SDValue N1 = Op.getOperand(1);
20597     if (!Commute && MayFoldLoad(N1))
20598       return false;
20599     // Avoid disabling potential load folding opportunities.
20600     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20601       return false;
20602     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20603       return false;
20604     Promote = true;
20605   }
20606   }
20607
20608   PVT = MVT::i32;
20609   return Promote;
20610 }
20611
20612 //===----------------------------------------------------------------------===//
20613 //                           X86 Inline Assembly Support
20614 //===----------------------------------------------------------------------===//
20615
20616 namespace {
20617   // Helper to match a string separated by whitespace.
20618   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20619     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20620
20621     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20622       StringRef piece(*args[i]);
20623       if (!s.startswith(piece)) // Check if the piece matches.
20624         return false;
20625
20626       s = s.substr(piece.size());
20627       StringRef::size_type pos = s.find_first_not_of(" \t");
20628       if (pos == 0) // We matched a prefix.
20629         return false;
20630
20631       s = s.substr(pos);
20632     }
20633
20634     return s.empty();
20635   }
20636   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20637 }
20638
20639 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20640
20641   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20642     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20643         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20644         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20645
20646       if (AsmPieces.size() == 3)
20647         return true;
20648       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20649         return true;
20650     }
20651   }
20652   return false;
20653 }
20654
20655 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20656   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20657
20658   std::string AsmStr = IA->getAsmString();
20659
20660   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20661   if (!Ty || Ty->getBitWidth() % 16 != 0)
20662     return false;
20663
20664   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20665   SmallVector<StringRef, 4> AsmPieces;
20666   SplitString(AsmStr, AsmPieces, ";\n");
20667
20668   switch (AsmPieces.size()) {
20669   default: return false;
20670   case 1:
20671     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20672     // we will turn this bswap into something that will be lowered to logical
20673     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20674     // lower so don't worry about this.
20675     // bswap $0
20676     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20677         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20678         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20679         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20680         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20681         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20682       // No need to check constraints, nothing other than the equivalent of
20683       // "=r,0" would be valid here.
20684       return IntrinsicLowering::LowerToByteSwap(CI);
20685     }
20686
20687     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20688     if (CI->getType()->isIntegerTy(16) &&
20689         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20690         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20691          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20692       AsmPieces.clear();
20693       const std::string &ConstraintsStr = IA->getConstraintString();
20694       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20695       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20696       if (clobbersFlagRegisters(AsmPieces))
20697         return IntrinsicLowering::LowerToByteSwap(CI);
20698     }
20699     break;
20700   case 3:
20701     if (CI->getType()->isIntegerTy(32) &&
20702         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20703         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20704         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20705         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20706       AsmPieces.clear();
20707       const std::string &ConstraintsStr = IA->getConstraintString();
20708       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20709       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20710       if (clobbersFlagRegisters(AsmPieces))
20711         return IntrinsicLowering::LowerToByteSwap(CI);
20712     }
20713
20714     if (CI->getType()->isIntegerTy(64)) {
20715       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20716       if (Constraints.size() >= 2 &&
20717           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20718           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20719         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20720         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20721             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20722             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20723           return IntrinsicLowering::LowerToByteSwap(CI);
20724       }
20725     }
20726     break;
20727   }
20728   return false;
20729 }
20730
20731 /// getConstraintType - Given a constraint letter, return the type of
20732 /// constraint it is for this target.
20733 X86TargetLowering::ConstraintType
20734 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20735   if (Constraint.size() == 1) {
20736     switch (Constraint[0]) {
20737     case 'R':
20738     case 'q':
20739     case 'Q':
20740     case 'f':
20741     case 't':
20742     case 'u':
20743     case 'y':
20744     case 'x':
20745     case 'Y':
20746     case 'l':
20747       return C_RegisterClass;
20748     case 'a':
20749     case 'b':
20750     case 'c':
20751     case 'd':
20752     case 'S':
20753     case 'D':
20754     case 'A':
20755       return C_Register;
20756     case 'I':
20757     case 'J':
20758     case 'K':
20759     case 'L':
20760     case 'M':
20761     case 'N':
20762     case 'G':
20763     case 'C':
20764     case 'e':
20765     case 'Z':
20766       return C_Other;
20767     default:
20768       break;
20769     }
20770   }
20771   return TargetLowering::getConstraintType(Constraint);
20772 }
20773
20774 /// Examine constraint type and operand type and determine a weight value.
20775 /// This object must already have been set up with the operand type
20776 /// and the current alternative constraint selected.
20777 TargetLowering::ConstraintWeight
20778   X86TargetLowering::getSingleConstraintMatchWeight(
20779     AsmOperandInfo &info, const char *constraint) const {
20780   ConstraintWeight weight = CW_Invalid;
20781   Value *CallOperandVal = info.CallOperandVal;
20782     // If we don't have a value, we can't do a match,
20783     // but allow it at the lowest weight.
20784   if (!CallOperandVal)
20785     return CW_Default;
20786   Type *type = CallOperandVal->getType();
20787   // Look at the constraint type.
20788   switch (*constraint) {
20789   default:
20790     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20791   case 'R':
20792   case 'q':
20793   case 'Q':
20794   case 'a':
20795   case 'b':
20796   case 'c':
20797   case 'd':
20798   case 'S':
20799   case 'D':
20800   case 'A':
20801     if (CallOperandVal->getType()->isIntegerTy())
20802       weight = CW_SpecificReg;
20803     break;
20804   case 'f':
20805   case 't':
20806   case 'u':
20807     if (type->isFloatingPointTy())
20808       weight = CW_SpecificReg;
20809     break;
20810   case 'y':
20811     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20812       weight = CW_SpecificReg;
20813     break;
20814   case 'x':
20815   case 'Y':
20816     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20817         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20818       weight = CW_Register;
20819     break;
20820   case 'I':
20821     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20822       if (C->getZExtValue() <= 31)
20823         weight = CW_Constant;
20824     }
20825     break;
20826   case 'J':
20827     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20828       if (C->getZExtValue() <= 63)
20829         weight = CW_Constant;
20830     }
20831     break;
20832   case 'K':
20833     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20834       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20835         weight = CW_Constant;
20836     }
20837     break;
20838   case 'L':
20839     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20840       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20841         weight = CW_Constant;
20842     }
20843     break;
20844   case 'M':
20845     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20846       if (C->getZExtValue() <= 3)
20847         weight = CW_Constant;
20848     }
20849     break;
20850   case 'N':
20851     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20852       if (C->getZExtValue() <= 0xff)
20853         weight = CW_Constant;
20854     }
20855     break;
20856   case 'G':
20857   case 'C':
20858     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20859       weight = CW_Constant;
20860     }
20861     break;
20862   case 'e':
20863     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20864       if ((C->getSExtValue() >= -0x80000000LL) &&
20865           (C->getSExtValue() <= 0x7fffffffLL))
20866         weight = CW_Constant;
20867     }
20868     break;
20869   case 'Z':
20870     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20871       if (C->getZExtValue() <= 0xffffffff)
20872         weight = CW_Constant;
20873     }
20874     break;
20875   }
20876   return weight;
20877 }
20878
20879 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20880 /// with another that has more specific requirements based on the type of the
20881 /// corresponding operand.
20882 const char *X86TargetLowering::
20883 LowerXConstraint(EVT ConstraintVT) const {
20884   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20885   // 'f' like normal targets.
20886   if (ConstraintVT.isFloatingPoint()) {
20887     if (Subtarget->hasSSE2())
20888       return "Y";
20889     if (Subtarget->hasSSE1())
20890       return "x";
20891   }
20892
20893   return TargetLowering::LowerXConstraint(ConstraintVT);
20894 }
20895
20896 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20897 /// vector.  If it is invalid, don't add anything to Ops.
20898 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20899                                                      std::string &Constraint,
20900                                                      std::vector<SDValue>&Ops,
20901                                                      SelectionDAG &DAG) const {
20902   SDValue Result;
20903
20904   // Only support length 1 constraints for now.
20905   if (Constraint.length() > 1) return;
20906
20907   char ConstraintLetter = Constraint[0];
20908   switch (ConstraintLetter) {
20909   default: break;
20910   case 'I':
20911     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20912       if (C->getZExtValue() <= 31) {
20913         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20914         break;
20915       }
20916     }
20917     return;
20918   case 'J':
20919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20920       if (C->getZExtValue() <= 63) {
20921         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20922         break;
20923       }
20924     }
20925     return;
20926   case 'K':
20927     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20928       if (isInt<8>(C->getSExtValue())) {
20929         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20930         break;
20931       }
20932     }
20933     return;
20934   case 'N':
20935     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20936       if (C->getZExtValue() <= 255) {
20937         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20938         break;
20939       }
20940     }
20941     return;
20942   case 'e': {
20943     // 32-bit signed value
20944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20945       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20946                                            C->getSExtValue())) {
20947         // Widen to 64 bits here to get it sign extended.
20948         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20949         break;
20950       }
20951     // FIXME gcc accepts some relocatable values here too, but only in certain
20952     // memory models; it's complicated.
20953     }
20954     return;
20955   }
20956   case 'Z': {
20957     // 32-bit unsigned value
20958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20959       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20960                                            C->getZExtValue())) {
20961         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20962         break;
20963       }
20964     }
20965     // FIXME gcc accepts some relocatable values here too, but only in certain
20966     // memory models; it's complicated.
20967     return;
20968   }
20969   case 'i': {
20970     // Literal immediates are always ok.
20971     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20972       // Widen to 64 bits here to get it sign extended.
20973       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20974       break;
20975     }
20976
20977     // In any sort of PIC mode addresses need to be computed at runtime by
20978     // adding in a register or some sort of table lookup.  These can't
20979     // be used as immediates.
20980     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20981       return;
20982
20983     // If we are in non-pic codegen mode, we allow the address of a global (with
20984     // an optional displacement) to be used with 'i'.
20985     GlobalAddressSDNode *GA = nullptr;
20986     int64_t Offset = 0;
20987
20988     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20989     while (1) {
20990       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20991         Offset += GA->getOffset();
20992         break;
20993       } else if (Op.getOpcode() == ISD::ADD) {
20994         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20995           Offset += C->getZExtValue();
20996           Op = Op.getOperand(0);
20997           continue;
20998         }
20999       } else if (Op.getOpcode() == ISD::SUB) {
21000         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21001           Offset += -C->getZExtValue();
21002           Op = Op.getOperand(0);
21003           continue;
21004         }
21005       }
21006
21007       // Otherwise, this isn't something we can handle, reject it.
21008       return;
21009     }
21010
21011     const GlobalValue *GV = GA->getGlobal();
21012     // If we require an extra load to get this address, as in PIC mode, we
21013     // can't accept it.
21014     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21015                                                         getTargetMachine())))
21016       return;
21017
21018     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21019                                         GA->getValueType(0), Offset);
21020     break;
21021   }
21022   }
21023
21024   if (Result.getNode()) {
21025     Ops.push_back(Result);
21026     return;
21027   }
21028   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21029 }
21030
21031 std::pair<unsigned, const TargetRegisterClass*>
21032 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21033                                                 MVT VT) const {
21034   // First, see if this is a constraint that directly corresponds to an LLVM
21035   // register class.
21036   if (Constraint.size() == 1) {
21037     // GCC Constraint Letters
21038     switch (Constraint[0]) {
21039     default: break;
21040       // TODO: Slight differences here in allocation order and leaving
21041       // RIP in the class. Do they matter any more here than they do
21042       // in the normal allocation?
21043     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21044       if (Subtarget->is64Bit()) {
21045         if (VT == MVT::i32 || VT == MVT::f32)
21046           return std::make_pair(0U, &X86::GR32RegClass);
21047         if (VT == MVT::i16)
21048           return std::make_pair(0U, &X86::GR16RegClass);
21049         if (VT == MVT::i8 || VT == MVT::i1)
21050           return std::make_pair(0U, &X86::GR8RegClass);
21051         if (VT == MVT::i64 || VT == MVT::f64)
21052           return std::make_pair(0U, &X86::GR64RegClass);
21053         break;
21054       }
21055       // 32-bit fallthrough
21056     case 'Q':   // Q_REGS
21057       if (VT == MVT::i32 || VT == MVT::f32)
21058         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21059       if (VT == MVT::i16)
21060         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21061       if (VT == MVT::i8 || VT == MVT::i1)
21062         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21063       if (VT == MVT::i64)
21064         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21065       break;
21066     case 'r':   // GENERAL_REGS
21067     case 'l':   // INDEX_REGS
21068       if (VT == MVT::i8 || VT == MVT::i1)
21069         return std::make_pair(0U, &X86::GR8RegClass);
21070       if (VT == MVT::i16)
21071         return std::make_pair(0U, &X86::GR16RegClass);
21072       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21073         return std::make_pair(0U, &X86::GR32RegClass);
21074       return std::make_pair(0U, &X86::GR64RegClass);
21075     case 'R':   // LEGACY_REGS
21076       if (VT == MVT::i8 || VT == MVT::i1)
21077         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21078       if (VT == MVT::i16)
21079         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21080       if (VT == MVT::i32 || !Subtarget->is64Bit())
21081         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21082       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21083     case 'f':  // FP Stack registers.
21084       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21085       // value to the correct fpstack register class.
21086       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21087         return std::make_pair(0U, &X86::RFP32RegClass);
21088       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21089         return std::make_pair(0U, &X86::RFP64RegClass);
21090       return std::make_pair(0U, &X86::RFP80RegClass);
21091     case 'y':   // MMX_REGS if MMX allowed.
21092       if (!Subtarget->hasMMX()) break;
21093       return std::make_pair(0U, &X86::VR64RegClass);
21094     case 'Y':   // SSE_REGS if SSE2 allowed
21095       if (!Subtarget->hasSSE2()) break;
21096       // FALL THROUGH.
21097     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21098       if (!Subtarget->hasSSE1()) break;
21099
21100       switch (VT.SimpleTy) {
21101       default: break;
21102       // Scalar SSE types.
21103       case MVT::f32:
21104       case MVT::i32:
21105         return std::make_pair(0U, &X86::FR32RegClass);
21106       case MVT::f64:
21107       case MVT::i64:
21108         return std::make_pair(0U, &X86::FR64RegClass);
21109       // Vector types.
21110       case MVT::v16i8:
21111       case MVT::v8i16:
21112       case MVT::v4i32:
21113       case MVT::v2i64:
21114       case MVT::v4f32:
21115       case MVT::v2f64:
21116         return std::make_pair(0U, &X86::VR128RegClass);
21117       // AVX types.
21118       case MVT::v32i8:
21119       case MVT::v16i16:
21120       case MVT::v8i32:
21121       case MVT::v4i64:
21122       case MVT::v8f32:
21123       case MVT::v4f64:
21124         return std::make_pair(0U, &X86::VR256RegClass);
21125       case MVT::v8f64:
21126       case MVT::v16f32:
21127       case MVT::v16i32:
21128       case MVT::v8i64:
21129         return std::make_pair(0U, &X86::VR512RegClass);
21130       }
21131       break;
21132     }
21133   }
21134
21135   // Use the default implementation in TargetLowering to convert the register
21136   // constraint into a member of a register class.
21137   std::pair<unsigned, const TargetRegisterClass*> Res;
21138   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21139
21140   // Not found as a standard register?
21141   if (!Res.second) {
21142     // Map st(0) -> st(7) -> ST0
21143     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21144         tolower(Constraint[1]) == 's' &&
21145         tolower(Constraint[2]) == 't' &&
21146         Constraint[3] == '(' &&
21147         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21148         Constraint[5] == ')' &&
21149         Constraint[6] == '}') {
21150
21151       Res.first = X86::ST0+Constraint[4]-'0';
21152       Res.second = &X86::RFP80RegClass;
21153       return Res;
21154     }
21155
21156     // GCC allows "st(0)" to be called just plain "st".
21157     if (StringRef("{st}").equals_lower(Constraint)) {
21158       Res.first = X86::ST0;
21159       Res.second = &X86::RFP80RegClass;
21160       return Res;
21161     }
21162
21163     // flags -> EFLAGS
21164     if (StringRef("{flags}").equals_lower(Constraint)) {
21165       Res.first = X86::EFLAGS;
21166       Res.second = &X86::CCRRegClass;
21167       return Res;
21168     }
21169
21170     // 'A' means EAX + EDX.
21171     if (Constraint == "A") {
21172       Res.first = X86::EAX;
21173       Res.second = &X86::GR32_ADRegClass;
21174       return Res;
21175     }
21176     return Res;
21177   }
21178
21179   // Otherwise, check to see if this is a register class of the wrong value
21180   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21181   // turn into {ax},{dx}.
21182   if (Res.second->hasType(VT))
21183     return Res;   // Correct type already, nothing to do.
21184
21185   // All of the single-register GCC register classes map their values onto
21186   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21187   // really want an 8-bit or 32-bit register, map to the appropriate register
21188   // class and return the appropriate register.
21189   if (Res.second == &X86::GR16RegClass) {
21190     if (VT == MVT::i8 || VT == MVT::i1) {
21191       unsigned DestReg = 0;
21192       switch (Res.first) {
21193       default: break;
21194       case X86::AX: DestReg = X86::AL; break;
21195       case X86::DX: DestReg = X86::DL; break;
21196       case X86::CX: DestReg = X86::CL; break;
21197       case X86::BX: DestReg = X86::BL; break;
21198       }
21199       if (DestReg) {
21200         Res.first = DestReg;
21201         Res.second = &X86::GR8RegClass;
21202       }
21203     } else if (VT == MVT::i32 || VT == MVT::f32) {
21204       unsigned DestReg = 0;
21205       switch (Res.first) {
21206       default: break;
21207       case X86::AX: DestReg = X86::EAX; break;
21208       case X86::DX: DestReg = X86::EDX; break;
21209       case X86::CX: DestReg = X86::ECX; break;
21210       case X86::BX: DestReg = X86::EBX; break;
21211       case X86::SI: DestReg = X86::ESI; break;
21212       case X86::DI: DestReg = X86::EDI; break;
21213       case X86::BP: DestReg = X86::EBP; break;
21214       case X86::SP: DestReg = X86::ESP; break;
21215       }
21216       if (DestReg) {
21217         Res.first = DestReg;
21218         Res.second = &X86::GR32RegClass;
21219       }
21220     } else if (VT == MVT::i64 || VT == MVT::f64) {
21221       unsigned DestReg = 0;
21222       switch (Res.first) {
21223       default: break;
21224       case X86::AX: DestReg = X86::RAX; break;
21225       case X86::DX: DestReg = X86::RDX; break;
21226       case X86::CX: DestReg = X86::RCX; break;
21227       case X86::BX: DestReg = X86::RBX; break;
21228       case X86::SI: DestReg = X86::RSI; break;
21229       case X86::DI: DestReg = X86::RDI; break;
21230       case X86::BP: DestReg = X86::RBP; break;
21231       case X86::SP: DestReg = X86::RSP; break;
21232       }
21233       if (DestReg) {
21234         Res.first = DestReg;
21235         Res.second = &X86::GR64RegClass;
21236       }
21237     }
21238   } else if (Res.second == &X86::FR32RegClass ||
21239              Res.second == &X86::FR64RegClass ||
21240              Res.second == &X86::VR128RegClass ||
21241              Res.second == &X86::VR256RegClass ||
21242              Res.second == &X86::FR32XRegClass ||
21243              Res.second == &X86::FR64XRegClass ||
21244              Res.second == &X86::VR128XRegClass ||
21245              Res.second == &X86::VR256XRegClass ||
21246              Res.second == &X86::VR512RegClass) {
21247     // Handle references to XMM physical registers that got mapped into the
21248     // wrong class.  This can happen with constraints like {xmm0} where the
21249     // target independent register mapper will just pick the first match it can
21250     // find, ignoring the required type.
21251
21252     if (VT == MVT::f32 || VT == MVT::i32)
21253       Res.second = &X86::FR32RegClass;
21254     else if (VT == MVT::f64 || VT == MVT::i64)
21255       Res.second = &X86::FR64RegClass;
21256     else if (X86::VR128RegClass.hasType(VT))
21257       Res.second = &X86::VR128RegClass;
21258     else if (X86::VR256RegClass.hasType(VT))
21259       Res.second = &X86::VR256RegClass;
21260     else if (X86::VR512RegClass.hasType(VT))
21261       Res.second = &X86::VR512RegClass;
21262   }
21263
21264   return Res;
21265 }
21266
21267 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21268                                             Type *Ty) const {
21269   // Scaling factors are not free at all.
21270   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21271   // will take 2 allocations in the out of order engine instead of 1
21272   // for plain addressing mode, i.e. inst (reg1).
21273   // E.g.,
21274   // vaddps (%rsi,%drx), %ymm0, %ymm1
21275   // Requires two allocations (one for the load, one for the computation)
21276   // whereas:
21277   // vaddps (%rsi), %ymm0, %ymm1
21278   // Requires just 1 allocation, i.e., freeing allocations for other operations
21279   // and having less micro operations to execute.
21280   //
21281   // For some X86 architectures, this is even worse because for instance for
21282   // stores, the complex addressing mode forces the instruction to use the
21283   // "load" ports instead of the dedicated "store" port.
21284   // E.g., on Haswell:
21285   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21286   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21287   if (isLegalAddressingMode(AM, Ty))
21288     // Scale represents reg2 * scale, thus account for 1
21289     // as soon as we use a second register.
21290     return AM.Scale != 0;
21291   return -1;
21292 }