[X86] Fix a bug in the lowering of BLENDI introduced in r209043.
[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->hasSSE2()) {
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->hasSSE2()) {
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 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7416                                          SelectionDAG &DAG) {
7417   SDLoc dl(Load);
7418   MVT VT = Load->getSimpleValueType(0);
7419   MVT EVT = VT.getVectorElementType();
7420   SDValue Addr = Load->getOperand(1);
7421   SDValue NewAddr = DAG.getNode(
7422       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7423       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7424
7425   SDValue NewLoad =
7426       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7427                   DAG.getMachineFunction().getMachineMemOperand(
7428                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7429   return NewLoad;
7430 }
7431
7432 // It is only safe to call this function if isINSERTPSMask is true for
7433 // this shufflevector mask.
7434 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7435                            SelectionDAG &DAG) {
7436   // Generate an insertps instruction when inserting an f32 from memory onto a
7437   // v4f32 or when copying a member from one v4f32 to another.
7438   // We also use it for transferring i32 from one register to another,
7439   // since it simply copies the same bits.
7440   // If we're transferring an i32 from memory to a specific element in a
7441   // register, we output a generic DAG that will match the PINSRD
7442   // instruction.
7443   MVT VT = SVOp->getSimpleValueType(0);
7444   MVT EVT = VT.getVectorElementType();
7445   SDValue V1 = SVOp->getOperand(0);
7446   SDValue V2 = SVOp->getOperand(1);
7447   auto Mask = SVOp->getMask();
7448   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7449          "unsupported vector type for insertps/pinsrd");
7450
7451   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7452                              [](const int &i) { return i < 4; });
7453
7454   SDValue From;
7455   SDValue To;
7456   unsigned DestIndex;
7457   if (FromV1 == 1) {
7458     From = V1;
7459     To = V2;
7460     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7461                              [](const int &i) { return i < 4; }) -
7462                 Mask.begin();
7463   } else {
7464     From = V2;
7465     To = V1;
7466     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7467                              [](const int &i) { return i >= 4; }) -
7468                 Mask.begin();
7469   }
7470
7471   if (MayFoldLoad(From)) {
7472     // Trivial case, when From comes from a load and is only used by the
7473     // shuffle. Make it use insertps from the vector that we need from that
7474     // load.
7475     SDValue NewLoad =
7476         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7477     if (!NewLoad.getNode())
7478       return SDValue();
7479
7480     if (EVT == MVT::f32) {
7481       // Create this as a scalar to vector to match the instruction pattern.
7482       SDValue LoadScalarToVector =
7483           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7484       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7485       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7486                          InsertpsMask);
7487     } else { // EVT == MVT::i32
7488       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7489       // instruction, to match the PINSRD instruction, which loads an i32 to a
7490       // certain vector element.
7491       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7492                          DAG.getConstant(DestIndex, MVT::i32));
7493     }
7494   }
7495
7496   // Vector-element-to-vector
7497   unsigned SrcIndex = Mask[DestIndex] % 4;
7498   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7499   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7500 }
7501
7502 // Reduce a vector shuffle to zext.
7503 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7504                                     SelectionDAG &DAG) {
7505   // PMOVZX is only available from SSE41.
7506   if (!Subtarget->hasSSE41())
7507     return SDValue();
7508
7509   MVT VT = Op.getSimpleValueType();
7510
7511   // Only AVX2 support 256-bit vector integer extending.
7512   if (!Subtarget->hasInt256() && VT.is256BitVector())
7513     return SDValue();
7514
7515   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7516   SDLoc DL(Op);
7517   SDValue V1 = Op.getOperand(0);
7518   SDValue V2 = Op.getOperand(1);
7519   unsigned NumElems = VT.getVectorNumElements();
7520
7521   // Extending is an unary operation and the element type of the source vector
7522   // won't be equal to or larger than i64.
7523   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7524       VT.getVectorElementType() == MVT::i64)
7525     return SDValue();
7526
7527   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7528   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7529   while ((1U << Shift) < NumElems) {
7530     if (SVOp->getMaskElt(1U << Shift) == 1)
7531       break;
7532     Shift += 1;
7533     // The maximal ratio is 8, i.e. from i8 to i64.
7534     if (Shift > 3)
7535       return SDValue();
7536   }
7537
7538   // Check the shuffle mask.
7539   unsigned Mask = (1U << Shift) - 1;
7540   for (unsigned i = 0; i != NumElems; ++i) {
7541     int EltIdx = SVOp->getMaskElt(i);
7542     if ((i & Mask) != 0 && EltIdx != -1)
7543       return SDValue();
7544     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7545       return SDValue();
7546   }
7547
7548   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7549   MVT NeVT = MVT::getIntegerVT(NBits);
7550   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7551
7552   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7553     return SDValue();
7554
7555   // Simplify the operand as it's prepared to be fed into shuffle.
7556   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7557   if (V1.getOpcode() == ISD::BITCAST &&
7558       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7559       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7560       V1.getOperand(0).getOperand(0)
7561         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7562     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7563     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7564     ConstantSDNode *CIdx =
7565       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7566     // If it's foldable, i.e. normal load with single use, we will let code
7567     // selection to fold it. Otherwise, we will short the conversion sequence.
7568     if (CIdx && CIdx->getZExtValue() == 0 &&
7569         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7570       MVT FullVT = V.getSimpleValueType();
7571       MVT V1VT = V1.getSimpleValueType();
7572       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7573         // The "ext_vec_elt" node is wider than the result node.
7574         // In this case we should extract subvector from V.
7575         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7576         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7577         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7578                                         FullVT.getVectorNumElements()/Ratio);
7579         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7580                         DAG.getIntPtrConstant(0));
7581       }
7582       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7583     }
7584   }
7585
7586   return DAG.getNode(ISD::BITCAST, DL, VT,
7587                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7588 }
7589
7590 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7591                                       SelectionDAG &DAG) {
7592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7593   MVT VT = Op.getSimpleValueType();
7594   SDLoc dl(Op);
7595   SDValue V1 = Op.getOperand(0);
7596   SDValue V2 = Op.getOperand(1);
7597
7598   if (isZeroShuffle(SVOp))
7599     return getZeroVector(VT, Subtarget, DAG, dl);
7600
7601   // Handle splat operations
7602   if (SVOp->isSplat()) {
7603     // Use vbroadcast whenever the splat comes from a foldable load
7604     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7605     if (Broadcast.getNode())
7606       return Broadcast;
7607   }
7608
7609   // Check integer expanding shuffles.
7610   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7611   if (NewOp.getNode())
7612     return NewOp;
7613
7614   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7615   // do it!
7616   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7617       VT == MVT::v32i8) {
7618     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7619     if (NewOp.getNode())
7620       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7621   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7622     // FIXME: Figure out a cleaner way to do this.
7623     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7624       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7625       if (NewOp.getNode()) {
7626         MVT NewVT = NewOp.getSimpleValueType();
7627         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7628                                NewVT, true, false))
7629           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7630                               dl);
7631       }
7632     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7633       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7634       if (NewOp.getNode()) {
7635         MVT NewVT = NewOp.getSimpleValueType();
7636         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7637           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7638                               dl);
7639       }
7640     }
7641   }
7642   return SDValue();
7643 }
7644
7645 SDValue
7646 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7647   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7648   SDValue V1 = Op.getOperand(0);
7649   SDValue V2 = Op.getOperand(1);
7650   MVT VT = Op.getSimpleValueType();
7651   SDLoc dl(Op);
7652   unsigned NumElems = VT.getVectorNumElements();
7653   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7654   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7655   bool V1IsSplat = false;
7656   bool V2IsSplat = false;
7657   bool HasSSE2 = Subtarget->hasSSE2();
7658   bool HasFp256    = Subtarget->hasFp256();
7659   bool HasInt256   = Subtarget->hasInt256();
7660   MachineFunction &MF = DAG.getMachineFunction();
7661   bool OptForSize = MF.getFunction()->getAttributes().
7662     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7663
7664   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7665
7666   if (V1IsUndef && V2IsUndef)
7667     return DAG.getUNDEF(VT);
7668
7669   // When we create a shuffle node we put the UNDEF node to second operand,
7670   // but in some cases the first operand may be transformed to UNDEF.
7671   // In this case we should just commute the node.
7672   if (V1IsUndef)
7673     return CommuteVectorShuffle(SVOp, DAG);
7674
7675   // Vector shuffle lowering takes 3 steps:
7676   //
7677   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7678   //    narrowing and commutation of operands should be handled.
7679   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7680   //    shuffle nodes.
7681   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7682   //    so the shuffle can be broken into other shuffles and the legalizer can
7683   //    try the lowering again.
7684   //
7685   // The general idea is that no vector_shuffle operation should be left to
7686   // be matched during isel, all of them must be converted to a target specific
7687   // node here.
7688
7689   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7690   // narrowing and commutation of operands should be handled. The actual code
7691   // doesn't include all of those, work in progress...
7692   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7693   if (NewOp.getNode())
7694     return NewOp;
7695
7696   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7697
7698   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7699   // unpckh_undef). Only use pshufd if speed is more important than size.
7700   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7701     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7702   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7703     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7704
7705   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7706       V2IsUndef && MayFoldVectorLoad(V1))
7707     return getMOVDDup(Op, dl, V1, DAG);
7708
7709   if (isMOVHLPS_v_undef_Mask(M, VT))
7710     return getMOVHighToLow(Op, dl, DAG);
7711
7712   // Use to match splats
7713   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7714       (VT == MVT::v2f64 || VT == MVT::v2i64))
7715     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7716
7717   if (isPSHUFDMask(M, VT)) {
7718     // The actual implementation will match the mask in the if above and then
7719     // during isel it can match several different instructions, not only pshufd
7720     // as its name says, sad but true, emulate the behavior for now...
7721     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7722       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7723
7724     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7725
7726     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7727       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7728
7729     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7730       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7731                                   DAG);
7732
7733     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7734                                 TargetMask, DAG);
7735   }
7736
7737   if (isPALIGNRMask(M, VT, Subtarget))
7738     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7739                                 getShufflePALIGNRImmediate(SVOp),
7740                                 DAG);
7741
7742   // Check if this can be converted into a logical shift.
7743   bool isLeft = false;
7744   unsigned ShAmt = 0;
7745   SDValue ShVal;
7746   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7747   if (isShift && ShVal.hasOneUse()) {
7748     // If the shifted value has multiple uses, it may be cheaper to use
7749     // v_set0 + movlhps or movhlps, etc.
7750     MVT EltVT = VT.getVectorElementType();
7751     ShAmt *= EltVT.getSizeInBits();
7752     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7753   }
7754
7755   if (isMOVLMask(M, VT)) {
7756     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7757       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7758     if (!isMOVLPMask(M, VT)) {
7759       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7760         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7761
7762       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7763         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7764     }
7765   }
7766
7767   // FIXME: fold these into legal mask.
7768   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7769     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7770
7771   if (isMOVHLPSMask(M, VT))
7772     return getMOVHighToLow(Op, dl, DAG);
7773
7774   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7775     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7776
7777   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7778     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7779
7780   if (isMOVLPMask(M, VT))
7781     return getMOVLP(Op, dl, DAG, HasSSE2);
7782
7783   if (ShouldXformToMOVHLPS(M, VT) ||
7784       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7785     return CommuteVectorShuffle(SVOp, DAG);
7786
7787   if (isShift) {
7788     // No better options. Use a vshldq / vsrldq.
7789     MVT EltVT = VT.getVectorElementType();
7790     ShAmt *= EltVT.getSizeInBits();
7791     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7792   }
7793
7794   bool Commuted = false;
7795   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7796   // 1,1,1,1 -> v8i16 though.
7797   V1IsSplat = isSplatVector(V1.getNode());
7798   V2IsSplat = isSplatVector(V2.getNode());
7799
7800   // Canonicalize the splat or undef, if present, to be on the RHS.
7801   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7802     CommuteVectorShuffleMask(M, NumElems);
7803     std::swap(V1, V2);
7804     std::swap(V1IsSplat, V2IsSplat);
7805     Commuted = true;
7806   }
7807
7808   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7809     // Shuffling low element of v1 into undef, just return v1.
7810     if (V2IsUndef)
7811       return V1;
7812     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7813     // the instruction selector will not match, so get a canonical MOVL with
7814     // swapped operands to undo the commute.
7815     return getMOVL(DAG, dl, VT, V2, V1);
7816   }
7817
7818   if (isUNPCKLMask(M, VT, HasInt256))
7819     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7820
7821   if (isUNPCKHMask(M, VT, HasInt256))
7822     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7823
7824   if (V2IsSplat) {
7825     // Normalize mask so all entries that point to V2 points to its first
7826     // element then try to match unpck{h|l} again. If match, return a
7827     // new vector_shuffle with the corrected mask.p
7828     SmallVector<int, 8> NewMask(M.begin(), M.end());
7829     NormalizeMask(NewMask, NumElems);
7830     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7831       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7832     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7833       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7834   }
7835
7836   if (Commuted) {
7837     // Commute is back and try unpck* again.
7838     // FIXME: this seems wrong.
7839     CommuteVectorShuffleMask(M, NumElems);
7840     std::swap(V1, V2);
7841     std::swap(V1IsSplat, V2IsSplat);
7842
7843     if (isUNPCKLMask(M, VT, HasInt256))
7844       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7845
7846     if (isUNPCKHMask(M, VT, HasInt256))
7847       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7848   }
7849
7850   // Normalize the node to match x86 shuffle ops if needed
7851   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7852     return CommuteVectorShuffle(SVOp, DAG);
7853
7854   // The checks below are all present in isShuffleMaskLegal, but they are
7855   // inlined here right now to enable us to directly emit target specific
7856   // nodes, and remove one by one until they don't return Op anymore.
7857
7858   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7859       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7860     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7861       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7862   }
7863
7864   if (isPSHUFHWMask(M, VT, HasInt256))
7865     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7866                                 getShufflePSHUFHWImmediate(SVOp),
7867                                 DAG);
7868
7869   if (isPSHUFLWMask(M, VT, HasInt256))
7870     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7871                                 getShufflePSHUFLWImmediate(SVOp),
7872                                 DAG);
7873
7874   if (isSHUFPMask(M, VT))
7875     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7876                                 getShuffleSHUFImmediate(SVOp), DAG);
7877
7878   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7879     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7880   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7881     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7882
7883   //===--------------------------------------------------------------------===//
7884   // Generate target specific nodes for 128 or 256-bit shuffles only
7885   // supported in the AVX instruction set.
7886   //
7887
7888   // Handle VMOVDDUPY permutations
7889   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7890     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7891
7892   // Handle VPERMILPS/D* permutations
7893   if (isVPERMILPMask(M, VT)) {
7894     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7895       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7896                                   getShuffleSHUFImmediate(SVOp), DAG);
7897     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7898                                 getShuffleSHUFImmediate(SVOp), DAG);
7899   }
7900
7901   unsigned Idx;
7902   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7903     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7904                               Idx*(NumElems/2), DAG, dl);
7905
7906   // Handle VPERM2F128/VPERM2I128 permutations
7907   if (isVPERM2X128Mask(M, VT, HasFp256))
7908     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7909                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7910
7911   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7912   if (BlendOp.getNode())
7913     return BlendOp;
7914
7915   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7916     return getINSERTPS(SVOp, dl, DAG);
7917
7918   unsigned Imm8;
7919   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7920     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7921
7922   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7923       VT.is512BitVector()) {
7924     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7925     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7926     SmallVector<SDValue, 16> permclMask;
7927     for (unsigned i = 0; i != NumElems; ++i) {
7928       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7929     }
7930
7931     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7932     if (V2IsUndef)
7933       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7934       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7935                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7936     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7937                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7938   }
7939
7940   //===--------------------------------------------------------------------===//
7941   // Since no target specific shuffle was selected for this generic one,
7942   // lower it into other known shuffles. FIXME: this isn't true yet, but
7943   // this is the plan.
7944   //
7945
7946   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7947   if (VT == MVT::v8i16) {
7948     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7949     if (NewOp.getNode())
7950       return NewOp;
7951   }
7952
7953   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7954     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7955     if (NewOp.getNode())
7956       return NewOp;
7957   }
7958
7959   if (VT == MVT::v16i8) {
7960     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7961     if (NewOp.getNode())
7962       return NewOp;
7963   }
7964
7965   if (VT == MVT::v32i8) {
7966     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7967     if (NewOp.getNode())
7968       return NewOp;
7969   }
7970
7971   // Handle all 128-bit wide vectors with 4 elements, and match them with
7972   // several different shuffle types.
7973   if (NumElems == 4 && VT.is128BitVector())
7974     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7975
7976   // Handle general 256-bit shuffles
7977   if (VT.is256BitVector())
7978     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7979
7980   return SDValue();
7981 }
7982
7983 // This function assumes its argument is a BUILD_VECTOR of constants or
7984 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
7985 // true.
7986 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
7987                                     unsigned &MaskValue) {
7988   MaskValue = 0;
7989   unsigned NumElems = BuildVector->getNumOperands();
7990   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7991   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7992   unsigned NumElemsInLane = NumElems / NumLanes;
7993
7994   // Blend for v16i16 should be symetric for the both lanes.
7995   for (unsigned i = 0; i < NumElemsInLane; ++i) {
7996     SDValue EltCond = BuildVector->getOperand(i);
7997     SDValue SndLaneEltCond =
7998         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
7999
8000     int Lane1Cond = -1, Lane2Cond = -1;
8001     if (isa<ConstantSDNode>(EltCond))
8002       Lane1Cond = !isZero(EltCond);
8003     if (isa<ConstantSDNode>(SndLaneEltCond))
8004       Lane2Cond = !isZero(SndLaneEltCond);
8005
8006     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8007       // Lane1Cond != 0, means we want the first argument.
8008       // Lane1Cond == 0, means we want the second argument.
8009       // The encoding of this argument is 0 for the first argument, 1
8010       // for the second. Therefore, invert the condition.
8011       MaskValue |= !Lane1Cond << i;
8012     else if (Lane1Cond < 0)
8013       MaskValue |= !Lane2Cond << i;
8014     else
8015       return false;
8016   }
8017   return true;
8018 }
8019
8020 // Try to lower a vselect node into a simple blend instruction.
8021 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8022                                    SelectionDAG &DAG) {
8023   SDValue Cond = Op.getOperand(0);
8024   SDValue LHS = Op.getOperand(1);
8025   SDValue RHS = Op.getOperand(2);
8026   SDLoc dl(Op);
8027   MVT VT = Op.getSimpleValueType();
8028   MVT EltVT = VT.getVectorElementType();
8029   unsigned NumElems = VT.getVectorNumElements();
8030
8031   // There is no blend with immediate in AVX-512.
8032   if (VT.is512BitVector())
8033     return SDValue();
8034
8035   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8036     return SDValue();
8037   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8038     return SDValue();
8039
8040   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8041     return SDValue();
8042
8043   // Check the mask for BLEND and build the value.
8044   unsigned MaskValue = 0;
8045   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8046     return SDValue();
8047
8048   // Convert i32 vectors to floating point if it is not AVX2.
8049   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8050   MVT BlendVT = VT;
8051   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8052     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8053                                NumElems);
8054     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8055     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8056   }
8057
8058   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8059                             DAG.getConstant(MaskValue, MVT::i32));
8060   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8061 }
8062
8063 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8064   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8065   if (BlendOp.getNode())
8066     return BlendOp;
8067
8068   // Some types for vselect were previously set to Expand, not Legal or
8069   // Custom. Return an empty SDValue so we fall-through to Expand, after
8070   // the Custom lowering phase.
8071   MVT VT = Op.getSimpleValueType();
8072   switch (VT.SimpleTy) {
8073   default:
8074     break;
8075   case MVT::v8i16:
8076   case MVT::v16i16:
8077     return SDValue();
8078   }
8079
8080   // We couldn't create a "Blend with immediate" node.
8081   // This node should still be legal, but we'll have to emit a blendv*
8082   // instruction.
8083   return Op;
8084 }
8085
8086 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8087   MVT VT = Op.getSimpleValueType();
8088   SDLoc dl(Op);
8089
8090   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8091     return SDValue();
8092
8093   if (VT.getSizeInBits() == 8) {
8094     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8095                                   Op.getOperand(0), Op.getOperand(1));
8096     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8097                                   DAG.getValueType(VT));
8098     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8099   }
8100
8101   if (VT.getSizeInBits() == 16) {
8102     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8103     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8104     if (Idx == 0)
8105       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8106                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8107                                      DAG.getNode(ISD::BITCAST, dl,
8108                                                  MVT::v4i32,
8109                                                  Op.getOperand(0)),
8110                                      Op.getOperand(1)));
8111     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8112                                   Op.getOperand(0), Op.getOperand(1));
8113     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8114                                   DAG.getValueType(VT));
8115     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8116   }
8117
8118   if (VT == MVT::f32) {
8119     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8120     // the result back to FR32 register. It's only worth matching if the
8121     // result has a single use which is a store or a bitcast to i32.  And in
8122     // the case of a store, it's not worth it if the index is a constant 0,
8123     // because a MOVSSmr can be used instead, which is smaller and faster.
8124     if (!Op.hasOneUse())
8125       return SDValue();
8126     SDNode *User = *Op.getNode()->use_begin();
8127     if ((User->getOpcode() != ISD::STORE ||
8128          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8129           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8130         (User->getOpcode() != ISD::BITCAST ||
8131          User->getValueType(0) != MVT::i32))
8132       return SDValue();
8133     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8134                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8135                                               Op.getOperand(0)),
8136                                               Op.getOperand(1));
8137     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8138   }
8139
8140   if (VT == MVT::i32 || VT == MVT::i64) {
8141     // ExtractPS/pextrq works with constant index.
8142     if (isa<ConstantSDNode>(Op.getOperand(1)))
8143       return Op;
8144   }
8145   return SDValue();
8146 }
8147
8148 /// Extract one bit from mask vector, like v16i1 or v8i1.
8149 /// AVX-512 feature.
8150 SDValue
8151 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8152   SDValue Vec = Op.getOperand(0);
8153   SDLoc dl(Vec);
8154   MVT VecVT = Vec.getSimpleValueType();
8155   SDValue Idx = Op.getOperand(1);
8156   MVT EltVT = Op.getSimpleValueType();
8157
8158   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8159
8160   // variable index can't be handled in mask registers,
8161   // extend vector to VR512
8162   if (!isa<ConstantSDNode>(Idx)) {
8163     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8164     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8165     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8166                               ExtVT.getVectorElementType(), Ext, Idx);
8167     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8168   }
8169
8170   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8171   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8172   unsigned MaxSift = rc->getSize()*8 - 1;
8173   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8174                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8175   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8176                     DAG.getConstant(MaxSift, MVT::i8));
8177   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8178                        DAG.getIntPtrConstant(0));
8179 }
8180
8181 SDValue
8182 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8183                                            SelectionDAG &DAG) const {
8184   SDLoc dl(Op);
8185   SDValue Vec = Op.getOperand(0);
8186   MVT VecVT = Vec.getSimpleValueType();
8187   SDValue Idx = Op.getOperand(1);
8188
8189   if (Op.getSimpleValueType() == MVT::i1)
8190     return ExtractBitFromMaskVector(Op, DAG);
8191
8192   if (!isa<ConstantSDNode>(Idx)) {
8193     if (VecVT.is512BitVector() ||
8194         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8195          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8196
8197       MVT MaskEltVT =
8198         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8199       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8200                                     MaskEltVT.getSizeInBits());
8201
8202       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8203       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8204                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8205                                 Idx, DAG.getConstant(0, getPointerTy()));
8206       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8207       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8208                         Perm, DAG.getConstant(0, getPointerTy()));
8209     }
8210     return SDValue();
8211   }
8212
8213   // If this is a 256-bit vector result, first extract the 128-bit vector and
8214   // then extract the element from the 128-bit vector.
8215   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8216
8217     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8218     // Get the 128-bit vector.
8219     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8220     MVT EltVT = VecVT.getVectorElementType();
8221
8222     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8223
8224     //if (IdxVal >= NumElems/2)
8225     //  IdxVal -= NumElems/2;
8226     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8227     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8228                        DAG.getConstant(IdxVal, MVT::i32));
8229   }
8230
8231   assert(VecVT.is128BitVector() && "Unexpected vector length");
8232
8233   if (Subtarget->hasSSE41()) {
8234     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8235     if (Res.getNode())
8236       return Res;
8237   }
8238
8239   MVT VT = Op.getSimpleValueType();
8240   // TODO: handle v16i8.
8241   if (VT.getSizeInBits() == 16) {
8242     SDValue Vec = Op.getOperand(0);
8243     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8244     if (Idx == 0)
8245       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8246                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8247                                      DAG.getNode(ISD::BITCAST, dl,
8248                                                  MVT::v4i32, Vec),
8249                                      Op.getOperand(1)));
8250     // Transform it so it match pextrw which produces a 32-bit result.
8251     MVT EltVT = MVT::i32;
8252     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8253                                   Op.getOperand(0), Op.getOperand(1));
8254     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8255                                   DAG.getValueType(VT));
8256     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8257   }
8258
8259   if (VT.getSizeInBits() == 32) {
8260     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8261     if (Idx == 0)
8262       return Op;
8263
8264     // SHUFPS the element to the lowest double word, then movss.
8265     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8266     MVT VVT = Op.getOperand(0).getSimpleValueType();
8267     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8268                                        DAG.getUNDEF(VVT), Mask);
8269     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8270                        DAG.getIntPtrConstant(0));
8271   }
8272
8273   if (VT.getSizeInBits() == 64) {
8274     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8275     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8276     //        to match extract_elt for f64.
8277     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8278     if (Idx == 0)
8279       return Op;
8280
8281     // UNPCKHPD the element to the lowest double word, then movsd.
8282     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8283     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8284     int Mask[2] = { 1, -1 };
8285     MVT VVT = Op.getOperand(0).getSimpleValueType();
8286     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8287                                        DAG.getUNDEF(VVT), Mask);
8288     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8289                        DAG.getIntPtrConstant(0));
8290   }
8291
8292   return SDValue();
8293 }
8294
8295 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8296   MVT VT = Op.getSimpleValueType();
8297   MVT EltVT = VT.getVectorElementType();
8298   SDLoc dl(Op);
8299
8300   SDValue N0 = Op.getOperand(0);
8301   SDValue N1 = Op.getOperand(1);
8302   SDValue N2 = Op.getOperand(2);
8303
8304   if (!VT.is128BitVector())
8305     return SDValue();
8306
8307   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8308       isa<ConstantSDNode>(N2)) {
8309     unsigned Opc;
8310     if (VT == MVT::v8i16)
8311       Opc = X86ISD::PINSRW;
8312     else if (VT == MVT::v16i8)
8313       Opc = X86ISD::PINSRB;
8314     else
8315       Opc = X86ISD::PINSRB;
8316
8317     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8318     // argument.
8319     if (N1.getValueType() != MVT::i32)
8320       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8321     if (N2.getValueType() != MVT::i32)
8322       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8323     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8324   }
8325
8326   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8327     // Bits [7:6] of the constant are the source select.  This will always be
8328     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8329     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8330     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8331     // Bits [5:4] of the constant are the destination select.  This is the
8332     //  value of the incoming immediate.
8333     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8334     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8335     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8336     // Create this as a scalar to vector..
8337     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8338     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8339   }
8340
8341   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8342     // PINSR* works with constant index.
8343     return Op;
8344   }
8345   return SDValue();
8346 }
8347
8348 /// Insert one bit to mask vector, like v16i1 or v8i1.
8349 /// AVX-512 feature.
8350 SDValue 
8351 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8352   SDLoc dl(Op);
8353   SDValue Vec = Op.getOperand(0);
8354   SDValue Elt = Op.getOperand(1);
8355   SDValue Idx = Op.getOperand(2);
8356   MVT VecVT = Vec.getSimpleValueType();
8357
8358   if (!isa<ConstantSDNode>(Idx)) {
8359     // Non constant index. Extend source and destination,
8360     // insert element and then truncate the result.
8361     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8362     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8363     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8364       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8365       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8366     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8367   }
8368
8369   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8370   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8371   if (Vec.getOpcode() == ISD::UNDEF)
8372     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8373                        DAG.getConstant(IdxVal, MVT::i8));
8374   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8375   unsigned MaxSift = rc->getSize()*8 - 1;
8376   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8377                     DAG.getConstant(MaxSift, MVT::i8));
8378   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8379                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8380   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8381 }
8382 SDValue
8383 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8384   MVT VT = Op.getSimpleValueType();
8385   MVT EltVT = VT.getVectorElementType();
8386   
8387   if (EltVT == MVT::i1)
8388     return InsertBitToMaskVector(Op, DAG);
8389
8390   SDLoc dl(Op);
8391   SDValue N0 = Op.getOperand(0);
8392   SDValue N1 = Op.getOperand(1);
8393   SDValue N2 = Op.getOperand(2);
8394
8395   // If this is a 256-bit vector result, first extract the 128-bit vector,
8396   // insert the element into the extracted half and then place it back.
8397   if (VT.is256BitVector() || VT.is512BitVector()) {
8398     if (!isa<ConstantSDNode>(N2))
8399       return SDValue();
8400
8401     // Get the desired 128-bit vector half.
8402     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8403     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8404
8405     // Insert the element into the desired half.
8406     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8407     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8408
8409     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8410                     DAG.getConstant(IdxIn128, MVT::i32));
8411
8412     // Insert the changed part back to the 256-bit vector
8413     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8414   }
8415
8416   if (Subtarget->hasSSE41())
8417     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8418
8419   if (EltVT == MVT::i8)
8420     return SDValue();
8421
8422   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8423     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8424     // as its second argument.
8425     if (N1.getValueType() != MVT::i32)
8426       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8427     if (N2.getValueType() != MVT::i32)
8428       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8429     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8430   }
8431   return SDValue();
8432 }
8433
8434 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8435   SDLoc dl(Op);
8436   MVT OpVT = Op.getSimpleValueType();
8437
8438   // If this is a 256-bit vector result, first insert into a 128-bit
8439   // vector and then insert into the 256-bit vector.
8440   if (!OpVT.is128BitVector()) {
8441     // Insert into a 128-bit vector.
8442     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8443     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8444                                  OpVT.getVectorNumElements() / SizeFactor);
8445
8446     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8447
8448     // Insert the 128-bit vector.
8449     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8450   }
8451
8452   if (OpVT == MVT::v1i64 &&
8453       Op.getOperand(0).getValueType() == MVT::i64)
8454     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8455
8456   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8457   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8458   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8459                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8460 }
8461
8462 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8463 // a simple subregister reference or explicit instructions to grab
8464 // upper bits of a vector.
8465 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8466                                       SelectionDAG &DAG) {
8467   SDLoc dl(Op);
8468   SDValue In =  Op.getOperand(0);
8469   SDValue Idx = Op.getOperand(1);
8470   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8471   MVT ResVT   = Op.getSimpleValueType();
8472   MVT InVT    = In.getSimpleValueType();
8473
8474   if (Subtarget->hasFp256()) {
8475     if (ResVT.is128BitVector() &&
8476         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8477         isa<ConstantSDNode>(Idx)) {
8478       return Extract128BitVector(In, IdxVal, DAG, dl);
8479     }
8480     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8481         isa<ConstantSDNode>(Idx)) {
8482       return Extract256BitVector(In, IdxVal, DAG, dl);
8483     }
8484   }
8485   return SDValue();
8486 }
8487
8488 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8489 // simple superregister reference or explicit instructions to insert
8490 // the upper bits of a vector.
8491 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8492                                      SelectionDAG &DAG) {
8493   if (Subtarget->hasFp256()) {
8494     SDLoc dl(Op.getNode());
8495     SDValue Vec = Op.getNode()->getOperand(0);
8496     SDValue SubVec = Op.getNode()->getOperand(1);
8497     SDValue Idx = Op.getNode()->getOperand(2);
8498
8499     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8500          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8501         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8502         isa<ConstantSDNode>(Idx)) {
8503       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8504       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8505     }
8506
8507     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8508         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8509         isa<ConstantSDNode>(Idx)) {
8510       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8511       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8512     }
8513   }
8514   return SDValue();
8515 }
8516
8517 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8518 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8519 // one of the above mentioned nodes. It has to be wrapped because otherwise
8520 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8521 // be used to form addressing mode. These wrapped nodes will be selected
8522 // into MOV32ri.
8523 SDValue
8524 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8525   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8526
8527   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8528   // global base reg.
8529   unsigned char OpFlag = 0;
8530   unsigned WrapperKind = X86ISD::Wrapper;
8531   CodeModel::Model M = getTargetMachine().getCodeModel();
8532
8533   if (Subtarget->isPICStyleRIPRel() &&
8534       (M == CodeModel::Small || M == CodeModel::Kernel))
8535     WrapperKind = X86ISD::WrapperRIP;
8536   else if (Subtarget->isPICStyleGOT())
8537     OpFlag = X86II::MO_GOTOFF;
8538   else if (Subtarget->isPICStyleStubPIC())
8539     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8540
8541   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8542                                              CP->getAlignment(),
8543                                              CP->getOffset(), OpFlag);
8544   SDLoc DL(CP);
8545   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8546   // With PIC, the address is actually $g + Offset.
8547   if (OpFlag) {
8548     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8549                          DAG.getNode(X86ISD::GlobalBaseReg,
8550                                      SDLoc(), getPointerTy()),
8551                          Result);
8552   }
8553
8554   return Result;
8555 }
8556
8557 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8558   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8559
8560   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8561   // global base reg.
8562   unsigned char OpFlag = 0;
8563   unsigned WrapperKind = X86ISD::Wrapper;
8564   CodeModel::Model M = getTargetMachine().getCodeModel();
8565
8566   if (Subtarget->isPICStyleRIPRel() &&
8567       (M == CodeModel::Small || M == CodeModel::Kernel))
8568     WrapperKind = X86ISD::WrapperRIP;
8569   else if (Subtarget->isPICStyleGOT())
8570     OpFlag = X86II::MO_GOTOFF;
8571   else if (Subtarget->isPICStyleStubPIC())
8572     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8573
8574   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8575                                           OpFlag);
8576   SDLoc DL(JT);
8577   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8578
8579   // With PIC, the address is actually $g + Offset.
8580   if (OpFlag)
8581     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8582                          DAG.getNode(X86ISD::GlobalBaseReg,
8583                                      SDLoc(), getPointerTy()),
8584                          Result);
8585
8586   return Result;
8587 }
8588
8589 SDValue
8590 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8591   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8592
8593   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8594   // global base reg.
8595   unsigned char OpFlag = 0;
8596   unsigned WrapperKind = X86ISD::Wrapper;
8597   CodeModel::Model M = getTargetMachine().getCodeModel();
8598
8599   if (Subtarget->isPICStyleRIPRel() &&
8600       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8601     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8602       OpFlag = X86II::MO_GOTPCREL;
8603     WrapperKind = X86ISD::WrapperRIP;
8604   } else if (Subtarget->isPICStyleGOT()) {
8605     OpFlag = X86II::MO_GOT;
8606   } else if (Subtarget->isPICStyleStubPIC()) {
8607     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8608   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8609     OpFlag = X86II::MO_DARWIN_NONLAZY;
8610   }
8611
8612   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8613
8614   SDLoc DL(Op);
8615   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8616
8617   // With PIC, the address is actually $g + Offset.
8618   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8619       !Subtarget->is64Bit()) {
8620     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8621                          DAG.getNode(X86ISD::GlobalBaseReg,
8622                                      SDLoc(), getPointerTy()),
8623                          Result);
8624   }
8625
8626   // For symbols that require a load from a stub to get the address, emit the
8627   // load.
8628   if (isGlobalStubReference(OpFlag))
8629     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8630                          MachinePointerInfo::getGOT(), false, false, false, 0);
8631
8632   return Result;
8633 }
8634
8635 SDValue
8636 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8637   // Create the TargetBlockAddressAddress node.
8638   unsigned char OpFlags =
8639     Subtarget->ClassifyBlockAddressReference();
8640   CodeModel::Model M = getTargetMachine().getCodeModel();
8641   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8642   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8643   SDLoc dl(Op);
8644   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8645                                              OpFlags);
8646
8647   if (Subtarget->isPICStyleRIPRel() &&
8648       (M == CodeModel::Small || M == CodeModel::Kernel))
8649     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8650   else
8651     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8652
8653   // With PIC, the address is actually $g + Offset.
8654   if (isGlobalRelativeToPICBase(OpFlags)) {
8655     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8656                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8657                          Result);
8658   }
8659
8660   return Result;
8661 }
8662
8663 SDValue
8664 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8665                                       int64_t Offset, SelectionDAG &DAG) const {
8666   // Create the TargetGlobalAddress node, folding in the constant
8667   // offset if it is legal.
8668   unsigned char OpFlags =
8669     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8670   CodeModel::Model M = getTargetMachine().getCodeModel();
8671   SDValue Result;
8672   if (OpFlags == X86II::MO_NO_FLAG &&
8673       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8674     // A direct static reference to a global.
8675     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8676     Offset = 0;
8677   } else {
8678     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8679   }
8680
8681   if (Subtarget->isPICStyleRIPRel() &&
8682       (M == CodeModel::Small || M == CodeModel::Kernel))
8683     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8684   else
8685     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8686
8687   // With PIC, the address is actually $g + Offset.
8688   if (isGlobalRelativeToPICBase(OpFlags)) {
8689     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8690                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8691                          Result);
8692   }
8693
8694   // For globals that require a load from a stub to get the address, emit the
8695   // load.
8696   if (isGlobalStubReference(OpFlags))
8697     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8698                          MachinePointerInfo::getGOT(), false, false, false, 0);
8699
8700   // If there was a non-zero offset that we didn't fold, create an explicit
8701   // addition for it.
8702   if (Offset != 0)
8703     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8704                          DAG.getConstant(Offset, getPointerTy()));
8705
8706   return Result;
8707 }
8708
8709 SDValue
8710 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8711   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8712   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8713   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8714 }
8715
8716 static SDValue
8717 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8718            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8719            unsigned char OperandFlags, bool LocalDynamic = false) {
8720   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8721   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8722   SDLoc dl(GA);
8723   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8724                                            GA->getValueType(0),
8725                                            GA->getOffset(),
8726                                            OperandFlags);
8727
8728   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8729                                            : X86ISD::TLSADDR;
8730
8731   if (InFlag) {
8732     SDValue Ops[] = { Chain,  TGA, *InFlag };
8733     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8734   } else {
8735     SDValue Ops[]  = { Chain, TGA };
8736     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8737   }
8738
8739   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8740   MFI->setAdjustsStack(true);
8741
8742   SDValue Flag = Chain.getValue(1);
8743   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8744 }
8745
8746 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8747 static SDValue
8748 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8749                                 const EVT PtrVT) {
8750   SDValue InFlag;
8751   SDLoc dl(GA);  // ? function entry point might be better
8752   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8753                                    DAG.getNode(X86ISD::GlobalBaseReg,
8754                                                SDLoc(), PtrVT), InFlag);
8755   InFlag = Chain.getValue(1);
8756
8757   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8758 }
8759
8760 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8761 static SDValue
8762 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8763                                 const EVT PtrVT) {
8764   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8765                     X86::RAX, X86II::MO_TLSGD);
8766 }
8767
8768 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8769                                            SelectionDAG &DAG,
8770                                            const EVT PtrVT,
8771                                            bool is64Bit) {
8772   SDLoc dl(GA);
8773
8774   // Get the start address of the TLS block for this module.
8775   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8776       .getInfo<X86MachineFunctionInfo>();
8777   MFI->incNumLocalDynamicTLSAccesses();
8778
8779   SDValue Base;
8780   if (is64Bit) {
8781     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8782                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8783   } else {
8784     SDValue InFlag;
8785     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8786         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8787     InFlag = Chain.getValue(1);
8788     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8789                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8790   }
8791
8792   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8793   // of Base.
8794
8795   // Build x@dtpoff.
8796   unsigned char OperandFlags = X86II::MO_DTPOFF;
8797   unsigned WrapperKind = X86ISD::Wrapper;
8798   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8799                                            GA->getValueType(0),
8800                                            GA->getOffset(), OperandFlags);
8801   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8802
8803   // Add x@dtpoff with the base.
8804   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8805 }
8806
8807 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8808 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8809                                    const EVT PtrVT, TLSModel::Model model,
8810                                    bool is64Bit, bool isPIC) {
8811   SDLoc dl(GA);
8812
8813   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8814   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8815                                                          is64Bit ? 257 : 256));
8816
8817   SDValue ThreadPointer =
8818       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8819                   MachinePointerInfo(Ptr), false, false, false, 0);
8820
8821   unsigned char OperandFlags = 0;
8822   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8823   // initialexec.
8824   unsigned WrapperKind = X86ISD::Wrapper;
8825   if (model == TLSModel::LocalExec) {
8826     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8827   } else if (model == TLSModel::InitialExec) {
8828     if (is64Bit) {
8829       OperandFlags = X86II::MO_GOTTPOFF;
8830       WrapperKind = X86ISD::WrapperRIP;
8831     } else {
8832       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8833     }
8834   } else {
8835     llvm_unreachable("Unexpected model");
8836   }
8837
8838   // emit "addl x@ntpoff,%eax" (local exec)
8839   // or "addl x@indntpoff,%eax" (initial exec)
8840   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8841   SDValue TGA =
8842       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8843                                  GA->getOffset(), OperandFlags);
8844   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8845
8846   if (model == TLSModel::InitialExec) {
8847     if (isPIC && !is64Bit) {
8848       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8849                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8850                            Offset);
8851     }
8852
8853     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8854                          MachinePointerInfo::getGOT(), false, false, false, 0);
8855   }
8856
8857   // The address of the thread local variable is the add of the thread
8858   // pointer with the offset of the variable.
8859   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8860 }
8861
8862 SDValue
8863 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8864
8865   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8866   const GlobalValue *GV = GA->getGlobal();
8867
8868   if (Subtarget->isTargetELF()) {
8869     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8870
8871     switch (model) {
8872       case TLSModel::GeneralDynamic:
8873         if (Subtarget->is64Bit())
8874           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8875         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8876       case TLSModel::LocalDynamic:
8877         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8878                                            Subtarget->is64Bit());
8879       case TLSModel::InitialExec:
8880       case TLSModel::LocalExec:
8881         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8882                                    Subtarget->is64Bit(),
8883                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8884     }
8885     llvm_unreachable("Unknown TLS model.");
8886   }
8887
8888   if (Subtarget->isTargetDarwin()) {
8889     // Darwin only has one model of TLS.  Lower to that.
8890     unsigned char OpFlag = 0;
8891     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8892                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8893
8894     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8895     // global base reg.
8896     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8897                   !Subtarget->is64Bit();
8898     if (PIC32)
8899       OpFlag = X86II::MO_TLVP_PIC_BASE;
8900     else
8901       OpFlag = X86II::MO_TLVP;
8902     SDLoc DL(Op);
8903     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8904                                                 GA->getValueType(0),
8905                                                 GA->getOffset(), OpFlag);
8906     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8907
8908     // With PIC32, the address is actually $g + Offset.
8909     if (PIC32)
8910       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8911                            DAG.getNode(X86ISD::GlobalBaseReg,
8912                                        SDLoc(), getPointerTy()),
8913                            Offset);
8914
8915     // Lowering the machine isd will make sure everything is in the right
8916     // location.
8917     SDValue Chain = DAG.getEntryNode();
8918     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8919     SDValue Args[] = { Chain, Offset };
8920     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8921
8922     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8923     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8924     MFI->setAdjustsStack(true);
8925
8926     // And our return value (tls address) is in the standard call return value
8927     // location.
8928     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8929     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8930                               Chain.getValue(1));
8931   }
8932
8933   if (Subtarget->isTargetKnownWindowsMSVC() ||
8934       Subtarget->isTargetWindowsGNU()) {
8935     // Just use the implicit TLS architecture
8936     // Need to generate someting similar to:
8937     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8938     //                                  ; from TEB
8939     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8940     //   mov     rcx, qword [rdx+rcx*8]
8941     //   mov     eax, .tls$:tlsvar
8942     //   [rax+rcx] contains the address
8943     // Windows 64bit: gs:0x58
8944     // Windows 32bit: fs:__tls_array
8945
8946     // If GV is an alias then use the aliasee for determining
8947     // thread-localness.
8948     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8949       GV = GA->getAliasee();
8950     SDLoc dl(GA);
8951     SDValue Chain = DAG.getEntryNode();
8952
8953     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8954     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8955     // use its literal value of 0x2C.
8956     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8957                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8958                                                              256)
8959                                         : Type::getInt32PtrTy(*DAG.getContext(),
8960                                                               257));
8961
8962     SDValue TlsArray =
8963         Subtarget->is64Bit()
8964             ? DAG.getIntPtrConstant(0x58)
8965             : (Subtarget->isTargetWindowsGNU()
8966                    ? DAG.getIntPtrConstant(0x2C)
8967                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8968
8969     SDValue ThreadPointer =
8970         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8971                     MachinePointerInfo(Ptr), false, false, false, 0);
8972
8973     // Load the _tls_index variable
8974     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8975     if (Subtarget->is64Bit())
8976       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8977                            IDX, MachinePointerInfo(), MVT::i32,
8978                            false, false, 0);
8979     else
8980       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8981                         false, false, false, 0);
8982
8983     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8984                                     getPointerTy());
8985     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8986
8987     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8988     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8989                       false, false, false, 0);
8990
8991     // Get the offset of start of .tls section
8992     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8993                                              GA->getValueType(0),
8994                                              GA->getOffset(), X86II::MO_SECREL);
8995     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8996
8997     // The address of the thread local variable is the add of the thread
8998     // pointer with the offset of the variable.
8999     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9000   }
9001
9002   llvm_unreachable("TLS not implemented for this target.");
9003 }
9004
9005 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9006 /// and take a 2 x i32 value to shift plus a shift amount.
9007 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9008   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9009   MVT VT = Op.getSimpleValueType();
9010   unsigned VTBits = VT.getSizeInBits();
9011   SDLoc dl(Op);
9012   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9013   SDValue ShOpLo = Op.getOperand(0);
9014   SDValue ShOpHi = Op.getOperand(1);
9015   SDValue ShAmt  = Op.getOperand(2);
9016   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9017   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9018   // during isel.
9019   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9020                                   DAG.getConstant(VTBits - 1, MVT::i8));
9021   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9022                                      DAG.getConstant(VTBits - 1, MVT::i8))
9023                        : DAG.getConstant(0, VT);
9024
9025   SDValue Tmp2, Tmp3;
9026   if (Op.getOpcode() == ISD::SHL_PARTS) {
9027     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9028     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9029   } else {
9030     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9031     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9032   }
9033
9034   // If the shift amount is larger or equal than the width of a part we can't
9035   // rely on the results of shld/shrd. Insert a test and select the appropriate
9036   // values for large shift amounts.
9037   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9038                                 DAG.getConstant(VTBits, MVT::i8));
9039   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9040                              AndNode, DAG.getConstant(0, MVT::i8));
9041
9042   SDValue Hi, Lo;
9043   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9044   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9045   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9046
9047   if (Op.getOpcode() == ISD::SHL_PARTS) {
9048     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9049     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9050   } else {
9051     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9052     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9053   }
9054
9055   SDValue Ops[2] = { Lo, Hi };
9056   return DAG.getMergeValues(Ops, dl);
9057 }
9058
9059 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9060                                            SelectionDAG &DAG) const {
9061   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9062
9063   if (SrcVT.isVector())
9064     return SDValue();
9065
9066   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9067          "Unknown SINT_TO_FP to lower!");
9068
9069   // These are really Legal; return the operand so the caller accepts it as
9070   // Legal.
9071   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9072     return Op;
9073   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9074       Subtarget->is64Bit()) {
9075     return Op;
9076   }
9077
9078   SDLoc dl(Op);
9079   unsigned Size = SrcVT.getSizeInBits()/8;
9080   MachineFunction &MF = DAG.getMachineFunction();
9081   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9082   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9083   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9084                                StackSlot,
9085                                MachinePointerInfo::getFixedStack(SSFI),
9086                                false, false, 0);
9087   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9088 }
9089
9090 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9091                                      SDValue StackSlot,
9092                                      SelectionDAG &DAG) const {
9093   // Build the FILD
9094   SDLoc DL(Op);
9095   SDVTList Tys;
9096   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9097   if (useSSE)
9098     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9099   else
9100     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9101
9102   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9103
9104   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9105   MachineMemOperand *MMO;
9106   if (FI) {
9107     int SSFI = FI->getIndex();
9108     MMO =
9109       DAG.getMachineFunction()
9110       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9111                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9112   } else {
9113     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9114     StackSlot = StackSlot.getOperand(1);
9115   }
9116   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9117   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9118                                            X86ISD::FILD, DL,
9119                                            Tys, Ops, SrcVT, MMO);
9120
9121   if (useSSE) {
9122     Chain = Result.getValue(1);
9123     SDValue InFlag = Result.getValue(2);
9124
9125     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9126     // shouldn't be necessary except that RFP cannot be live across
9127     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9128     MachineFunction &MF = DAG.getMachineFunction();
9129     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9130     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9131     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9132     Tys = DAG.getVTList(MVT::Other);
9133     SDValue Ops[] = {
9134       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9135     };
9136     MachineMemOperand *MMO =
9137       DAG.getMachineFunction()
9138       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9139                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9140
9141     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9142                                     Ops, Op.getValueType(), MMO);
9143     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9144                          MachinePointerInfo::getFixedStack(SSFI),
9145                          false, false, false, 0);
9146   }
9147
9148   return Result;
9149 }
9150
9151 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9152 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9153                                                SelectionDAG &DAG) const {
9154   // This algorithm is not obvious. Here it is what we're trying to output:
9155   /*
9156      movq       %rax,  %xmm0
9157      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9158      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9159      #ifdef __SSE3__
9160        haddpd   %xmm0, %xmm0
9161      #else
9162        pshufd   $0x4e, %xmm0, %xmm1
9163        addpd    %xmm1, %xmm0
9164      #endif
9165   */
9166
9167   SDLoc dl(Op);
9168   LLVMContext *Context = DAG.getContext();
9169
9170   // Build some magic constants.
9171   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9172   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9173   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9174
9175   SmallVector<Constant*,2> CV1;
9176   CV1.push_back(
9177     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9178                                       APInt(64, 0x4330000000000000ULL))));
9179   CV1.push_back(
9180     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9181                                       APInt(64, 0x4530000000000000ULL))));
9182   Constant *C1 = ConstantVector::get(CV1);
9183   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9184
9185   // Load the 64-bit value into an XMM register.
9186   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9187                             Op.getOperand(0));
9188   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9189                               MachinePointerInfo::getConstantPool(),
9190                               false, false, false, 16);
9191   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9192                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9193                               CLod0);
9194
9195   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9196                               MachinePointerInfo::getConstantPool(),
9197                               false, false, false, 16);
9198   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9199   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9200   SDValue Result;
9201
9202   if (Subtarget->hasSSE3()) {
9203     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9204     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9205   } else {
9206     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9207     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9208                                            S2F, 0x4E, DAG);
9209     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9210                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9211                          Sub);
9212   }
9213
9214   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9215                      DAG.getIntPtrConstant(0));
9216 }
9217
9218 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9219 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9220                                                SelectionDAG &DAG) const {
9221   SDLoc dl(Op);
9222   // FP constant to bias correct the final result.
9223   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9224                                    MVT::f64);
9225
9226   // Load the 32-bit value into an XMM register.
9227   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9228                              Op.getOperand(0));
9229
9230   // Zero out the upper parts of the register.
9231   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9232
9233   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9234                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9235                      DAG.getIntPtrConstant(0));
9236
9237   // Or the load with the bias.
9238   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9239                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9240                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9241                                                    MVT::v2f64, Load)),
9242                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9243                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9244                                                    MVT::v2f64, Bias)));
9245   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9246                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9247                    DAG.getIntPtrConstant(0));
9248
9249   // Subtract the bias.
9250   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9251
9252   // Handle final rounding.
9253   EVT DestVT = Op.getValueType();
9254
9255   if (DestVT.bitsLT(MVT::f64))
9256     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9257                        DAG.getIntPtrConstant(0));
9258   if (DestVT.bitsGT(MVT::f64))
9259     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9260
9261   // Handle final rounding.
9262   return Sub;
9263 }
9264
9265 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9266                                                SelectionDAG &DAG) const {
9267   SDValue N0 = Op.getOperand(0);
9268   MVT SVT = N0.getSimpleValueType();
9269   SDLoc dl(Op);
9270
9271   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9272           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9273          "Custom UINT_TO_FP is not supported!");
9274
9275   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9276   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9277                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9278 }
9279
9280 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9281                                            SelectionDAG &DAG) const {
9282   SDValue N0 = Op.getOperand(0);
9283   SDLoc dl(Op);
9284
9285   if (Op.getValueType().isVector())
9286     return lowerUINT_TO_FP_vec(Op, DAG);
9287
9288   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9289   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9290   // the optimization here.
9291   if (DAG.SignBitIsZero(N0))
9292     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9293
9294   MVT SrcVT = N0.getSimpleValueType();
9295   MVT DstVT = Op.getSimpleValueType();
9296   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9297     return LowerUINT_TO_FP_i64(Op, DAG);
9298   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9299     return LowerUINT_TO_FP_i32(Op, DAG);
9300   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9301     return SDValue();
9302
9303   // Make a 64-bit buffer, and use it to build an FILD.
9304   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9305   if (SrcVT == MVT::i32) {
9306     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9307     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9308                                      getPointerTy(), StackSlot, WordOff);
9309     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9310                                   StackSlot, MachinePointerInfo(),
9311                                   false, false, 0);
9312     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9313                                   OffsetSlot, MachinePointerInfo(),
9314                                   false, false, 0);
9315     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9316     return Fild;
9317   }
9318
9319   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9320   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9321                                StackSlot, MachinePointerInfo(),
9322                                false, false, 0);
9323   // For i64 source, we need to add the appropriate power of 2 if the input
9324   // was negative.  This is the same as the optimization in
9325   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9326   // we must be careful to do the computation in x87 extended precision, not
9327   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9328   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9329   MachineMemOperand *MMO =
9330     DAG.getMachineFunction()
9331     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9332                           MachineMemOperand::MOLoad, 8, 8);
9333
9334   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9335   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9336   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9337                                          MVT::i64, MMO);
9338
9339   APInt FF(32, 0x5F800000ULL);
9340
9341   // Check whether the sign bit is set.
9342   SDValue SignSet = DAG.getSetCC(dl,
9343                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9344                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9345                                  ISD::SETLT);
9346
9347   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9348   SDValue FudgePtr = DAG.getConstantPool(
9349                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9350                                          getPointerTy());
9351
9352   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9353   SDValue Zero = DAG.getIntPtrConstant(0);
9354   SDValue Four = DAG.getIntPtrConstant(4);
9355   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9356                                Zero, Four);
9357   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9358
9359   // Load the value out, extending it from f32 to f80.
9360   // FIXME: Avoid the extend by constructing the right constant pool?
9361   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9362                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9363                                  MVT::f32, false, false, 4);
9364   // Extend everything to 80 bits to force it to be done on x87.
9365   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9366   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9367 }
9368
9369 std::pair<SDValue,SDValue>
9370 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9371                                     bool IsSigned, bool IsReplace) const {
9372   SDLoc DL(Op);
9373
9374   EVT DstTy = Op.getValueType();
9375
9376   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9377     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9378     DstTy = MVT::i64;
9379   }
9380
9381   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9382          DstTy.getSimpleVT() >= MVT::i16 &&
9383          "Unknown FP_TO_INT to lower!");
9384
9385   // These are really Legal.
9386   if (DstTy == MVT::i32 &&
9387       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9388     return std::make_pair(SDValue(), SDValue());
9389   if (Subtarget->is64Bit() &&
9390       DstTy == MVT::i64 &&
9391       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9392     return std::make_pair(SDValue(), SDValue());
9393
9394   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9395   // stack slot, or into the FTOL runtime function.
9396   MachineFunction &MF = DAG.getMachineFunction();
9397   unsigned MemSize = DstTy.getSizeInBits()/8;
9398   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9399   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9400
9401   unsigned Opc;
9402   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9403     Opc = X86ISD::WIN_FTOL;
9404   else
9405     switch (DstTy.getSimpleVT().SimpleTy) {
9406     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9407     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9408     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9409     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9410     }
9411
9412   SDValue Chain = DAG.getEntryNode();
9413   SDValue Value = Op.getOperand(0);
9414   EVT TheVT = Op.getOperand(0).getValueType();
9415   // FIXME This causes a redundant load/store if the SSE-class value is already
9416   // in memory, such as if it is on the callstack.
9417   if (isScalarFPTypeInSSEReg(TheVT)) {
9418     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9419     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9420                          MachinePointerInfo::getFixedStack(SSFI),
9421                          false, false, 0);
9422     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9423     SDValue Ops[] = {
9424       Chain, StackSlot, DAG.getValueType(TheVT)
9425     };
9426
9427     MachineMemOperand *MMO =
9428       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9429                               MachineMemOperand::MOLoad, MemSize, MemSize);
9430     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9431     Chain = Value.getValue(1);
9432     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9433     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9434   }
9435
9436   MachineMemOperand *MMO =
9437     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9438                             MachineMemOperand::MOStore, MemSize, MemSize);
9439
9440   if (Opc != X86ISD::WIN_FTOL) {
9441     // Build the FP_TO_INT*_IN_MEM
9442     SDValue Ops[] = { Chain, Value, StackSlot };
9443     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9444                                            Ops, DstTy, MMO);
9445     return std::make_pair(FIST, StackSlot);
9446   } else {
9447     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9448       DAG.getVTList(MVT::Other, MVT::Glue),
9449       Chain, Value);
9450     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9451       MVT::i32, ftol.getValue(1));
9452     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9453       MVT::i32, eax.getValue(2));
9454     SDValue Ops[] = { eax, edx };
9455     SDValue pair = IsReplace
9456       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9457       : DAG.getMergeValues(Ops, DL);
9458     return std::make_pair(pair, SDValue());
9459   }
9460 }
9461
9462 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9463                               const X86Subtarget *Subtarget) {
9464   MVT VT = Op->getSimpleValueType(0);
9465   SDValue In = Op->getOperand(0);
9466   MVT InVT = In.getSimpleValueType();
9467   SDLoc dl(Op);
9468
9469   // Optimize vectors in AVX mode:
9470   //
9471   //   v8i16 -> v8i32
9472   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9473   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9474   //   Concat upper and lower parts.
9475   //
9476   //   v4i32 -> v4i64
9477   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9478   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9479   //   Concat upper and lower parts.
9480   //
9481
9482   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9483       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9484       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9485     return SDValue();
9486
9487   if (Subtarget->hasInt256())
9488     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9489
9490   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9491   SDValue Undef = DAG.getUNDEF(InVT);
9492   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9493   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9494   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9495
9496   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9497                              VT.getVectorNumElements()/2);
9498
9499   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9500   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9501
9502   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9503 }
9504
9505 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9506                                         SelectionDAG &DAG) {
9507   MVT VT = Op->getSimpleValueType(0);
9508   SDValue In = Op->getOperand(0);
9509   MVT InVT = In.getSimpleValueType();
9510   SDLoc DL(Op);
9511   unsigned int NumElts = VT.getVectorNumElements();
9512   if (NumElts != 8 && NumElts != 16)
9513     return SDValue();
9514
9515   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9516     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9517
9518   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9520   // Now we have only mask extension
9521   assert(InVT.getVectorElementType() == MVT::i1);
9522   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9523   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9524   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9525   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9526   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9527                            MachinePointerInfo::getConstantPool(),
9528                            false, false, false, Alignment);
9529
9530   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9531   if (VT.is512BitVector())
9532     return Brcst;
9533   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9534 }
9535
9536 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9537                                SelectionDAG &DAG) {
9538   if (Subtarget->hasFp256()) {
9539     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9540     if (Res.getNode())
9541       return Res;
9542   }
9543
9544   return SDValue();
9545 }
9546
9547 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9548                                 SelectionDAG &DAG) {
9549   SDLoc DL(Op);
9550   MVT VT = Op.getSimpleValueType();
9551   SDValue In = Op.getOperand(0);
9552   MVT SVT = In.getSimpleValueType();
9553
9554   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9555     return LowerZERO_EXTEND_AVX512(Op, DAG);
9556
9557   if (Subtarget->hasFp256()) {
9558     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9559     if (Res.getNode())
9560       return Res;
9561   }
9562
9563   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9564          VT.getVectorNumElements() != SVT.getVectorNumElements());
9565   return SDValue();
9566 }
9567
9568 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9569   SDLoc DL(Op);
9570   MVT VT = Op.getSimpleValueType();
9571   SDValue In = Op.getOperand(0);
9572   MVT InVT = In.getSimpleValueType();
9573
9574   if (VT == MVT::i1) {
9575     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9576            "Invalid scalar TRUNCATE operation");
9577     if (InVT == MVT::i32)
9578       return SDValue();
9579     if (InVT.getSizeInBits() == 64)
9580       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9581     else if (InVT.getSizeInBits() < 32)
9582       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9583     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9584   }
9585   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9586          "Invalid TRUNCATE operation");
9587
9588   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9589     if (VT.getVectorElementType().getSizeInBits() >=8)
9590       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9591
9592     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9593     unsigned NumElts = InVT.getVectorNumElements();
9594     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9595     if (InVT.getSizeInBits() < 512) {
9596       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9597       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9598       InVT = ExtVT;
9599     }
9600     
9601     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9602     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9603     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9604     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9605     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9606                            MachinePointerInfo::getConstantPool(),
9607                            false, false, false, Alignment);
9608     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9609     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9610     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9611   }
9612
9613   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9614     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9615     if (Subtarget->hasInt256()) {
9616       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9617       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9618       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9619                                 ShufMask);
9620       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9621                          DAG.getIntPtrConstant(0));
9622     }
9623
9624     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9625                                DAG.getIntPtrConstant(0));
9626     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9627                                DAG.getIntPtrConstant(2));
9628     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9629     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9630     static const int ShufMask[] = {0, 2, 4, 6};
9631     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9632   }
9633
9634   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9635     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9636     if (Subtarget->hasInt256()) {
9637       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9638
9639       SmallVector<SDValue,32> pshufbMask;
9640       for (unsigned i = 0; i < 2; ++i) {
9641         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9642         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9643         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9644         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9645         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9646         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9647         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9648         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9649         for (unsigned j = 0; j < 8; ++j)
9650           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9651       }
9652       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9653       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9654       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9655
9656       static const int ShufMask[] = {0,  2,  -1,  -1};
9657       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9658                                 &ShufMask[0]);
9659       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9660                        DAG.getIntPtrConstant(0));
9661       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9662     }
9663
9664     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9665                                DAG.getIntPtrConstant(0));
9666
9667     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9668                                DAG.getIntPtrConstant(4));
9669
9670     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9671     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9672
9673     // The PSHUFB mask:
9674     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9675                                    -1, -1, -1, -1, -1, -1, -1, -1};
9676
9677     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9678     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9679     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9680
9681     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9682     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9683
9684     // The MOVLHPS Mask:
9685     static const int ShufMask2[] = {0, 1, 4, 5};
9686     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9687     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9688   }
9689
9690   // Handle truncation of V256 to V128 using shuffles.
9691   if (!VT.is128BitVector() || !InVT.is256BitVector())
9692     return SDValue();
9693
9694   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9695
9696   unsigned NumElems = VT.getVectorNumElements();
9697   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9698
9699   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9700   // Prepare truncation shuffle mask
9701   for (unsigned i = 0; i != NumElems; ++i)
9702     MaskVec[i] = i * 2;
9703   SDValue V = DAG.getVectorShuffle(NVT, DL,
9704                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9705                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9706   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9707                      DAG.getIntPtrConstant(0));
9708 }
9709
9710 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9711                                            SelectionDAG &DAG) const {
9712   assert(!Op.getSimpleValueType().isVector());
9713
9714   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9715     /*IsSigned=*/ true, /*IsReplace=*/ false);
9716   SDValue FIST = Vals.first, StackSlot = Vals.second;
9717   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9718   if (!FIST.getNode()) return Op;
9719
9720   if (StackSlot.getNode())
9721     // Load the result.
9722     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9723                        FIST, StackSlot, MachinePointerInfo(),
9724                        false, false, false, 0);
9725
9726   // The node is the result.
9727   return FIST;
9728 }
9729
9730 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9731                                            SelectionDAG &DAG) const {
9732   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9733     /*IsSigned=*/ false, /*IsReplace=*/ false);
9734   SDValue FIST = Vals.first, StackSlot = Vals.second;
9735   assert(FIST.getNode() && "Unexpected failure");
9736
9737   if (StackSlot.getNode())
9738     // Load the result.
9739     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9740                        FIST, StackSlot, MachinePointerInfo(),
9741                        false, false, false, 0);
9742
9743   // The node is the result.
9744   return FIST;
9745 }
9746
9747 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9748   SDLoc DL(Op);
9749   MVT VT = Op.getSimpleValueType();
9750   SDValue In = Op.getOperand(0);
9751   MVT SVT = In.getSimpleValueType();
9752
9753   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9754
9755   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9756                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9757                                  In, DAG.getUNDEF(SVT)));
9758 }
9759
9760 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9761   LLVMContext *Context = DAG.getContext();
9762   SDLoc dl(Op);
9763   MVT VT = Op.getSimpleValueType();
9764   MVT EltVT = VT;
9765   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9766   if (VT.isVector()) {
9767     EltVT = VT.getVectorElementType();
9768     NumElts = VT.getVectorNumElements();
9769   }
9770   Constant *C;
9771   if (EltVT == MVT::f64)
9772     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9773                                           APInt(64, ~(1ULL << 63))));
9774   else
9775     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9776                                           APInt(32, ~(1U << 31))));
9777   C = ConstantVector::getSplat(NumElts, C);
9778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9779   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9780   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9781   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9782                              MachinePointerInfo::getConstantPool(),
9783                              false, false, false, Alignment);
9784   if (VT.isVector()) {
9785     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9786     return DAG.getNode(ISD::BITCAST, dl, VT,
9787                        DAG.getNode(ISD::AND, dl, ANDVT,
9788                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9789                                                Op.getOperand(0)),
9790                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9791   }
9792   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9793 }
9794
9795 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9796   LLVMContext *Context = DAG.getContext();
9797   SDLoc dl(Op);
9798   MVT VT = Op.getSimpleValueType();
9799   MVT EltVT = VT;
9800   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9801   if (VT.isVector()) {
9802     EltVT = VT.getVectorElementType();
9803     NumElts = VT.getVectorNumElements();
9804   }
9805   Constant *C;
9806   if (EltVT == MVT::f64)
9807     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9808                                           APInt(64, 1ULL << 63)));
9809   else
9810     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9811                                           APInt(32, 1U << 31)));
9812   C = ConstantVector::getSplat(NumElts, C);
9813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9814   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9815   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9816   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9817                              MachinePointerInfo::getConstantPool(),
9818                              false, false, false, Alignment);
9819   if (VT.isVector()) {
9820     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9821     return DAG.getNode(ISD::BITCAST, dl, VT,
9822                        DAG.getNode(ISD::XOR, dl, XORVT,
9823                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9824                                                Op.getOperand(0)),
9825                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9826   }
9827
9828   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9829 }
9830
9831 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9833   LLVMContext *Context = DAG.getContext();
9834   SDValue Op0 = Op.getOperand(0);
9835   SDValue Op1 = Op.getOperand(1);
9836   SDLoc dl(Op);
9837   MVT VT = Op.getSimpleValueType();
9838   MVT SrcVT = Op1.getSimpleValueType();
9839
9840   // If second operand is smaller, extend it first.
9841   if (SrcVT.bitsLT(VT)) {
9842     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9843     SrcVT = VT;
9844   }
9845   // And if it is bigger, shrink it first.
9846   if (SrcVT.bitsGT(VT)) {
9847     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9848     SrcVT = VT;
9849   }
9850
9851   // At this point the operands and the result should have the same
9852   // type, and that won't be f80 since that is not custom lowered.
9853
9854   // First get the sign bit of second operand.
9855   SmallVector<Constant*,4> CV;
9856   if (SrcVT == MVT::f64) {
9857     const fltSemantics &Sem = APFloat::IEEEdouble;
9858     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9859     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9860   } else {
9861     const fltSemantics &Sem = APFloat::IEEEsingle;
9862     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9863     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9864     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9865     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9866   }
9867   Constant *C = ConstantVector::get(CV);
9868   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9869   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9870                               MachinePointerInfo::getConstantPool(),
9871                               false, false, false, 16);
9872   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9873
9874   // Shift sign bit right or left if the two operands have different types.
9875   if (SrcVT.bitsGT(VT)) {
9876     // Op0 is MVT::f32, Op1 is MVT::f64.
9877     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9878     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9879                           DAG.getConstant(32, MVT::i32));
9880     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9881     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9882                           DAG.getIntPtrConstant(0));
9883   }
9884
9885   // Clear first operand sign bit.
9886   CV.clear();
9887   if (VT == MVT::f64) {
9888     const fltSemantics &Sem = APFloat::IEEEdouble;
9889     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9890                                                    APInt(64, ~(1ULL << 63)))));
9891     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9892   } else {
9893     const fltSemantics &Sem = APFloat::IEEEsingle;
9894     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9895                                                    APInt(32, ~(1U << 31)))));
9896     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9897     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9898     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9899   }
9900   C = ConstantVector::get(CV);
9901   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9902   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9903                               MachinePointerInfo::getConstantPool(),
9904                               false, false, false, 16);
9905   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9906
9907   // Or the value with the sign bit.
9908   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9909 }
9910
9911 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9912   SDValue N0 = Op.getOperand(0);
9913   SDLoc dl(Op);
9914   MVT VT = Op.getSimpleValueType();
9915
9916   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9917   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9918                                   DAG.getConstant(1, VT));
9919   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9920 }
9921
9922 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9923 //
9924 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9925                                       SelectionDAG &DAG) {
9926   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9927
9928   if (!Subtarget->hasSSE41())
9929     return SDValue();
9930
9931   if (!Op->hasOneUse())
9932     return SDValue();
9933
9934   SDNode *N = Op.getNode();
9935   SDLoc DL(N);
9936
9937   SmallVector<SDValue, 8> Opnds;
9938   DenseMap<SDValue, unsigned> VecInMap;
9939   SmallVector<SDValue, 8> VecIns;
9940   EVT VT = MVT::Other;
9941
9942   // Recognize a special case where a vector is casted into wide integer to
9943   // test all 0s.
9944   Opnds.push_back(N->getOperand(0));
9945   Opnds.push_back(N->getOperand(1));
9946
9947   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9948     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9949     // BFS traverse all OR'd operands.
9950     if (I->getOpcode() == ISD::OR) {
9951       Opnds.push_back(I->getOperand(0));
9952       Opnds.push_back(I->getOperand(1));
9953       // Re-evaluate the number of nodes to be traversed.
9954       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9955       continue;
9956     }
9957
9958     // Quit if a non-EXTRACT_VECTOR_ELT
9959     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9960       return SDValue();
9961
9962     // Quit if without a constant index.
9963     SDValue Idx = I->getOperand(1);
9964     if (!isa<ConstantSDNode>(Idx))
9965       return SDValue();
9966
9967     SDValue ExtractedFromVec = I->getOperand(0);
9968     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9969     if (M == VecInMap.end()) {
9970       VT = ExtractedFromVec.getValueType();
9971       // Quit if not 128/256-bit vector.
9972       if (!VT.is128BitVector() && !VT.is256BitVector())
9973         return SDValue();
9974       // Quit if not the same type.
9975       if (VecInMap.begin() != VecInMap.end() &&
9976           VT != VecInMap.begin()->first.getValueType())
9977         return SDValue();
9978       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9979       VecIns.push_back(ExtractedFromVec);
9980     }
9981     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9982   }
9983
9984   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9985          "Not extracted from 128-/256-bit vector.");
9986
9987   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9988
9989   for (DenseMap<SDValue, unsigned>::const_iterator
9990         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9991     // Quit if not all elements are used.
9992     if (I->second != FullMask)
9993       return SDValue();
9994   }
9995
9996   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9997
9998   // Cast all vectors into TestVT for PTEST.
9999   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10000     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10001
10002   // If more than one full vectors are evaluated, OR them first before PTEST.
10003   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10004     // Each iteration will OR 2 nodes and append the result until there is only
10005     // 1 node left, i.e. the final OR'd value of all vectors.
10006     SDValue LHS = VecIns[Slot];
10007     SDValue RHS = VecIns[Slot + 1];
10008     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10009   }
10010
10011   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10012                      VecIns.back(), VecIns.back());
10013 }
10014
10015 /// \brief return true if \c Op has a use that doesn't just read flags.
10016 static bool hasNonFlagsUse(SDValue Op) {
10017   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10018        ++UI) {
10019     SDNode *User = *UI;
10020     unsigned UOpNo = UI.getOperandNo();
10021     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10022       // Look pass truncate.
10023       UOpNo = User->use_begin().getOperandNo();
10024       User = *User->use_begin();
10025     }
10026
10027     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10028         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10029       return true;
10030   }
10031   return false;
10032 }
10033
10034 /// Emit nodes that will be selected as "test Op0,Op0", or something
10035 /// equivalent.
10036 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10037                                     SelectionDAG &DAG) const {
10038   if (Op.getValueType() == MVT::i1)
10039     // KORTEST instruction should be selected
10040     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10041                        DAG.getConstant(0, Op.getValueType()));
10042
10043   // CF and OF aren't always set the way we want. Determine which
10044   // of these we need.
10045   bool NeedCF = false;
10046   bool NeedOF = false;
10047   switch (X86CC) {
10048   default: break;
10049   case X86::COND_A: case X86::COND_AE:
10050   case X86::COND_B: case X86::COND_BE:
10051     NeedCF = true;
10052     break;
10053   case X86::COND_G: case X86::COND_GE:
10054   case X86::COND_L: case X86::COND_LE:
10055   case X86::COND_O: case X86::COND_NO:
10056     NeedOF = true;
10057     break;
10058   }
10059   // See if we can use the EFLAGS value from the operand instead of
10060   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10061   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10062   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10063     // Emit a CMP with 0, which is the TEST pattern.
10064     //if (Op.getValueType() == MVT::i1)
10065     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10066     //                     DAG.getConstant(0, MVT::i1));
10067     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10068                        DAG.getConstant(0, Op.getValueType()));
10069   }
10070   unsigned Opcode = 0;
10071   unsigned NumOperands = 0;
10072
10073   // Truncate operations may prevent the merge of the SETCC instruction
10074   // and the arithmetic instruction before it. Attempt to truncate the operands
10075   // of the arithmetic instruction and use a reduced bit-width instruction.
10076   bool NeedTruncation = false;
10077   SDValue ArithOp = Op;
10078   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10079     SDValue Arith = Op->getOperand(0);
10080     // Both the trunc and the arithmetic op need to have one user each.
10081     if (Arith->hasOneUse())
10082       switch (Arith.getOpcode()) {
10083         default: break;
10084         case ISD::ADD:
10085         case ISD::SUB:
10086         case ISD::AND:
10087         case ISD::OR:
10088         case ISD::XOR: {
10089           NeedTruncation = true;
10090           ArithOp = Arith;
10091         }
10092       }
10093   }
10094
10095   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10096   // which may be the result of a CAST.  We use the variable 'Op', which is the
10097   // non-casted variable when we check for possible users.
10098   switch (ArithOp.getOpcode()) {
10099   case ISD::ADD:
10100     // Due to an isel shortcoming, be conservative if this add is likely to be
10101     // selected as part of a load-modify-store instruction. When the root node
10102     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10103     // uses of other nodes in the match, such as the ADD in this case. This
10104     // leads to the ADD being left around and reselected, with the result being
10105     // two adds in the output.  Alas, even if none our users are stores, that
10106     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10107     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10108     // climbing the DAG back to the root, and it doesn't seem to be worth the
10109     // effort.
10110     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10111          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10112       if (UI->getOpcode() != ISD::CopyToReg &&
10113           UI->getOpcode() != ISD::SETCC &&
10114           UI->getOpcode() != ISD::STORE)
10115         goto default_case;
10116
10117     if (ConstantSDNode *C =
10118         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10119       // An add of one will be selected as an INC.
10120       if (C->getAPIntValue() == 1) {
10121         Opcode = X86ISD::INC;
10122         NumOperands = 1;
10123         break;
10124       }
10125
10126       // An add of negative one (subtract of one) will be selected as a DEC.
10127       if (C->getAPIntValue().isAllOnesValue()) {
10128         Opcode = X86ISD::DEC;
10129         NumOperands = 1;
10130         break;
10131       }
10132     }
10133
10134     // Otherwise use a regular EFLAGS-setting add.
10135     Opcode = X86ISD::ADD;
10136     NumOperands = 2;
10137     break;
10138   case ISD::SHL:
10139   case ISD::SRL:
10140     // If we have a constant logical shift that's only used in a comparison
10141     // against zero turn it into an equivalent AND. This allows turning it into
10142     // a TEST instruction later.
10143     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10144         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10145       EVT VT = Op.getValueType();
10146       unsigned BitWidth = VT.getSizeInBits();
10147       unsigned ShAmt = Op->getConstantOperandVal(1);
10148       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10149         break;
10150       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10151                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10152                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10153       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10154         break;
10155       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10156                                 DAG.getConstant(Mask, VT));
10157       DAG.ReplaceAllUsesWith(Op, New);
10158       Op = New;
10159     }
10160     break;
10161
10162   case ISD::AND:
10163     // If the primary and result isn't used, don't bother using X86ISD::AND,
10164     // because a TEST instruction will be better.
10165     if (!hasNonFlagsUse(Op))
10166       break;
10167     // FALL THROUGH
10168   case ISD::SUB:
10169   case ISD::OR:
10170   case ISD::XOR:
10171     // Due to the ISEL shortcoming noted above, be conservative if this op is
10172     // likely to be selected as part of a load-modify-store instruction.
10173     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10174            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10175       if (UI->getOpcode() == ISD::STORE)
10176         goto default_case;
10177
10178     // Otherwise use a regular EFLAGS-setting instruction.
10179     switch (ArithOp.getOpcode()) {
10180     default: llvm_unreachable("unexpected operator!");
10181     case ISD::SUB: Opcode = X86ISD::SUB; break;
10182     case ISD::XOR: Opcode = X86ISD::XOR; break;
10183     case ISD::AND: Opcode = X86ISD::AND; break;
10184     case ISD::OR: {
10185       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10186         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10187         if (EFLAGS.getNode())
10188           return EFLAGS;
10189       }
10190       Opcode = X86ISD::OR;
10191       break;
10192     }
10193     }
10194
10195     NumOperands = 2;
10196     break;
10197   case X86ISD::ADD:
10198   case X86ISD::SUB:
10199   case X86ISD::INC:
10200   case X86ISD::DEC:
10201   case X86ISD::OR:
10202   case X86ISD::XOR:
10203   case X86ISD::AND:
10204     return SDValue(Op.getNode(), 1);
10205   default:
10206   default_case:
10207     break;
10208   }
10209
10210   // If we found that truncation is beneficial, perform the truncation and
10211   // update 'Op'.
10212   if (NeedTruncation) {
10213     EVT VT = Op.getValueType();
10214     SDValue WideVal = Op->getOperand(0);
10215     EVT WideVT = WideVal.getValueType();
10216     unsigned ConvertedOp = 0;
10217     // Use a target machine opcode to prevent further DAGCombine
10218     // optimizations that may separate the arithmetic operations
10219     // from the setcc node.
10220     switch (WideVal.getOpcode()) {
10221       default: break;
10222       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10223       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10224       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10225       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10226       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10227     }
10228
10229     if (ConvertedOp) {
10230       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10231       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10232         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10233         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10234         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10235       }
10236     }
10237   }
10238
10239   if (Opcode == 0)
10240     // Emit a CMP with 0, which is the TEST pattern.
10241     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10242                        DAG.getConstant(0, Op.getValueType()));
10243
10244   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10245   SmallVector<SDValue, 4> Ops;
10246   for (unsigned i = 0; i != NumOperands; ++i)
10247     Ops.push_back(Op.getOperand(i));
10248
10249   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10250   DAG.ReplaceAllUsesWith(Op, New);
10251   return SDValue(New.getNode(), 1);
10252 }
10253
10254 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10255 /// equivalent.
10256 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10257                                    SDLoc dl, SelectionDAG &DAG) const {
10258   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10259     if (C->getAPIntValue() == 0)
10260       return EmitTest(Op0, X86CC, dl, DAG);
10261
10262      if (Op0.getValueType() == MVT::i1)
10263        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10264   }
10265  
10266   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10267        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10268     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10269     // This avoids subregister aliasing issues. Keep the smaller reference 
10270     // if we're optimizing for size, however, as that'll allow better folding 
10271     // of memory operations.
10272     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10273         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10274              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10275         !Subtarget->isAtom()) {
10276       unsigned ExtendOp =
10277           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10278       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10279       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10280     }
10281     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10282     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10283     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10284                               Op0, Op1);
10285     return SDValue(Sub.getNode(), 1);
10286   }
10287   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10288 }
10289
10290 /// Convert a comparison if required by the subtarget.
10291 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10292                                                  SelectionDAG &DAG) const {
10293   // If the subtarget does not support the FUCOMI instruction, floating-point
10294   // comparisons have to be converted.
10295   if (Subtarget->hasCMov() ||
10296       Cmp.getOpcode() != X86ISD::CMP ||
10297       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10298       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10299     return Cmp;
10300
10301   // The instruction selector will select an FUCOM instruction instead of
10302   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10303   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10304   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10305   SDLoc dl(Cmp);
10306   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10307   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10308   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10309                             DAG.getConstant(8, MVT::i8));
10310   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10311   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10312 }
10313
10314 static bool isAllOnes(SDValue V) {
10315   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10316   return C && C->isAllOnesValue();
10317 }
10318
10319 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10320 /// if it's possible.
10321 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10322                                      SDLoc dl, SelectionDAG &DAG) const {
10323   SDValue Op0 = And.getOperand(0);
10324   SDValue Op1 = And.getOperand(1);
10325   if (Op0.getOpcode() == ISD::TRUNCATE)
10326     Op0 = Op0.getOperand(0);
10327   if (Op1.getOpcode() == ISD::TRUNCATE)
10328     Op1 = Op1.getOperand(0);
10329
10330   SDValue LHS, RHS;
10331   if (Op1.getOpcode() == ISD::SHL)
10332     std::swap(Op0, Op1);
10333   if (Op0.getOpcode() == ISD::SHL) {
10334     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10335       if (And00C->getZExtValue() == 1) {
10336         // If we looked past a truncate, check that it's only truncating away
10337         // known zeros.
10338         unsigned BitWidth = Op0.getValueSizeInBits();
10339         unsigned AndBitWidth = And.getValueSizeInBits();
10340         if (BitWidth > AndBitWidth) {
10341           APInt Zeros, Ones;
10342           DAG.computeKnownBits(Op0, Zeros, Ones);
10343           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10344             return SDValue();
10345         }
10346         LHS = Op1;
10347         RHS = Op0.getOperand(1);
10348       }
10349   } else if (Op1.getOpcode() == ISD::Constant) {
10350     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10351     uint64_t AndRHSVal = AndRHS->getZExtValue();
10352     SDValue AndLHS = Op0;
10353
10354     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10355       LHS = AndLHS.getOperand(0);
10356       RHS = AndLHS.getOperand(1);
10357     }
10358
10359     // Use BT if the immediate can't be encoded in a TEST instruction.
10360     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10361       LHS = AndLHS;
10362       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10363     }
10364   }
10365
10366   if (LHS.getNode()) {
10367     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10368     // instruction.  Since the shift amount is in-range-or-undefined, we know
10369     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10370     // the encoding for the i16 version is larger than the i32 version.
10371     // Also promote i16 to i32 for performance / code size reason.
10372     if (LHS.getValueType() == MVT::i8 ||
10373         LHS.getValueType() == MVT::i16)
10374       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10375
10376     // If the operand types disagree, extend the shift amount to match.  Since
10377     // BT ignores high bits (like shifts) we can use anyextend.
10378     if (LHS.getValueType() != RHS.getValueType())
10379       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10380
10381     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10382     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10383     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10384                        DAG.getConstant(Cond, MVT::i8), BT);
10385   }
10386
10387   return SDValue();
10388 }
10389
10390 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10391 /// mask CMPs.
10392 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10393                               SDValue &Op1) {
10394   unsigned SSECC;
10395   bool Swap = false;
10396
10397   // SSE Condition code mapping:
10398   //  0 - EQ
10399   //  1 - LT
10400   //  2 - LE
10401   //  3 - UNORD
10402   //  4 - NEQ
10403   //  5 - NLT
10404   //  6 - NLE
10405   //  7 - ORD
10406   switch (SetCCOpcode) {
10407   default: llvm_unreachable("Unexpected SETCC condition");
10408   case ISD::SETOEQ:
10409   case ISD::SETEQ:  SSECC = 0; break;
10410   case ISD::SETOGT:
10411   case ISD::SETGT:  Swap = true; // Fallthrough
10412   case ISD::SETLT:
10413   case ISD::SETOLT: SSECC = 1; break;
10414   case ISD::SETOGE:
10415   case ISD::SETGE:  Swap = true; // Fallthrough
10416   case ISD::SETLE:
10417   case ISD::SETOLE: SSECC = 2; break;
10418   case ISD::SETUO:  SSECC = 3; break;
10419   case ISD::SETUNE:
10420   case ISD::SETNE:  SSECC = 4; break;
10421   case ISD::SETULE: Swap = true; // Fallthrough
10422   case ISD::SETUGE: SSECC = 5; break;
10423   case ISD::SETULT: Swap = true; // Fallthrough
10424   case ISD::SETUGT: SSECC = 6; break;
10425   case ISD::SETO:   SSECC = 7; break;
10426   case ISD::SETUEQ:
10427   case ISD::SETONE: SSECC = 8; break;
10428   }
10429   if (Swap)
10430     std::swap(Op0, Op1);
10431
10432   return SSECC;
10433 }
10434
10435 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10436 // ones, and then concatenate the result back.
10437 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10438   MVT VT = Op.getSimpleValueType();
10439
10440   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10441          "Unsupported value type for operation");
10442
10443   unsigned NumElems = VT.getVectorNumElements();
10444   SDLoc dl(Op);
10445   SDValue CC = Op.getOperand(2);
10446
10447   // Extract the LHS vectors
10448   SDValue LHS = Op.getOperand(0);
10449   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10450   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10451
10452   // Extract the RHS vectors
10453   SDValue RHS = Op.getOperand(1);
10454   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10455   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10456
10457   // Issue the operation on the smaller types and concatenate the result back
10458   MVT EltVT = VT.getVectorElementType();
10459   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10460   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10461                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10462                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10463 }
10464
10465 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10466                                      const X86Subtarget *Subtarget) {
10467   SDValue Op0 = Op.getOperand(0);
10468   SDValue Op1 = Op.getOperand(1);
10469   SDValue CC = Op.getOperand(2);
10470   MVT VT = Op.getSimpleValueType();
10471   SDLoc dl(Op);
10472
10473   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10474          Op.getValueType().getScalarType() == MVT::i1 &&
10475          "Cannot set masked compare for this operation");
10476
10477   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10478   unsigned  Opc = 0;
10479   bool Unsigned = false;
10480   bool Swap = false;
10481   unsigned SSECC;
10482   switch (SetCCOpcode) {
10483   default: llvm_unreachable("Unexpected SETCC condition");
10484   case ISD::SETNE:  SSECC = 4; break;
10485   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10486   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10487   case ISD::SETLT:  Swap = true; //fall-through
10488   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10489   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10490   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10491   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10492   case ISD::SETULE: Unsigned = true; //fall-through
10493   case ISD::SETLE:  SSECC = 2; break;
10494   }
10495
10496   if (Swap)
10497     std::swap(Op0, Op1);
10498   if (Opc)
10499     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10500   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10501   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10502                      DAG.getConstant(SSECC, MVT::i8));
10503 }
10504
10505 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10506 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10507 /// return an empty value.
10508 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10509 {
10510   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10511   if (!BV)
10512     return SDValue();
10513
10514   MVT VT = Op1.getSimpleValueType();
10515   MVT EVT = VT.getVectorElementType();
10516   unsigned n = VT.getVectorNumElements();
10517   SmallVector<SDValue, 8> ULTOp1;
10518
10519   for (unsigned i = 0; i < n; ++i) {
10520     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10521     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10522       return SDValue();
10523
10524     // Avoid underflow.
10525     APInt Val = Elt->getAPIntValue();
10526     if (Val == 0)
10527       return SDValue();
10528
10529     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10530   }
10531
10532   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10533 }
10534
10535 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10536                            SelectionDAG &DAG) {
10537   SDValue Op0 = Op.getOperand(0);
10538   SDValue Op1 = Op.getOperand(1);
10539   SDValue CC = Op.getOperand(2);
10540   MVT VT = Op.getSimpleValueType();
10541   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10542   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10543   SDLoc dl(Op);
10544
10545   if (isFP) {
10546 #ifndef NDEBUG
10547     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10548     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10549 #endif
10550
10551     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10552     unsigned Opc = X86ISD::CMPP;
10553     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10554       assert(VT.getVectorNumElements() <= 16);
10555       Opc = X86ISD::CMPM;
10556     }
10557     // In the two special cases we can't handle, emit two comparisons.
10558     if (SSECC == 8) {
10559       unsigned CC0, CC1;
10560       unsigned CombineOpc;
10561       if (SetCCOpcode == ISD::SETUEQ) {
10562         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10563       } else {
10564         assert(SetCCOpcode == ISD::SETONE);
10565         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10566       }
10567
10568       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10569                                  DAG.getConstant(CC0, MVT::i8));
10570       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10571                                  DAG.getConstant(CC1, MVT::i8));
10572       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10573     }
10574     // Handle all other FP comparisons here.
10575     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10576                        DAG.getConstant(SSECC, MVT::i8));
10577   }
10578
10579   // Break 256-bit integer vector compare into smaller ones.
10580   if (VT.is256BitVector() && !Subtarget->hasInt256())
10581     return Lower256IntVSETCC(Op, DAG);
10582
10583   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10584   EVT OpVT = Op1.getValueType();
10585   if (Subtarget->hasAVX512()) {
10586     if (Op1.getValueType().is512BitVector() ||
10587         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10588       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10589
10590     // In AVX-512 architecture setcc returns mask with i1 elements,
10591     // But there is no compare instruction for i8 and i16 elements.
10592     // We are not talking about 512-bit operands in this case, these
10593     // types are illegal.
10594     if (MaskResult &&
10595         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10596          OpVT.getVectorElementType().getSizeInBits() >= 8))
10597       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10598                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10599   }
10600
10601   // We are handling one of the integer comparisons here.  Since SSE only has
10602   // GT and EQ comparisons for integer, swapping operands and multiple
10603   // operations may be required for some comparisons.
10604   unsigned Opc;
10605   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10606   bool Subus = false;
10607
10608   switch (SetCCOpcode) {
10609   default: llvm_unreachable("Unexpected SETCC condition");
10610   case ISD::SETNE:  Invert = true;
10611   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10612   case ISD::SETLT:  Swap = true;
10613   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10614   case ISD::SETGE:  Swap = true;
10615   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10616                     Invert = true; break;
10617   case ISD::SETULT: Swap = true;
10618   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10619                     FlipSigns = true; break;
10620   case ISD::SETUGE: Swap = true;
10621   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10622                     FlipSigns = true; Invert = true; break;
10623   }
10624
10625   // Special case: Use min/max operations for SETULE/SETUGE
10626   MVT VET = VT.getVectorElementType();
10627   bool hasMinMax =
10628        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10629     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10630
10631   if (hasMinMax) {
10632     switch (SetCCOpcode) {
10633     default: break;
10634     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10635     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10636     }
10637
10638     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10639   }
10640
10641   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10642   if (!MinMax && hasSubus) {
10643     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10644     // Op0 u<= Op1:
10645     //   t = psubus Op0, Op1
10646     //   pcmpeq t, <0..0>
10647     switch (SetCCOpcode) {
10648     default: break;
10649     case ISD::SETULT: {
10650       // If the comparison is against a constant we can turn this into a
10651       // setule.  With psubus, setule does not require a swap.  This is
10652       // beneficial because the constant in the register is no longer
10653       // destructed as the destination so it can be hoisted out of a loop.
10654       // Only do this pre-AVX since vpcmp* is no longer destructive.
10655       if (Subtarget->hasAVX())
10656         break;
10657       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10658       if (ULEOp1.getNode()) {
10659         Op1 = ULEOp1;
10660         Subus = true; Invert = false; Swap = false;
10661       }
10662       break;
10663     }
10664     // Psubus is better than flip-sign because it requires no inversion.
10665     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10666     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10667     }
10668
10669     if (Subus) {
10670       Opc = X86ISD::SUBUS;
10671       FlipSigns = false;
10672     }
10673   }
10674
10675   if (Swap)
10676     std::swap(Op0, Op1);
10677
10678   // Check that the operation in question is available (most are plain SSE2,
10679   // but PCMPGTQ and PCMPEQQ have different requirements).
10680   if (VT == MVT::v2i64) {
10681     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10682       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10683
10684       // First cast everything to the right type.
10685       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10686       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10687
10688       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10689       // bits of the inputs before performing those operations. The lower
10690       // compare is always unsigned.
10691       SDValue SB;
10692       if (FlipSigns) {
10693         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10694       } else {
10695         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10696         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10697         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10698                          Sign, Zero, Sign, Zero);
10699       }
10700       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10701       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10702
10703       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10704       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10705       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10706
10707       // Create masks for only the low parts/high parts of the 64 bit integers.
10708       static const int MaskHi[] = { 1, 1, 3, 3 };
10709       static const int MaskLo[] = { 0, 0, 2, 2 };
10710       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10711       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10712       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10713
10714       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10715       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10716
10717       if (Invert)
10718         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10719
10720       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10721     }
10722
10723     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10724       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10725       // pcmpeqd + pshufd + pand.
10726       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10727
10728       // First cast everything to the right type.
10729       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10730       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10731
10732       // Do the compare.
10733       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10734
10735       // Make sure the lower and upper halves are both all-ones.
10736       static const int Mask[] = { 1, 0, 3, 2 };
10737       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10738       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10739
10740       if (Invert)
10741         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10742
10743       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10744     }
10745   }
10746
10747   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10748   // bits of the inputs before performing those operations.
10749   if (FlipSigns) {
10750     EVT EltVT = VT.getVectorElementType();
10751     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10752     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10753     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10754   }
10755
10756   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10757
10758   // If the logical-not of the result is required, perform that now.
10759   if (Invert)
10760     Result = DAG.getNOT(dl, Result, VT);
10761
10762   if (MinMax)
10763     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10764
10765   if (Subus)
10766     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10767                          getZeroVector(VT, Subtarget, DAG, dl));
10768
10769   return Result;
10770 }
10771
10772 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10773
10774   MVT VT = Op.getSimpleValueType();
10775
10776   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10777
10778   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10779          && "SetCC type must be 8-bit or 1-bit integer");
10780   SDValue Op0 = Op.getOperand(0);
10781   SDValue Op1 = Op.getOperand(1);
10782   SDLoc dl(Op);
10783   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10784
10785   // Optimize to BT if possible.
10786   // Lower (X & (1 << N)) == 0 to BT(X, N).
10787   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10788   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10789   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10790       Op1.getOpcode() == ISD::Constant &&
10791       cast<ConstantSDNode>(Op1)->isNullValue() &&
10792       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10793     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10794     if (NewSetCC.getNode())
10795       return NewSetCC;
10796   }
10797
10798   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10799   // these.
10800   if (Op1.getOpcode() == ISD::Constant &&
10801       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10802        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10803       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10804
10805     // If the input is a setcc, then reuse the input setcc or use a new one with
10806     // the inverted condition.
10807     if (Op0.getOpcode() == X86ISD::SETCC) {
10808       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10809       bool Invert = (CC == ISD::SETNE) ^
10810         cast<ConstantSDNode>(Op1)->isNullValue();
10811       if (!Invert)
10812         return Op0;
10813
10814       CCode = X86::GetOppositeBranchCondition(CCode);
10815       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10816                                   DAG.getConstant(CCode, MVT::i8),
10817                                   Op0.getOperand(1));
10818       if (VT == MVT::i1)
10819         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10820       return SetCC;
10821     }
10822   }
10823   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10824       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10825       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10826
10827     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10828     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10829   }
10830
10831   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10832   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10833   if (X86CC == X86::COND_INVALID)
10834     return SDValue();
10835
10836   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10837   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10838   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10839                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10840   if (VT == MVT::i1)
10841     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10842   return SetCC;
10843 }
10844
10845 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10846 static bool isX86LogicalCmp(SDValue Op) {
10847   unsigned Opc = Op.getNode()->getOpcode();
10848   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10849       Opc == X86ISD::SAHF)
10850     return true;
10851   if (Op.getResNo() == 1 &&
10852       (Opc == X86ISD::ADD ||
10853        Opc == X86ISD::SUB ||
10854        Opc == X86ISD::ADC ||
10855        Opc == X86ISD::SBB ||
10856        Opc == X86ISD::SMUL ||
10857        Opc == X86ISD::UMUL ||
10858        Opc == X86ISD::INC ||
10859        Opc == X86ISD::DEC ||
10860        Opc == X86ISD::OR ||
10861        Opc == X86ISD::XOR ||
10862        Opc == X86ISD::AND))
10863     return true;
10864
10865   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10866     return true;
10867
10868   return false;
10869 }
10870
10871 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10872   if (V.getOpcode() != ISD::TRUNCATE)
10873     return false;
10874
10875   SDValue VOp0 = V.getOperand(0);
10876   unsigned InBits = VOp0.getValueSizeInBits();
10877   unsigned Bits = V.getValueSizeInBits();
10878   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10879 }
10880
10881 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10882   bool addTest = true;
10883   SDValue Cond  = Op.getOperand(0);
10884   SDValue Op1 = Op.getOperand(1);
10885   SDValue Op2 = Op.getOperand(2);
10886   SDLoc DL(Op);
10887   EVT VT = Op1.getValueType();
10888   SDValue CC;
10889
10890   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10891   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10892   // sequence later on.
10893   if (Cond.getOpcode() == ISD::SETCC &&
10894       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10895        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10896       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10897     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10898     int SSECC = translateX86FSETCC(
10899         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10900
10901     if (SSECC != 8) {
10902       if (Subtarget->hasAVX512()) {
10903         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10904                                   DAG.getConstant(SSECC, MVT::i8));
10905         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10906       }
10907       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10908                                 DAG.getConstant(SSECC, MVT::i8));
10909       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10910       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10911       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10912     }
10913   }
10914
10915   if (Cond.getOpcode() == ISD::SETCC) {
10916     SDValue NewCond = LowerSETCC(Cond, DAG);
10917     if (NewCond.getNode())
10918       Cond = NewCond;
10919   }
10920
10921   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10922   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10923   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10924   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10925   if (Cond.getOpcode() == X86ISD::SETCC &&
10926       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10927       isZero(Cond.getOperand(1).getOperand(1))) {
10928     SDValue Cmp = Cond.getOperand(1);
10929
10930     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10931
10932     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10933         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10934       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10935
10936       SDValue CmpOp0 = Cmp.getOperand(0);
10937       // Apply further optimizations for special cases
10938       // (select (x != 0), -1, 0) -> neg & sbb
10939       // (select (x == 0), 0, -1) -> neg & sbb
10940       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10941         if (YC->isNullValue() &&
10942             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10943           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10944           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10945                                     DAG.getConstant(0, CmpOp0.getValueType()),
10946                                     CmpOp0);
10947           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10948                                     DAG.getConstant(X86::COND_B, MVT::i8),
10949                                     SDValue(Neg.getNode(), 1));
10950           return Res;
10951         }
10952
10953       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10954                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10955       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10956
10957       SDValue Res =   // Res = 0 or -1.
10958         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10959                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10960
10961       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10962         Res = DAG.getNOT(DL, Res, Res.getValueType());
10963
10964       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10965       if (!N2C || !N2C->isNullValue())
10966         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10967       return Res;
10968     }
10969   }
10970
10971   // Look past (and (setcc_carry (cmp ...)), 1).
10972   if (Cond.getOpcode() == ISD::AND &&
10973       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10974     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10975     if (C && C->getAPIntValue() == 1)
10976       Cond = Cond.getOperand(0);
10977   }
10978
10979   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10980   // setting operand in place of the X86ISD::SETCC.
10981   unsigned CondOpcode = Cond.getOpcode();
10982   if (CondOpcode == X86ISD::SETCC ||
10983       CondOpcode == X86ISD::SETCC_CARRY) {
10984     CC = Cond.getOperand(0);
10985
10986     SDValue Cmp = Cond.getOperand(1);
10987     unsigned Opc = Cmp.getOpcode();
10988     MVT VT = Op.getSimpleValueType();
10989
10990     bool IllegalFPCMov = false;
10991     if (VT.isFloatingPoint() && !VT.isVector() &&
10992         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10993       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10994
10995     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10996         Opc == X86ISD::BT) { // FIXME
10997       Cond = Cmp;
10998       addTest = false;
10999     }
11000   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11001              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11002              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11003               Cond.getOperand(0).getValueType() != MVT::i8)) {
11004     SDValue LHS = Cond.getOperand(0);
11005     SDValue RHS = Cond.getOperand(1);
11006     unsigned X86Opcode;
11007     unsigned X86Cond;
11008     SDVTList VTs;
11009     switch (CondOpcode) {
11010     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11011     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11012     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11013     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11014     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11015     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11016     default: llvm_unreachable("unexpected overflowing operator");
11017     }
11018     if (CondOpcode == ISD::UMULO)
11019       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11020                           MVT::i32);
11021     else
11022       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11023
11024     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11025
11026     if (CondOpcode == ISD::UMULO)
11027       Cond = X86Op.getValue(2);
11028     else
11029       Cond = X86Op.getValue(1);
11030
11031     CC = DAG.getConstant(X86Cond, MVT::i8);
11032     addTest = false;
11033   }
11034
11035   if (addTest) {
11036     // Look pass the truncate if the high bits are known zero.
11037     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11038         Cond = Cond.getOperand(0);
11039
11040     // We know the result of AND is compared against zero. Try to match
11041     // it to BT.
11042     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11043       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11044       if (NewSetCC.getNode()) {
11045         CC = NewSetCC.getOperand(0);
11046         Cond = NewSetCC.getOperand(1);
11047         addTest = false;
11048       }
11049     }
11050   }
11051
11052   if (addTest) {
11053     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11054     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11055   }
11056
11057   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11058   // a <  b ?  0 : -1 -> RES = setcc_carry
11059   // a >= b ? -1 :  0 -> RES = setcc_carry
11060   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11061   if (Cond.getOpcode() == X86ISD::SUB) {
11062     Cond = ConvertCmpIfNecessary(Cond, DAG);
11063     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11064
11065     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11066         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11067       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11068                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11069       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11070         return DAG.getNOT(DL, Res, Res.getValueType());
11071       return Res;
11072     }
11073   }
11074
11075   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11076   // widen the cmov and push the truncate through. This avoids introducing a new
11077   // branch during isel and doesn't add any extensions.
11078   if (Op.getValueType() == MVT::i8 &&
11079       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11080     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11081     if (T1.getValueType() == T2.getValueType() &&
11082         // Blacklist CopyFromReg to avoid partial register stalls.
11083         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11084       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11085       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11086       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11087     }
11088   }
11089
11090   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11091   // condition is true.
11092   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11093   SDValue Ops[] = { Op2, Op1, CC, Cond };
11094   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11095 }
11096
11097 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11098   MVT VT = Op->getSimpleValueType(0);
11099   SDValue In = Op->getOperand(0);
11100   MVT InVT = In.getSimpleValueType();
11101   SDLoc dl(Op);
11102
11103   unsigned int NumElts = VT.getVectorNumElements();
11104   if (NumElts != 8 && NumElts != 16)
11105     return SDValue();
11106
11107   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11108     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11109
11110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11111   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11112
11113   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11114   Constant *C = ConstantInt::get(*DAG.getContext(),
11115     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11116
11117   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11118   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11119   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11120                           MachinePointerInfo::getConstantPool(),
11121                           false, false, false, Alignment);
11122   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11123   if (VT.is512BitVector())
11124     return Brcst;
11125   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11126 }
11127
11128 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11129                                 SelectionDAG &DAG) {
11130   MVT VT = Op->getSimpleValueType(0);
11131   SDValue In = Op->getOperand(0);
11132   MVT InVT = In.getSimpleValueType();
11133   SDLoc dl(Op);
11134
11135   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11136     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11137
11138   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11139       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11140       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11141     return SDValue();
11142
11143   if (Subtarget->hasInt256())
11144     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11145
11146   // Optimize vectors in AVX mode
11147   // Sign extend  v8i16 to v8i32 and
11148   //              v4i32 to v4i64
11149   //
11150   // Divide input vector into two parts
11151   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11152   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11153   // concat the vectors to original VT
11154
11155   unsigned NumElems = InVT.getVectorNumElements();
11156   SDValue Undef = DAG.getUNDEF(InVT);
11157
11158   SmallVector<int,8> ShufMask1(NumElems, -1);
11159   for (unsigned i = 0; i != NumElems/2; ++i)
11160     ShufMask1[i] = i;
11161
11162   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11163
11164   SmallVector<int,8> ShufMask2(NumElems, -1);
11165   for (unsigned i = 0; i != NumElems/2; ++i)
11166     ShufMask2[i] = i + NumElems/2;
11167
11168   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11169
11170   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11171                                 VT.getVectorNumElements()/2);
11172
11173   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11174   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11175
11176   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11177 }
11178
11179 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11180 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11181 // from the AND / OR.
11182 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11183   Opc = Op.getOpcode();
11184   if (Opc != ISD::OR && Opc != ISD::AND)
11185     return false;
11186   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11187           Op.getOperand(0).hasOneUse() &&
11188           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11189           Op.getOperand(1).hasOneUse());
11190 }
11191
11192 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11193 // 1 and that the SETCC node has a single use.
11194 static bool isXor1OfSetCC(SDValue Op) {
11195   if (Op.getOpcode() != ISD::XOR)
11196     return false;
11197   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11198   if (N1C && N1C->getAPIntValue() == 1) {
11199     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11200       Op.getOperand(0).hasOneUse();
11201   }
11202   return false;
11203 }
11204
11205 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11206   bool addTest = true;
11207   SDValue Chain = Op.getOperand(0);
11208   SDValue Cond  = Op.getOperand(1);
11209   SDValue Dest  = Op.getOperand(2);
11210   SDLoc dl(Op);
11211   SDValue CC;
11212   bool Inverted = false;
11213
11214   if (Cond.getOpcode() == ISD::SETCC) {
11215     // Check for setcc([su]{add,sub,mul}o == 0).
11216     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11217         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11218         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11219         Cond.getOperand(0).getResNo() == 1 &&
11220         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11221          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11222          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11223          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11224          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11225          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11226       Inverted = true;
11227       Cond = Cond.getOperand(0);
11228     } else {
11229       SDValue NewCond = LowerSETCC(Cond, DAG);
11230       if (NewCond.getNode())
11231         Cond = NewCond;
11232     }
11233   }
11234 #if 0
11235   // FIXME: LowerXALUO doesn't handle these!!
11236   else if (Cond.getOpcode() == X86ISD::ADD  ||
11237            Cond.getOpcode() == X86ISD::SUB  ||
11238            Cond.getOpcode() == X86ISD::SMUL ||
11239            Cond.getOpcode() == X86ISD::UMUL)
11240     Cond = LowerXALUO(Cond, DAG);
11241 #endif
11242
11243   // Look pass (and (setcc_carry (cmp ...)), 1).
11244   if (Cond.getOpcode() == ISD::AND &&
11245       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11246     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11247     if (C && C->getAPIntValue() == 1)
11248       Cond = Cond.getOperand(0);
11249   }
11250
11251   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11252   // setting operand in place of the X86ISD::SETCC.
11253   unsigned CondOpcode = Cond.getOpcode();
11254   if (CondOpcode == X86ISD::SETCC ||
11255       CondOpcode == X86ISD::SETCC_CARRY) {
11256     CC = Cond.getOperand(0);
11257
11258     SDValue Cmp = Cond.getOperand(1);
11259     unsigned Opc = Cmp.getOpcode();
11260     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11261     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11262       Cond = Cmp;
11263       addTest = false;
11264     } else {
11265       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11266       default: break;
11267       case X86::COND_O:
11268       case X86::COND_B:
11269         // These can only come from an arithmetic instruction with overflow,
11270         // e.g. SADDO, UADDO.
11271         Cond = Cond.getNode()->getOperand(1);
11272         addTest = false;
11273         break;
11274       }
11275     }
11276   }
11277   CondOpcode = Cond.getOpcode();
11278   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11279       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11280       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11281        Cond.getOperand(0).getValueType() != MVT::i8)) {
11282     SDValue LHS = Cond.getOperand(0);
11283     SDValue RHS = Cond.getOperand(1);
11284     unsigned X86Opcode;
11285     unsigned X86Cond;
11286     SDVTList VTs;
11287     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11288     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11289     // X86ISD::INC).
11290     switch (CondOpcode) {
11291     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11292     case ISD::SADDO:
11293       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11294         if (C->isOne()) {
11295           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11296           break;
11297         }
11298       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11299     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11300     case ISD::SSUBO:
11301       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11302         if (C->isOne()) {
11303           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11304           break;
11305         }
11306       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11307     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11308     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11309     default: llvm_unreachable("unexpected overflowing operator");
11310     }
11311     if (Inverted)
11312       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11313     if (CondOpcode == ISD::UMULO)
11314       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11315                           MVT::i32);
11316     else
11317       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11318
11319     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11320
11321     if (CondOpcode == ISD::UMULO)
11322       Cond = X86Op.getValue(2);
11323     else
11324       Cond = X86Op.getValue(1);
11325
11326     CC = DAG.getConstant(X86Cond, MVT::i8);
11327     addTest = false;
11328   } else {
11329     unsigned CondOpc;
11330     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11331       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11332       if (CondOpc == ISD::OR) {
11333         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11334         // two branches instead of an explicit OR instruction with a
11335         // separate test.
11336         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11337             isX86LogicalCmp(Cmp)) {
11338           CC = Cond.getOperand(0).getOperand(0);
11339           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11340                               Chain, Dest, CC, Cmp);
11341           CC = Cond.getOperand(1).getOperand(0);
11342           Cond = Cmp;
11343           addTest = false;
11344         }
11345       } else { // ISD::AND
11346         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11347         // two branches instead of an explicit AND instruction with a
11348         // separate test. However, we only do this if this block doesn't
11349         // have a fall-through edge, because this requires an explicit
11350         // jmp when the condition is false.
11351         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11352             isX86LogicalCmp(Cmp) &&
11353             Op.getNode()->hasOneUse()) {
11354           X86::CondCode CCode =
11355             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11356           CCode = X86::GetOppositeBranchCondition(CCode);
11357           CC = DAG.getConstant(CCode, MVT::i8);
11358           SDNode *User = *Op.getNode()->use_begin();
11359           // Look for an unconditional branch following this conditional branch.
11360           // We need this because we need to reverse the successors in order
11361           // to implement FCMP_OEQ.
11362           if (User->getOpcode() == ISD::BR) {
11363             SDValue FalseBB = User->getOperand(1);
11364             SDNode *NewBR =
11365               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11366             assert(NewBR == User);
11367             (void)NewBR;
11368             Dest = FalseBB;
11369
11370             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11371                                 Chain, Dest, CC, Cmp);
11372             X86::CondCode CCode =
11373               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11374             CCode = X86::GetOppositeBranchCondition(CCode);
11375             CC = DAG.getConstant(CCode, MVT::i8);
11376             Cond = Cmp;
11377             addTest = false;
11378           }
11379         }
11380       }
11381     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11382       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11383       // It should be transformed during dag combiner except when the condition
11384       // is set by a arithmetics with overflow node.
11385       X86::CondCode CCode =
11386         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11387       CCode = X86::GetOppositeBranchCondition(CCode);
11388       CC = DAG.getConstant(CCode, MVT::i8);
11389       Cond = Cond.getOperand(0).getOperand(1);
11390       addTest = false;
11391     } else if (Cond.getOpcode() == ISD::SETCC &&
11392                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11393       // For FCMP_OEQ, we can emit
11394       // two branches instead of an explicit AND instruction with a
11395       // separate test. However, we only do this if this block doesn't
11396       // have a fall-through edge, because this requires an explicit
11397       // jmp when the condition is false.
11398       if (Op.getNode()->hasOneUse()) {
11399         SDNode *User = *Op.getNode()->use_begin();
11400         // Look for an unconditional branch following this conditional branch.
11401         // We need this because we need to reverse the successors in order
11402         // to implement FCMP_OEQ.
11403         if (User->getOpcode() == ISD::BR) {
11404           SDValue FalseBB = User->getOperand(1);
11405           SDNode *NewBR =
11406             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11407           assert(NewBR == User);
11408           (void)NewBR;
11409           Dest = FalseBB;
11410
11411           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11412                                     Cond.getOperand(0), Cond.getOperand(1));
11413           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11414           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11415           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11416                               Chain, Dest, CC, Cmp);
11417           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11418           Cond = Cmp;
11419           addTest = false;
11420         }
11421       }
11422     } else if (Cond.getOpcode() == ISD::SETCC &&
11423                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11424       // For FCMP_UNE, we can emit
11425       // two branches instead of an explicit AND instruction with a
11426       // separate test. However, we only do this if this block doesn't
11427       // have a fall-through edge, because this requires an explicit
11428       // jmp when the condition is false.
11429       if (Op.getNode()->hasOneUse()) {
11430         SDNode *User = *Op.getNode()->use_begin();
11431         // Look for an unconditional branch following this conditional branch.
11432         // We need this because we need to reverse the successors in order
11433         // to implement FCMP_UNE.
11434         if (User->getOpcode() == ISD::BR) {
11435           SDValue FalseBB = User->getOperand(1);
11436           SDNode *NewBR =
11437             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11438           assert(NewBR == User);
11439           (void)NewBR;
11440
11441           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11442                                     Cond.getOperand(0), Cond.getOperand(1));
11443           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11444           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11445           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11446                               Chain, Dest, CC, Cmp);
11447           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11448           Cond = Cmp;
11449           addTest = false;
11450           Dest = FalseBB;
11451         }
11452       }
11453     }
11454   }
11455
11456   if (addTest) {
11457     // Look pass the truncate if the high bits are known zero.
11458     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11459         Cond = Cond.getOperand(0);
11460
11461     // We know the result of AND is compared against zero. Try to match
11462     // it to BT.
11463     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11464       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11465       if (NewSetCC.getNode()) {
11466         CC = NewSetCC.getOperand(0);
11467         Cond = NewSetCC.getOperand(1);
11468         addTest = false;
11469       }
11470     }
11471   }
11472
11473   if (addTest) {
11474     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11475     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11476   }
11477   Cond = ConvertCmpIfNecessary(Cond, DAG);
11478   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11479                      Chain, Dest, CC, Cond);
11480 }
11481
11482 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11483 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11484 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11485 // that the guard pages used by the OS virtual memory manager are allocated in
11486 // correct sequence.
11487 SDValue
11488 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11489                                            SelectionDAG &DAG) const {
11490   MachineFunction &MF = DAG.getMachineFunction();
11491   bool SplitStack = MF.shouldSplitStack();
11492   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11493                SplitStack;
11494   SDLoc dl(Op);
11495
11496   if (!Lower) {
11497     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11498     SDNode* Node = Op.getNode();
11499
11500     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11501     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11502         " not tell us which reg is the stack pointer!");
11503     EVT VT = Node->getValueType(0);
11504     SDValue Tmp1 = SDValue(Node, 0);
11505     SDValue Tmp2 = SDValue(Node, 1);
11506     SDValue Tmp3 = Node->getOperand(2);
11507     SDValue Chain = Tmp1.getOperand(0);
11508
11509     // Chain the dynamic stack allocation so that it doesn't modify the stack
11510     // pointer when other instructions are using the stack.
11511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11512         SDLoc(Node));
11513
11514     SDValue Size = Tmp2.getOperand(1);
11515     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11516     Chain = SP.getValue(1);
11517     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11518     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11519     unsigned StackAlign = TFI.getStackAlignment();
11520     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11521     if (Align > StackAlign)
11522       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11523           DAG.getConstant(-(uint64_t)Align, VT));
11524     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11525
11526     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11527         DAG.getIntPtrConstant(0, true), SDValue(),
11528         SDLoc(Node));
11529
11530     SDValue Ops[2] = { Tmp1, Tmp2 };
11531     return DAG.getMergeValues(Ops, dl);
11532   }
11533
11534   // Get the inputs.
11535   SDValue Chain = Op.getOperand(0);
11536   SDValue Size  = Op.getOperand(1);
11537   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11538   EVT VT = Op.getNode()->getValueType(0);
11539
11540   bool Is64Bit = Subtarget->is64Bit();
11541   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11542
11543   if (SplitStack) {
11544     MachineRegisterInfo &MRI = MF.getRegInfo();
11545
11546     if (Is64Bit) {
11547       // The 64 bit implementation of segmented stacks needs to clobber both r10
11548       // r11. This makes it impossible to use it along with nested parameters.
11549       const Function *F = MF.getFunction();
11550
11551       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11552            I != E; ++I)
11553         if (I->hasNestAttr())
11554           report_fatal_error("Cannot use segmented stacks with functions that "
11555                              "have nested arguments.");
11556     }
11557
11558     const TargetRegisterClass *AddrRegClass =
11559       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11560     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11561     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11562     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11563                                 DAG.getRegister(Vreg, SPTy));
11564     SDValue Ops1[2] = { Value, Chain };
11565     return DAG.getMergeValues(Ops1, dl);
11566   } else {
11567     SDValue Flag;
11568     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11569
11570     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11571     Flag = Chain.getValue(1);
11572     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11573
11574     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11575
11576     const X86RegisterInfo *RegInfo =
11577       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11578     unsigned SPReg = RegInfo->getStackRegister();
11579     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11580     Chain = SP.getValue(1);
11581
11582     if (Align) {
11583       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11584                        DAG.getConstant(-(uint64_t)Align, VT));
11585       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11586     }
11587
11588     SDValue Ops1[2] = { SP, Chain };
11589     return DAG.getMergeValues(Ops1, dl);
11590   }
11591 }
11592
11593 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11594   MachineFunction &MF = DAG.getMachineFunction();
11595   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11596
11597   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11598   SDLoc DL(Op);
11599
11600   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11601     // vastart just stores the address of the VarArgsFrameIndex slot into the
11602     // memory location argument.
11603     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11604                                    getPointerTy());
11605     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11606                         MachinePointerInfo(SV), false, false, 0);
11607   }
11608
11609   // __va_list_tag:
11610   //   gp_offset         (0 - 6 * 8)
11611   //   fp_offset         (48 - 48 + 8 * 16)
11612   //   overflow_arg_area (point to parameters coming in memory).
11613   //   reg_save_area
11614   SmallVector<SDValue, 8> MemOps;
11615   SDValue FIN = Op.getOperand(1);
11616   // Store gp_offset
11617   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11618                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11619                                                MVT::i32),
11620                                FIN, MachinePointerInfo(SV), false, false, 0);
11621   MemOps.push_back(Store);
11622
11623   // Store fp_offset
11624   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11625                     FIN, DAG.getIntPtrConstant(4));
11626   Store = DAG.getStore(Op.getOperand(0), DL,
11627                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11628                                        MVT::i32),
11629                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11630   MemOps.push_back(Store);
11631
11632   // Store ptr to overflow_arg_area
11633   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11634                     FIN, DAG.getIntPtrConstant(4));
11635   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11636                                     getPointerTy());
11637   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11638                        MachinePointerInfo(SV, 8),
11639                        false, false, 0);
11640   MemOps.push_back(Store);
11641
11642   // Store ptr to reg_save_area.
11643   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11644                     FIN, DAG.getIntPtrConstant(8));
11645   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11646                                     getPointerTy());
11647   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11648                        MachinePointerInfo(SV, 16), false, false, 0);
11649   MemOps.push_back(Store);
11650   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11651 }
11652
11653 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11654   assert(Subtarget->is64Bit() &&
11655          "LowerVAARG only handles 64-bit va_arg!");
11656   assert((Subtarget->isTargetLinux() ||
11657           Subtarget->isTargetDarwin()) &&
11658           "Unhandled target in LowerVAARG");
11659   assert(Op.getNode()->getNumOperands() == 4);
11660   SDValue Chain = Op.getOperand(0);
11661   SDValue SrcPtr = Op.getOperand(1);
11662   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11663   unsigned Align = Op.getConstantOperandVal(3);
11664   SDLoc dl(Op);
11665
11666   EVT ArgVT = Op.getNode()->getValueType(0);
11667   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11668   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11669   uint8_t ArgMode;
11670
11671   // Decide which area this value should be read from.
11672   // TODO: Implement the AMD64 ABI in its entirety. This simple
11673   // selection mechanism works only for the basic types.
11674   if (ArgVT == MVT::f80) {
11675     llvm_unreachable("va_arg for f80 not yet implemented");
11676   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11677     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11678   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11679     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11680   } else {
11681     llvm_unreachable("Unhandled argument type in LowerVAARG");
11682   }
11683
11684   if (ArgMode == 2) {
11685     // Sanity Check: Make sure using fp_offset makes sense.
11686     assert(!getTargetMachine().Options.UseSoftFloat &&
11687            !(DAG.getMachineFunction()
11688                 .getFunction()->getAttributes()
11689                 .hasAttribute(AttributeSet::FunctionIndex,
11690                               Attribute::NoImplicitFloat)) &&
11691            Subtarget->hasSSE1());
11692   }
11693
11694   // Insert VAARG_64 node into the DAG
11695   // VAARG_64 returns two values: Variable Argument Address, Chain
11696   SmallVector<SDValue, 11> InstOps;
11697   InstOps.push_back(Chain);
11698   InstOps.push_back(SrcPtr);
11699   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11700   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11701   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11702   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11703   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11704                                           VTs, InstOps, MVT::i64,
11705                                           MachinePointerInfo(SV),
11706                                           /*Align=*/0,
11707                                           /*Volatile=*/false,
11708                                           /*ReadMem=*/true,
11709                                           /*WriteMem=*/true);
11710   Chain = VAARG.getValue(1);
11711
11712   // Load the next argument and return it
11713   return DAG.getLoad(ArgVT, dl,
11714                      Chain,
11715                      VAARG,
11716                      MachinePointerInfo(),
11717                      false, false, false, 0);
11718 }
11719
11720 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11721                            SelectionDAG &DAG) {
11722   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11723   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11724   SDValue Chain = Op.getOperand(0);
11725   SDValue DstPtr = Op.getOperand(1);
11726   SDValue SrcPtr = Op.getOperand(2);
11727   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11728   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11729   SDLoc DL(Op);
11730
11731   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11732                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11733                        false,
11734                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11735 }
11736
11737 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11738 // amount is a constant. Takes immediate version of shift as input.
11739 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11740                                           SDValue SrcOp, uint64_t ShiftAmt,
11741                                           SelectionDAG &DAG) {
11742   MVT ElementType = VT.getVectorElementType();
11743
11744   // Fold this packed shift into its first operand if ShiftAmt is 0.
11745   if (ShiftAmt == 0)
11746     return SrcOp;
11747
11748   // Check for ShiftAmt >= element width
11749   if (ShiftAmt >= ElementType.getSizeInBits()) {
11750     if (Opc == X86ISD::VSRAI)
11751       ShiftAmt = ElementType.getSizeInBits() - 1;
11752     else
11753       return DAG.getConstant(0, VT);
11754   }
11755
11756   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11757          && "Unknown target vector shift-by-constant node");
11758
11759   // Fold this packed vector shift into a build vector if SrcOp is a
11760   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11761   if (VT == SrcOp.getSimpleValueType() &&
11762       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11763     SmallVector<SDValue, 8> Elts;
11764     unsigned NumElts = SrcOp->getNumOperands();
11765     ConstantSDNode *ND;
11766
11767     switch(Opc) {
11768     default: llvm_unreachable(nullptr);
11769     case X86ISD::VSHLI:
11770       for (unsigned i=0; i!=NumElts; ++i) {
11771         SDValue CurrentOp = SrcOp->getOperand(i);
11772         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11773           Elts.push_back(CurrentOp);
11774           continue;
11775         }
11776         ND = cast<ConstantSDNode>(CurrentOp);
11777         const APInt &C = ND->getAPIntValue();
11778         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11779       }
11780       break;
11781     case X86ISD::VSRLI:
11782       for (unsigned i=0; i!=NumElts; ++i) {
11783         SDValue CurrentOp = SrcOp->getOperand(i);
11784         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11785           Elts.push_back(CurrentOp);
11786           continue;
11787         }
11788         ND = cast<ConstantSDNode>(CurrentOp);
11789         const APInt &C = ND->getAPIntValue();
11790         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11791       }
11792       break;
11793     case X86ISD::VSRAI:
11794       for (unsigned i=0; i!=NumElts; ++i) {
11795         SDValue CurrentOp = SrcOp->getOperand(i);
11796         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11797           Elts.push_back(CurrentOp);
11798           continue;
11799         }
11800         ND = cast<ConstantSDNode>(CurrentOp);
11801         const APInt &C = ND->getAPIntValue();
11802         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11803       }
11804       break;
11805     }
11806
11807     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11808   }
11809
11810   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11811 }
11812
11813 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11814 // may or may not be a constant. Takes immediate version of shift as input.
11815 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11816                                    SDValue SrcOp, SDValue ShAmt,
11817                                    SelectionDAG &DAG) {
11818   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11819
11820   // Catch shift-by-constant.
11821   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11822     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11823                                       CShAmt->getZExtValue(), DAG);
11824
11825   // Change opcode to non-immediate version
11826   switch (Opc) {
11827     default: llvm_unreachable("Unknown target vector shift node");
11828     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11829     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11830     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11831   }
11832
11833   // Need to build a vector containing shift amount
11834   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11835   SDValue ShOps[4];
11836   ShOps[0] = ShAmt;
11837   ShOps[1] = DAG.getConstant(0, MVT::i32);
11838   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11839   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11840
11841   // The return type has to be a 128-bit type with the same element
11842   // type as the input type.
11843   MVT EltVT = VT.getVectorElementType();
11844   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11845
11846   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11847   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11848 }
11849
11850 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11851   SDLoc dl(Op);
11852   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11853   switch (IntNo) {
11854   default: return SDValue();    // Don't custom lower most intrinsics.
11855   // Comparison intrinsics.
11856   case Intrinsic::x86_sse_comieq_ss:
11857   case Intrinsic::x86_sse_comilt_ss:
11858   case Intrinsic::x86_sse_comile_ss:
11859   case Intrinsic::x86_sse_comigt_ss:
11860   case Intrinsic::x86_sse_comige_ss:
11861   case Intrinsic::x86_sse_comineq_ss:
11862   case Intrinsic::x86_sse_ucomieq_ss:
11863   case Intrinsic::x86_sse_ucomilt_ss:
11864   case Intrinsic::x86_sse_ucomile_ss:
11865   case Intrinsic::x86_sse_ucomigt_ss:
11866   case Intrinsic::x86_sse_ucomige_ss:
11867   case Intrinsic::x86_sse_ucomineq_ss:
11868   case Intrinsic::x86_sse2_comieq_sd:
11869   case Intrinsic::x86_sse2_comilt_sd:
11870   case Intrinsic::x86_sse2_comile_sd:
11871   case Intrinsic::x86_sse2_comigt_sd:
11872   case Intrinsic::x86_sse2_comige_sd:
11873   case Intrinsic::x86_sse2_comineq_sd:
11874   case Intrinsic::x86_sse2_ucomieq_sd:
11875   case Intrinsic::x86_sse2_ucomilt_sd:
11876   case Intrinsic::x86_sse2_ucomile_sd:
11877   case Intrinsic::x86_sse2_ucomigt_sd:
11878   case Intrinsic::x86_sse2_ucomige_sd:
11879   case Intrinsic::x86_sse2_ucomineq_sd: {
11880     unsigned Opc;
11881     ISD::CondCode CC;
11882     switch (IntNo) {
11883     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11884     case Intrinsic::x86_sse_comieq_ss:
11885     case Intrinsic::x86_sse2_comieq_sd:
11886       Opc = X86ISD::COMI;
11887       CC = ISD::SETEQ;
11888       break;
11889     case Intrinsic::x86_sse_comilt_ss:
11890     case Intrinsic::x86_sse2_comilt_sd:
11891       Opc = X86ISD::COMI;
11892       CC = ISD::SETLT;
11893       break;
11894     case Intrinsic::x86_sse_comile_ss:
11895     case Intrinsic::x86_sse2_comile_sd:
11896       Opc = X86ISD::COMI;
11897       CC = ISD::SETLE;
11898       break;
11899     case Intrinsic::x86_sse_comigt_ss:
11900     case Intrinsic::x86_sse2_comigt_sd:
11901       Opc = X86ISD::COMI;
11902       CC = ISD::SETGT;
11903       break;
11904     case Intrinsic::x86_sse_comige_ss:
11905     case Intrinsic::x86_sse2_comige_sd:
11906       Opc = X86ISD::COMI;
11907       CC = ISD::SETGE;
11908       break;
11909     case Intrinsic::x86_sse_comineq_ss:
11910     case Intrinsic::x86_sse2_comineq_sd:
11911       Opc = X86ISD::COMI;
11912       CC = ISD::SETNE;
11913       break;
11914     case Intrinsic::x86_sse_ucomieq_ss:
11915     case Intrinsic::x86_sse2_ucomieq_sd:
11916       Opc = X86ISD::UCOMI;
11917       CC = ISD::SETEQ;
11918       break;
11919     case Intrinsic::x86_sse_ucomilt_ss:
11920     case Intrinsic::x86_sse2_ucomilt_sd:
11921       Opc = X86ISD::UCOMI;
11922       CC = ISD::SETLT;
11923       break;
11924     case Intrinsic::x86_sse_ucomile_ss:
11925     case Intrinsic::x86_sse2_ucomile_sd:
11926       Opc = X86ISD::UCOMI;
11927       CC = ISD::SETLE;
11928       break;
11929     case Intrinsic::x86_sse_ucomigt_ss:
11930     case Intrinsic::x86_sse2_ucomigt_sd:
11931       Opc = X86ISD::UCOMI;
11932       CC = ISD::SETGT;
11933       break;
11934     case Intrinsic::x86_sse_ucomige_ss:
11935     case Intrinsic::x86_sse2_ucomige_sd:
11936       Opc = X86ISD::UCOMI;
11937       CC = ISD::SETGE;
11938       break;
11939     case Intrinsic::x86_sse_ucomineq_ss:
11940     case Intrinsic::x86_sse2_ucomineq_sd:
11941       Opc = X86ISD::UCOMI;
11942       CC = ISD::SETNE;
11943       break;
11944     }
11945
11946     SDValue LHS = Op.getOperand(1);
11947     SDValue RHS = Op.getOperand(2);
11948     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11949     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11950     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11951     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11952                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11953     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11954   }
11955
11956   // Arithmetic intrinsics.
11957   case Intrinsic::x86_sse2_pmulu_dq:
11958   case Intrinsic::x86_avx2_pmulu_dq:
11959     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11960                        Op.getOperand(1), Op.getOperand(2));
11961
11962   case Intrinsic::x86_sse41_pmuldq:
11963   case Intrinsic::x86_avx2_pmul_dq:
11964     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11965                        Op.getOperand(1), Op.getOperand(2));
11966
11967   case Intrinsic::x86_sse2_pmulhu_w:
11968   case Intrinsic::x86_avx2_pmulhu_w:
11969     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11970                        Op.getOperand(1), Op.getOperand(2));
11971
11972   case Intrinsic::x86_sse2_pmulh_w:
11973   case Intrinsic::x86_avx2_pmulh_w:
11974     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11975                        Op.getOperand(1), Op.getOperand(2));
11976
11977   // SSE2/AVX2 sub with unsigned saturation intrinsics
11978   case Intrinsic::x86_sse2_psubus_b:
11979   case Intrinsic::x86_sse2_psubus_w:
11980   case Intrinsic::x86_avx2_psubus_b:
11981   case Intrinsic::x86_avx2_psubus_w:
11982     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11983                        Op.getOperand(1), Op.getOperand(2));
11984
11985   // SSE3/AVX horizontal add/sub intrinsics
11986   case Intrinsic::x86_sse3_hadd_ps:
11987   case Intrinsic::x86_sse3_hadd_pd:
11988   case Intrinsic::x86_avx_hadd_ps_256:
11989   case Intrinsic::x86_avx_hadd_pd_256:
11990   case Intrinsic::x86_sse3_hsub_ps:
11991   case Intrinsic::x86_sse3_hsub_pd:
11992   case Intrinsic::x86_avx_hsub_ps_256:
11993   case Intrinsic::x86_avx_hsub_pd_256:
11994   case Intrinsic::x86_ssse3_phadd_w_128:
11995   case Intrinsic::x86_ssse3_phadd_d_128:
11996   case Intrinsic::x86_avx2_phadd_w:
11997   case Intrinsic::x86_avx2_phadd_d:
11998   case Intrinsic::x86_ssse3_phsub_w_128:
11999   case Intrinsic::x86_ssse3_phsub_d_128:
12000   case Intrinsic::x86_avx2_phsub_w:
12001   case Intrinsic::x86_avx2_phsub_d: {
12002     unsigned Opcode;
12003     switch (IntNo) {
12004     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12005     case Intrinsic::x86_sse3_hadd_ps:
12006     case Intrinsic::x86_sse3_hadd_pd:
12007     case Intrinsic::x86_avx_hadd_ps_256:
12008     case Intrinsic::x86_avx_hadd_pd_256:
12009       Opcode = X86ISD::FHADD;
12010       break;
12011     case Intrinsic::x86_sse3_hsub_ps:
12012     case Intrinsic::x86_sse3_hsub_pd:
12013     case Intrinsic::x86_avx_hsub_ps_256:
12014     case Intrinsic::x86_avx_hsub_pd_256:
12015       Opcode = X86ISD::FHSUB;
12016       break;
12017     case Intrinsic::x86_ssse3_phadd_w_128:
12018     case Intrinsic::x86_ssse3_phadd_d_128:
12019     case Intrinsic::x86_avx2_phadd_w:
12020     case Intrinsic::x86_avx2_phadd_d:
12021       Opcode = X86ISD::HADD;
12022       break;
12023     case Intrinsic::x86_ssse3_phsub_w_128:
12024     case Intrinsic::x86_ssse3_phsub_d_128:
12025     case Intrinsic::x86_avx2_phsub_w:
12026     case Intrinsic::x86_avx2_phsub_d:
12027       Opcode = X86ISD::HSUB;
12028       break;
12029     }
12030     return DAG.getNode(Opcode, dl, Op.getValueType(),
12031                        Op.getOperand(1), Op.getOperand(2));
12032   }
12033
12034   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12035   case Intrinsic::x86_sse2_pmaxu_b:
12036   case Intrinsic::x86_sse41_pmaxuw:
12037   case Intrinsic::x86_sse41_pmaxud:
12038   case Intrinsic::x86_avx2_pmaxu_b:
12039   case Intrinsic::x86_avx2_pmaxu_w:
12040   case Intrinsic::x86_avx2_pmaxu_d:
12041   case Intrinsic::x86_sse2_pminu_b:
12042   case Intrinsic::x86_sse41_pminuw:
12043   case Intrinsic::x86_sse41_pminud:
12044   case Intrinsic::x86_avx2_pminu_b:
12045   case Intrinsic::x86_avx2_pminu_w:
12046   case Intrinsic::x86_avx2_pminu_d:
12047   case Intrinsic::x86_sse41_pmaxsb:
12048   case Intrinsic::x86_sse2_pmaxs_w:
12049   case Intrinsic::x86_sse41_pmaxsd:
12050   case Intrinsic::x86_avx2_pmaxs_b:
12051   case Intrinsic::x86_avx2_pmaxs_w:
12052   case Intrinsic::x86_avx2_pmaxs_d:
12053   case Intrinsic::x86_sse41_pminsb:
12054   case Intrinsic::x86_sse2_pmins_w:
12055   case Intrinsic::x86_sse41_pminsd:
12056   case Intrinsic::x86_avx2_pmins_b:
12057   case Intrinsic::x86_avx2_pmins_w:
12058   case Intrinsic::x86_avx2_pmins_d: {
12059     unsigned Opcode;
12060     switch (IntNo) {
12061     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12062     case Intrinsic::x86_sse2_pmaxu_b:
12063     case Intrinsic::x86_sse41_pmaxuw:
12064     case Intrinsic::x86_sse41_pmaxud:
12065     case Intrinsic::x86_avx2_pmaxu_b:
12066     case Intrinsic::x86_avx2_pmaxu_w:
12067     case Intrinsic::x86_avx2_pmaxu_d:
12068       Opcode = X86ISD::UMAX;
12069       break;
12070     case Intrinsic::x86_sse2_pminu_b:
12071     case Intrinsic::x86_sse41_pminuw:
12072     case Intrinsic::x86_sse41_pminud:
12073     case Intrinsic::x86_avx2_pminu_b:
12074     case Intrinsic::x86_avx2_pminu_w:
12075     case Intrinsic::x86_avx2_pminu_d:
12076       Opcode = X86ISD::UMIN;
12077       break;
12078     case Intrinsic::x86_sse41_pmaxsb:
12079     case Intrinsic::x86_sse2_pmaxs_w:
12080     case Intrinsic::x86_sse41_pmaxsd:
12081     case Intrinsic::x86_avx2_pmaxs_b:
12082     case Intrinsic::x86_avx2_pmaxs_w:
12083     case Intrinsic::x86_avx2_pmaxs_d:
12084       Opcode = X86ISD::SMAX;
12085       break;
12086     case Intrinsic::x86_sse41_pminsb:
12087     case Intrinsic::x86_sse2_pmins_w:
12088     case Intrinsic::x86_sse41_pminsd:
12089     case Intrinsic::x86_avx2_pmins_b:
12090     case Intrinsic::x86_avx2_pmins_w:
12091     case Intrinsic::x86_avx2_pmins_d:
12092       Opcode = X86ISD::SMIN;
12093       break;
12094     }
12095     return DAG.getNode(Opcode, dl, Op.getValueType(),
12096                        Op.getOperand(1), Op.getOperand(2));
12097   }
12098
12099   // SSE/SSE2/AVX floating point max/min intrinsics.
12100   case Intrinsic::x86_sse_max_ps:
12101   case Intrinsic::x86_sse2_max_pd:
12102   case Intrinsic::x86_avx_max_ps_256:
12103   case Intrinsic::x86_avx_max_pd_256:
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     unsigned Opcode;
12109     switch (IntNo) {
12110     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12111     case Intrinsic::x86_sse_max_ps:
12112     case Intrinsic::x86_sse2_max_pd:
12113     case Intrinsic::x86_avx_max_ps_256:
12114     case Intrinsic::x86_avx_max_pd_256:
12115       Opcode = X86ISD::FMAX;
12116       break;
12117     case Intrinsic::x86_sse_min_ps:
12118     case Intrinsic::x86_sse2_min_pd:
12119     case Intrinsic::x86_avx_min_ps_256:
12120     case Intrinsic::x86_avx_min_pd_256:
12121       Opcode = X86ISD::FMIN;
12122       break;
12123     }
12124     return DAG.getNode(Opcode, dl, Op.getValueType(),
12125                        Op.getOperand(1), Op.getOperand(2));
12126   }
12127
12128   // AVX2 variable shift intrinsics
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   case Intrinsic::x86_avx2_psrlv_d:
12134   case Intrinsic::x86_avx2_psrlv_q:
12135   case Intrinsic::x86_avx2_psrlv_d_256:
12136   case Intrinsic::x86_avx2_psrlv_q_256:
12137   case Intrinsic::x86_avx2_psrav_d:
12138   case Intrinsic::x86_avx2_psrav_d_256: {
12139     unsigned Opcode;
12140     switch (IntNo) {
12141     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12142     case Intrinsic::x86_avx2_psllv_d:
12143     case Intrinsic::x86_avx2_psllv_q:
12144     case Intrinsic::x86_avx2_psllv_d_256:
12145     case Intrinsic::x86_avx2_psllv_q_256:
12146       Opcode = ISD::SHL;
12147       break;
12148     case Intrinsic::x86_avx2_psrlv_d:
12149     case Intrinsic::x86_avx2_psrlv_q:
12150     case Intrinsic::x86_avx2_psrlv_d_256:
12151     case Intrinsic::x86_avx2_psrlv_q_256:
12152       Opcode = ISD::SRL;
12153       break;
12154     case Intrinsic::x86_avx2_psrav_d:
12155     case Intrinsic::x86_avx2_psrav_d_256:
12156       Opcode = ISD::SRA;
12157       break;
12158     }
12159     return DAG.getNode(Opcode, dl, Op.getValueType(),
12160                        Op.getOperand(1), Op.getOperand(2));
12161   }
12162
12163   case Intrinsic::x86_ssse3_pshuf_b_128:
12164   case Intrinsic::x86_avx2_pshuf_b:
12165     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12166                        Op.getOperand(1), Op.getOperand(2));
12167
12168   case Intrinsic::x86_ssse3_psign_b_128:
12169   case Intrinsic::x86_ssse3_psign_w_128:
12170   case Intrinsic::x86_ssse3_psign_d_128:
12171   case Intrinsic::x86_avx2_psign_b:
12172   case Intrinsic::x86_avx2_psign_w:
12173   case Intrinsic::x86_avx2_psign_d:
12174     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12175                        Op.getOperand(1), Op.getOperand(2));
12176
12177   case Intrinsic::x86_sse41_insertps:
12178     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12179                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12180
12181   case Intrinsic::x86_avx_vperm2f128_ps_256:
12182   case Intrinsic::x86_avx_vperm2f128_pd_256:
12183   case Intrinsic::x86_avx_vperm2f128_si_256:
12184   case Intrinsic::x86_avx2_vperm2i128:
12185     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12186                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12187
12188   case Intrinsic::x86_avx2_permd:
12189   case Intrinsic::x86_avx2_permps:
12190     // Operands intentionally swapped. Mask is last operand to intrinsic,
12191     // but second operand for node/instruction.
12192     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12193                        Op.getOperand(2), Op.getOperand(1));
12194
12195   case Intrinsic::x86_sse_sqrt_ps:
12196   case Intrinsic::x86_sse2_sqrt_pd:
12197   case Intrinsic::x86_avx_sqrt_ps_256:
12198   case Intrinsic::x86_avx_sqrt_pd_256:
12199     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12200
12201   // ptest and testp intrinsics. The intrinsic these come from are designed to
12202   // return an integer value, not just an instruction so lower it to the ptest
12203   // or testp pattern and a setcc for the result.
12204   case Intrinsic::x86_sse41_ptestz:
12205   case Intrinsic::x86_sse41_ptestc:
12206   case Intrinsic::x86_sse41_ptestnzc:
12207   case Intrinsic::x86_avx_ptestz_256:
12208   case Intrinsic::x86_avx_ptestc_256:
12209   case Intrinsic::x86_avx_ptestnzc_256:
12210   case Intrinsic::x86_avx_vtestz_ps:
12211   case Intrinsic::x86_avx_vtestc_ps:
12212   case Intrinsic::x86_avx_vtestnzc_ps:
12213   case Intrinsic::x86_avx_vtestz_pd:
12214   case Intrinsic::x86_avx_vtestc_pd:
12215   case Intrinsic::x86_avx_vtestnzc_pd:
12216   case Intrinsic::x86_avx_vtestz_ps_256:
12217   case Intrinsic::x86_avx_vtestc_ps_256:
12218   case Intrinsic::x86_avx_vtestnzc_ps_256:
12219   case Intrinsic::x86_avx_vtestz_pd_256:
12220   case Intrinsic::x86_avx_vtestc_pd_256:
12221   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12222     bool IsTestPacked = false;
12223     unsigned X86CC;
12224     switch (IntNo) {
12225     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12226     case Intrinsic::x86_avx_vtestz_ps:
12227     case Intrinsic::x86_avx_vtestz_pd:
12228     case Intrinsic::x86_avx_vtestz_ps_256:
12229     case Intrinsic::x86_avx_vtestz_pd_256:
12230       IsTestPacked = true; // Fallthrough
12231     case Intrinsic::x86_sse41_ptestz:
12232     case Intrinsic::x86_avx_ptestz_256:
12233       // ZF = 1
12234       X86CC = X86::COND_E;
12235       break;
12236     case Intrinsic::x86_avx_vtestc_ps:
12237     case Intrinsic::x86_avx_vtestc_pd:
12238     case Intrinsic::x86_avx_vtestc_ps_256:
12239     case Intrinsic::x86_avx_vtestc_pd_256:
12240       IsTestPacked = true; // Fallthrough
12241     case Intrinsic::x86_sse41_ptestc:
12242     case Intrinsic::x86_avx_ptestc_256:
12243       // CF = 1
12244       X86CC = X86::COND_B;
12245       break;
12246     case Intrinsic::x86_avx_vtestnzc_ps:
12247     case Intrinsic::x86_avx_vtestnzc_pd:
12248     case Intrinsic::x86_avx_vtestnzc_ps_256:
12249     case Intrinsic::x86_avx_vtestnzc_pd_256:
12250       IsTestPacked = true; // Fallthrough
12251     case Intrinsic::x86_sse41_ptestnzc:
12252     case Intrinsic::x86_avx_ptestnzc_256:
12253       // ZF and CF = 0
12254       X86CC = X86::COND_A;
12255       break;
12256     }
12257
12258     SDValue LHS = Op.getOperand(1);
12259     SDValue RHS = Op.getOperand(2);
12260     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12261     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12262     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12263     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12264     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12265   }
12266   case Intrinsic::x86_avx512_kortestz_w:
12267   case Intrinsic::x86_avx512_kortestc_w: {
12268     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12269     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12270     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12271     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12272     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12273     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12274     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12275   }
12276
12277   // SSE/AVX shift intrinsics
12278   case Intrinsic::x86_sse2_psll_w:
12279   case Intrinsic::x86_sse2_psll_d:
12280   case Intrinsic::x86_sse2_psll_q:
12281   case Intrinsic::x86_avx2_psll_w:
12282   case Intrinsic::x86_avx2_psll_d:
12283   case Intrinsic::x86_avx2_psll_q:
12284   case Intrinsic::x86_sse2_psrl_w:
12285   case Intrinsic::x86_sse2_psrl_d:
12286   case Intrinsic::x86_sse2_psrl_q:
12287   case Intrinsic::x86_avx2_psrl_w:
12288   case Intrinsic::x86_avx2_psrl_d:
12289   case Intrinsic::x86_avx2_psrl_q:
12290   case Intrinsic::x86_sse2_psra_w:
12291   case Intrinsic::x86_sse2_psra_d:
12292   case Intrinsic::x86_avx2_psra_w:
12293   case Intrinsic::x86_avx2_psra_d: {
12294     unsigned Opcode;
12295     switch (IntNo) {
12296     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12297     case Intrinsic::x86_sse2_psll_w:
12298     case Intrinsic::x86_sse2_psll_d:
12299     case Intrinsic::x86_sse2_psll_q:
12300     case Intrinsic::x86_avx2_psll_w:
12301     case Intrinsic::x86_avx2_psll_d:
12302     case Intrinsic::x86_avx2_psll_q:
12303       Opcode = X86ISD::VSHL;
12304       break;
12305     case Intrinsic::x86_sse2_psrl_w:
12306     case Intrinsic::x86_sse2_psrl_d:
12307     case Intrinsic::x86_sse2_psrl_q:
12308     case Intrinsic::x86_avx2_psrl_w:
12309     case Intrinsic::x86_avx2_psrl_d:
12310     case Intrinsic::x86_avx2_psrl_q:
12311       Opcode = X86ISD::VSRL;
12312       break;
12313     case Intrinsic::x86_sse2_psra_w:
12314     case Intrinsic::x86_sse2_psra_d:
12315     case Intrinsic::x86_avx2_psra_w:
12316     case Intrinsic::x86_avx2_psra_d:
12317       Opcode = X86ISD::VSRA;
12318       break;
12319     }
12320     return DAG.getNode(Opcode, dl, Op.getValueType(),
12321                        Op.getOperand(1), Op.getOperand(2));
12322   }
12323
12324   // SSE/AVX immediate shift intrinsics
12325   case Intrinsic::x86_sse2_pslli_w:
12326   case Intrinsic::x86_sse2_pslli_d:
12327   case Intrinsic::x86_sse2_pslli_q:
12328   case Intrinsic::x86_avx2_pslli_w:
12329   case Intrinsic::x86_avx2_pslli_d:
12330   case Intrinsic::x86_avx2_pslli_q:
12331   case Intrinsic::x86_sse2_psrli_w:
12332   case Intrinsic::x86_sse2_psrli_d:
12333   case Intrinsic::x86_sse2_psrli_q:
12334   case Intrinsic::x86_avx2_psrli_w:
12335   case Intrinsic::x86_avx2_psrli_d:
12336   case Intrinsic::x86_avx2_psrli_q:
12337   case Intrinsic::x86_sse2_psrai_w:
12338   case Intrinsic::x86_sse2_psrai_d:
12339   case Intrinsic::x86_avx2_psrai_w:
12340   case Intrinsic::x86_avx2_psrai_d: {
12341     unsigned Opcode;
12342     switch (IntNo) {
12343     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12344     case Intrinsic::x86_sse2_pslli_w:
12345     case Intrinsic::x86_sse2_pslli_d:
12346     case Intrinsic::x86_sse2_pslli_q:
12347     case Intrinsic::x86_avx2_pslli_w:
12348     case Intrinsic::x86_avx2_pslli_d:
12349     case Intrinsic::x86_avx2_pslli_q:
12350       Opcode = X86ISD::VSHLI;
12351       break;
12352     case Intrinsic::x86_sse2_psrli_w:
12353     case Intrinsic::x86_sse2_psrli_d:
12354     case Intrinsic::x86_sse2_psrli_q:
12355     case Intrinsic::x86_avx2_psrli_w:
12356     case Intrinsic::x86_avx2_psrli_d:
12357     case Intrinsic::x86_avx2_psrli_q:
12358       Opcode = X86ISD::VSRLI;
12359       break;
12360     case Intrinsic::x86_sse2_psrai_w:
12361     case Intrinsic::x86_sse2_psrai_d:
12362     case Intrinsic::x86_avx2_psrai_w:
12363     case Intrinsic::x86_avx2_psrai_d:
12364       Opcode = X86ISD::VSRAI;
12365       break;
12366     }
12367     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12368                                Op.getOperand(1), Op.getOperand(2), DAG);
12369   }
12370
12371   case Intrinsic::x86_sse42_pcmpistria128:
12372   case Intrinsic::x86_sse42_pcmpestria128:
12373   case Intrinsic::x86_sse42_pcmpistric128:
12374   case Intrinsic::x86_sse42_pcmpestric128:
12375   case Intrinsic::x86_sse42_pcmpistrio128:
12376   case Intrinsic::x86_sse42_pcmpestrio128:
12377   case Intrinsic::x86_sse42_pcmpistris128:
12378   case Intrinsic::x86_sse42_pcmpestris128:
12379   case Intrinsic::x86_sse42_pcmpistriz128:
12380   case Intrinsic::x86_sse42_pcmpestriz128: {
12381     unsigned Opcode;
12382     unsigned X86CC;
12383     switch (IntNo) {
12384     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12385     case Intrinsic::x86_sse42_pcmpistria128:
12386       Opcode = X86ISD::PCMPISTRI;
12387       X86CC = X86::COND_A;
12388       break;
12389     case Intrinsic::x86_sse42_pcmpestria128:
12390       Opcode = X86ISD::PCMPESTRI;
12391       X86CC = X86::COND_A;
12392       break;
12393     case Intrinsic::x86_sse42_pcmpistric128:
12394       Opcode = X86ISD::PCMPISTRI;
12395       X86CC = X86::COND_B;
12396       break;
12397     case Intrinsic::x86_sse42_pcmpestric128:
12398       Opcode = X86ISD::PCMPESTRI;
12399       X86CC = X86::COND_B;
12400       break;
12401     case Intrinsic::x86_sse42_pcmpistrio128:
12402       Opcode = X86ISD::PCMPISTRI;
12403       X86CC = X86::COND_O;
12404       break;
12405     case Intrinsic::x86_sse42_pcmpestrio128:
12406       Opcode = X86ISD::PCMPESTRI;
12407       X86CC = X86::COND_O;
12408       break;
12409     case Intrinsic::x86_sse42_pcmpistris128:
12410       Opcode = X86ISD::PCMPISTRI;
12411       X86CC = X86::COND_S;
12412       break;
12413     case Intrinsic::x86_sse42_pcmpestris128:
12414       Opcode = X86ISD::PCMPESTRI;
12415       X86CC = X86::COND_S;
12416       break;
12417     case Intrinsic::x86_sse42_pcmpistriz128:
12418       Opcode = X86ISD::PCMPISTRI;
12419       X86CC = X86::COND_E;
12420       break;
12421     case Intrinsic::x86_sse42_pcmpestriz128:
12422       Opcode = X86ISD::PCMPESTRI;
12423       X86CC = X86::COND_E;
12424       break;
12425     }
12426     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12427     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12428     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12429     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12430                                 DAG.getConstant(X86CC, MVT::i8),
12431                                 SDValue(PCMP.getNode(), 1));
12432     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12433   }
12434
12435   case Intrinsic::x86_sse42_pcmpistri128:
12436   case Intrinsic::x86_sse42_pcmpestri128: {
12437     unsigned Opcode;
12438     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12439       Opcode = X86ISD::PCMPISTRI;
12440     else
12441       Opcode = X86ISD::PCMPESTRI;
12442
12443     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12444     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12445     return DAG.getNode(Opcode, dl, VTs, NewOps);
12446   }
12447   case Intrinsic::x86_fma_vfmadd_ps:
12448   case Intrinsic::x86_fma_vfmadd_pd:
12449   case Intrinsic::x86_fma_vfmsub_ps:
12450   case Intrinsic::x86_fma_vfmsub_pd:
12451   case Intrinsic::x86_fma_vfnmadd_ps:
12452   case Intrinsic::x86_fma_vfnmadd_pd:
12453   case Intrinsic::x86_fma_vfnmsub_ps:
12454   case Intrinsic::x86_fma_vfnmsub_pd:
12455   case Intrinsic::x86_fma_vfmaddsub_ps:
12456   case Intrinsic::x86_fma_vfmaddsub_pd:
12457   case Intrinsic::x86_fma_vfmsubadd_ps:
12458   case Intrinsic::x86_fma_vfmsubadd_pd:
12459   case Intrinsic::x86_fma_vfmadd_ps_256:
12460   case Intrinsic::x86_fma_vfmadd_pd_256:
12461   case Intrinsic::x86_fma_vfmsub_ps_256:
12462   case Intrinsic::x86_fma_vfmsub_pd_256:
12463   case Intrinsic::x86_fma_vfnmadd_ps_256:
12464   case Intrinsic::x86_fma_vfnmadd_pd_256:
12465   case Intrinsic::x86_fma_vfnmsub_ps_256:
12466   case Intrinsic::x86_fma_vfnmsub_pd_256:
12467   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12468   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12469   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12470   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12471   case Intrinsic::x86_fma_vfmadd_ps_512:
12472   case Intrinsic::x86_fma_vfmadd_pd_512:
12473   case Intrinsic::x86_fma_vfmsub_ps_512:
12474   case Intrinsic::x86_fma_vfmsub_pd_512:
12475   case Intrinsic::x86_fma_vfnmadd_ps_512:
12476   case Intrinsic::x86_fma_vfnmadd_pd_512:
12477   case Intrinsic::x86_fma_vfnmsub_ps_512:
12478   case Intrinsic::x86_fma_vfnmsub_pd_512:
12479   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12480   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12481   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12482   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12483     unsigned Opc;
12484     switch (IntNo) {
12485     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12486     case Intrinsic::x86_fma_vfmadd_ps:
12487     case Intrinsic::x86_fma_vfmadd_pd:
12488     case Intrinsic::x86_fma_vfmadd_ps_256:
12489     case Intrinsic::x86_fma_vfmadd_pd_256:
12490     case Intrinsic::x86_fma_vfmadd_ps_512:
12491     case Intrinsic::x86_fma_vfmadd_pd_512:
12492       Opc = X86ISD::FMADD;
12493       break;
12494     case Intrinsic::x86_fma_vfmsub_ps:
12495     case Intrinsic::x86_fma_vfmsub_pd:
12496     case Intrinsic::x86_fma_vfmsub_ps_256:
12497     case Intrinsic::x86_fma_vfmsub_pd_256:
12498     case Intrinsic::x86_fma_vfmsub_ps_512:
12499     case Intrinsic::x86_fma_vfmsub_pd_512:
12500       Opc = X86ISD::FMSUB;
12501       break;
12502     case Intrinsic::x86_fma_vfnmadd_ps:
12503     case Intrinsic::x86_fma_vfnmadd_pd:
12504     case Intrinsic::x86_fma_vfnmadd_ps_256:
12505     case Intrinsic::x86_fma_vfnmadd_pd_256:
12506     case Intrinsic::x86_fma_vfnmadd_ps_512:
12507     case Intrinsic::x86_fma_vfnmadd_pd_512:
12508       Opc = X86ISD::FNMADD;
12509       break;
12510     case Intrinsic::x86_fma_vfnmsub_ps:
12511     case Intrinsic::x86_fma_vfnmsub_pd:
12512     case Intrinsic::x86_fma_vfnmsub_ps_256:
12513     case Intrinsic::x86_fma_vfnmsub_pd_256:
12514     case Intrinsic::x86_fma_vfnmsub_ps_512:
12515     case Intrinsic::x86_fma_vfnmsub_pd_512:
12516       Opc = X86ISD::FNMSUB;
12517       break;
12518     case Intrinsic::x86_fma_vfmaddsub_ps:
12519     case Intrinsic::x86_fma_vfmaddsub_pd:
12520     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12521     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12522     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12523     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12524       Opc = X86ISD::FMADDSUB;
12525       break;
12526     case Intrinsic::x86_fma_vfmsubadd_ps:
12527     case Intrinsic::x86_fma_vfmsubadd_pd:
12528     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12529     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12530     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12531     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12532       Opc = X86ISD::FMSUBADD;
12533       break;
12534     }
12535
12536     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12537                        Op.getOperand(2), Op.getOperand(3));
12538   }
12539   }
12540 }
12541
12542 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12543                               SDValue Src, SDValue Mask, SDValue Base,
12544                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12545                               const X86Subtarget * Subtarget) {
12546   SDLoc dl(Op);
12547   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12548   assert(C && "Invalid scale type");
12549   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12550   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12551                              Index.getSimpleValueType().getVectorNumElements());
12552   SDValue MaskInReg;
12553   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12554   if (MaskC)
12555     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12556   else
12557     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12558   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12559   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12560   SDValue Segment = DAG.getRegister(0, MVT::i32);
12561   if (Src.getOpcode() == ISD::UNDEF)
12562     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12563   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12564   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12565   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12566   return DAG.getMergeValues(RetOps, dl);
12567 }
12568
12569 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12570                                SDValue Src, SDValue Mask, SDValue Base,
12571                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12572   SDLoc dl(Op);
12573   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12574   assert(C && "Invalid scale type");
12575   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12576   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12577   SDValue Segment = DAG.getRegister(0, MVT::i32);
12578   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12579                              Index.getSimpleValueType().getVectorNumElements());
12580   SDValue MaskInReg;
12581   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12582   if (MaskC)
12583     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12584   else
12585     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12586   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12587   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12588   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12589   return SDValue(Res, 1);
12590 }
12591
12592 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12593                                SDValue Mask, SDValue Base, SDValue Index,
12594                                SDValue ScaleOp, SDValue Chain) {
12595   SDLoc dl(Op);
12596   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12597   assert(C && "Invalid scale type");
12598   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12599   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12600   SDValue Segment = DAG.getRegister(0, MVT::i32);
12601   EVT MaskVT =
12602     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12603   SDValue MaskInReg;
12604   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12605   if (MaskC)
12606     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12607   else
12608     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12609   //SDVTList VTs = DAG.getVTList(MVT::Other);
12610   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12611   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12612   return SDValue(Res, 0);
12613 }
12614
12615 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12616 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12617 // also used to custom lower READCYCLECOUNTER nodes.
12618 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12619                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12620                               SmallVectorImpl<SDValue> &Results) {
12621   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12622   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12623   SDValue LO, HI;
12624
12625   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12626   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12627   // and the EAX register is loaded with the low-order 32 bits.
12628   if (Subtarget->is64Bit()) {
12629     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12630     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12631                             LO.getValue(2));
12632   } else {
12633     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12634     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12635                             LO.getValue(2));
12636   }
12637   SDValue Chain = HI.getValue(1);
12638
12639   if (Opcode == X86ISD::RDTSCP_DAG) {
12640     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12641
12642     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12643     // the ECX register. Add 'ecx' explicitly to the chain.
12644     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12645                                      HI.getValue(2));
12646     // Explicitly store the content of ECX at the location passed in input
12647     // to the 'rdtscp' intrinsic.
12648     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12649                          MachinePointerInfo(), false, false, 0);
12650   }
12651
12652   if (Subtarget->is64Bit()) {
12653     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12654     // the EAX register is loaded with the low-order 32 bits.
12655     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12656                               DAG.getConstant(32, MVT::i8));
12657     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12658     Results.push_back(Chain);
12659     return;
12660   }
12661
12662   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12663   SDValue Ops[] = { LO, HI };
12664   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12665   Results.push_back(Pair);
12666   Results.push_back(Chain);
12667 }
12668
12669 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12670                                      SelectionDAG &DAG) {
12671   SmallVector<SDValue, 2> Results;
12672   SDLoc DL(Op);
12673   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12674                           Results);
12675   return DAG.getMergeValues(Results, DL);
12676 }
12677
12678 enum IntrinsicType {
12679   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12680 };
12681
12682 struct IntrinsicData {
12683   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12684     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12685   IntrinsicType Type;
12686   unsigned      Opc0;
12687   unsigned      Opc1;
12688 };
12689
12690 std::map < unsigned, IntrinsicData> IntrMap;
12691 static void InitIntinsicsMap() {
12692   static bool Initialized = false;
12693   if (Initialized) 
12694     return;
12695   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12696                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12697   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12698                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12699   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12700                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12701   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12702                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12703   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12704                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12705   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12706                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12707   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12708                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12709   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12710                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12711   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12712                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12713
12714   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12715                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12716   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12717                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12718   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12719                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12720   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12721                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12722   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12723                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12724   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12725                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12726   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12727                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12728   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12729                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12730    
12731   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12732                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12733                                                         X86::VGATHERPF1QPSm)));
12734   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12735                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12736                                                         X86::VGATHERPF1QPDm)));
12737   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12738                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12739                                                         X86::VGATHERPF1DPDm)));
12740   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12741                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12742                                                         X86::VGATHERPF1DPSm)));
12743   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12744                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12745                                                         X86::VSCATTERPF1QPSm)));
12746   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12747                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12748                                                         X86::VSCATTERPF1QPDm)));
12749   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12750                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12751                                                         X86::VSCATTERPF1DPDm)));
12752   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12753                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12754                                                         X86::VSCATTERPF1DPSm)));
12755   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12756                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12757   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12758                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12759   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12760                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12761   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12762                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12763   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12764                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12765   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12766                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12767   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12768                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12769   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12770                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12771   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12772                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12773   Initialized = true;
12774 }
12775
12776 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12777                                       SelectionDAG &DAG) {
12778   InitIntinsicsMap();
12779   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12780   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12781   if (itr == IntrMap.end())
12782     return SDValue();
12783
12784   SDLoc dl(Op);
12785   IntrinsicData Intr = itr->second;
12786   switch(Intr.Type) {
12787   case RDSEED:
12788   case RDRAND: {
12789     // Emit the node with the right value type.
12790     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12791     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12792
12793     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12794     // Otherwise return the value from Rand, which is always 0, casted to i32.
12795     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12796                       DAG.getConstant(1, Op->getValueType(1)),
12797                       DAG.getConstant(X86::COND_B, MVT::i32),
12798                       SDValue(Result.getNode(), 1) };
12799     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12800                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12801                                   Ops);
12802
12803     // Return { result, isValid, chain }.
12804     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12805                        SDValue(Result.getNode(), 2));
12806   }
12807   case GATHER: {
12808   //gather(v1, mask, index, base, scale);
12809     SDValue Chain = Op.getOperand(0);
12810     SDValue Src   = Op.getOperand(2);
12811     SDValue Base  = Op.getOperand(3);
12812     SDValue Index = Op.getOperand(4);
12813     SDValue Mask  = Op.getOperand(5);
12814     SDValue Scale = Op.getOperand(6);
12815     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12816                           Subtarget);
12817   }
12818   case SCATTER: {
12819   //scatter(base, mask, index, v1, scale);
12820     SDValue Chain = Op.getOperand(0);
12821     SDValue Base  = Op.getOperand(2);
12822     SDValue Mask  = Op.getOperand(3);
12823     SDValue Index = Op.getOperand(4);
12824     SDValue Src   = Op.getOperand(5);
12825     SDValue Scale = Op.getOperand(6);
12826     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12827   }
12828   case PREFETCH: {
12829     SDValue Hint = Op.getOperand(6);
12830     unsigned HintVal;
12831     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12832         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12833       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12834     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12835     SDValue Chain = Op.getOperand(0);
12836     SDValue Mask  = Op.getOperand(2);
12837     SDValue Index = Op.getOperand(3);
12838     SDValue Base  = Op.getOperand(4);
12839     SDValue Scale = Op.getOperand(5);
12840     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12841   }
12842   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12843   case RDTSC: {
12844     SmallVector<SDValue, 2> Results;
12845     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12846     return DAG.getMergeValues(Results, dl);
12847   }
12848   // XTEST intrinsics.
12849   case XTEST: {
12850     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12851     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12852     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12853                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12854                                 InTrans);
12855     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12856     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12857                        Ret, SDValue(InTrans.getNode(), 1));
12858   }
12859   }
12860   llvm_unreachable("Unknown Intrinsic Type");
12861 }
12862
12863 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12864                                            SelectionDAG &DAG) const {
12865   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12866   MFI->setReturnAddressIsTaken(true);
12867
12868   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12869     return SDValue();
12870
12871   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12872   SDLoc dl(Op);
12873   EVT PtrVT = getPointerTy();
12874
12875   if (Depth > 0) {
12876     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12877     const X86RegisterInfo *RegInfo =
12878       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12879     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12880     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12881                        DAG.getNode(ISD::ADD, dl, PtrVT,
12882                                    FrameAddr, Offset),
12883                        MachinePointerInfo(), false, false, false, 0);
12884   }
12885
12886   // Just load the return address.
12887   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12888   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12889                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12890 }
12891
12892 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12893   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12894   MFI->setFrameAddressIsTaken(true);
12895
12896   EVT VT = Op.getValueType();
12897   SDLoc dl(Op);  // FIXME probably not meaningful
12898   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12899   const X86RegisterInfo *RegInfo =
12900     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12901   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12902   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12903           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12904          "Invalid Frame Register!");
12905   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12906   while (Depth--)
12907     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12908                             MachinePointerInfo(),
12909                             false, false, false, 0);
12910   return FrameAddr;
12911 }
12912
12913 // FIXME? Maybe this could be a TableGen attribute on some registers and
12914 // this table could be generated automatically from RegInfo.
12915 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12916                                               EVT VT) const {
12917   unsigned Reg = StringSwitch<unsigned>(RegName)
12918                        .Case("esp", X86::ESP)
12919                        .Case("rsp", X86::RSP)
12920                        .Default(0);
12921   if (Reg)
12922     return Reg;
12923   report_fatal_error("Invalid register name global variable");
12924 }
12925
12926 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12927                                                      SelectionDAG &DAG) const {
12928   const X86RegisterInfo *RegInfo =
12929     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12930   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12931 }
12932
12933 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12934   SDValue Chain     = Op.getOperand(0);
12935   SDValue Offset    = Op.getOperand(1);
12936   SDValue Handler   = Op.getOperand(2);
12937   SDLoc dl      (Op);
12938
12939   EVT PtrVT = getPointerTy();
12940   const X86RegisterInfo *RegInfo =
12941     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12942   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12943   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12944           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12945          "Invalid Frame Register!");
12946   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12947   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12948
12949   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12950                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12951   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12952   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12953                        false, false, 0);
12954   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12955
12956   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12957                      DAG.getRegister(StoreAddrReg, PtrVT));
12958 }
12959
12960 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12961                                                SelectionDAG &DAG) const {
12962   SDLoc DL(Op);
12963   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12964                      DAG.getVTList(MVT::i32, MVT::Other),
12965                      Op.getOperand(0), Op.getOperand(1));
12966 }
12967
12968 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12969                                                 SelectionDAG &DAG) const {
12970   SDLoc DL(Op);
12971   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12972                      Op.getOperand(0), Op.getOperand(1));
12973 }
12974
12975 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12976   return Op.getOperand(0);
12977 }
12978
12979 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12980                                                 SelectionDAG &DAG) const {
12981   SDValue Root = Op.getOperand(0);
12982   SDValue Trmp = Op.getOperand(1); // trampoline
12983   SDValue FPtr = Op.getOperand(2); // nested function
12984   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12985   SDLoc dl (Op);
12986
12987   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12988   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12989
12990   if (Subtarget->is64Bit()) {
12991     SDValue OutChains[6];
12992
12993     // Large code-model.
12994     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12995     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12996
12997     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12998     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12999
13000     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13001
13002     // Load the pointer to the nested function into R11.
13003     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13004     SDValue Addr = Trmp;
13005     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13006                                 Addr, MachinePointerInfo(TrmpAddr),
13007                                 false, false, 0);
13008
13009     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13010                        DAG.getConstant(2, MVT::i64));
13011     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13012                                 MachinePointerInfo(TrmpAddr, 2),
13013                                 false, false, 2);
13014
13015     // Load the 'nest' parameter value into R10.
13016     // R10 is specified in X86CallingConv.td
13017     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13018     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13019                        DAG.getConstant(10, MVT::i64));
13020     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13021                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13022                                 false, false, 0);
13023
13024     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13025                        DAG.getConstant(12, MVT::i64));
13026     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13027                                 MachinePointerInfo(TrmpAddr, 12),
13028                                 false, false, 2);
13029
13030     // Jump to the nested function.
13031     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13032     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13033                        DAG.getConstant(20, MVT::i64));
13034     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13035                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13036                                 false, false, 0);
13037
13038     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13040                        DAG.getConstant(22, MVT::i64));
13041     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13042                                 MachinePointerInfo(TrmpAddr, 22),
13043                                 false, false, 0);
13044
13045     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13046   } else {
13047     const Function *Func =
13048       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13049     CallingConv::ID CC = Func->getCallingConv();
13050     unsigned NestReg;
13051
13052     switch (CC) {
13053     default:
13054       llvm_unreachable("Unsupported calling convention");
13055     case CallingConv::C:
13056     case CallingConv::X86_StdCall: {
13057       // Pass 'nest' parameter in ECX.
13058       // Must be kept in sync with X86CallingConv.td
13059       NestReg = X86::ECX;
13060
13061       // Check that ECX wasn't needed by an 'inreg' parameter.
13062       FunctionType *FTy = Func->getFunctionType();
13063       const AttributeSet &Attrs = Func->getAttributes();
13064
13065       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13066         unsigned InRegCount = 0;
13067         unsigned Idx = 1;
13068
13069         for (FunctionType::param_iterator I = FTy->param_begin(),
13070              E = FTy->param_end(); I != E; ++I, ++Idx)
13071           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13072             // FIXME: should only count parameters that are lowered to integers.
13073             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13074
13075         if (InRegCount > 2) {
13076           report_fatal_error("Nest register in use - reduce number of inreg"
13077                              " parameters!");
13078         }
13079       }
13080       break;
13081     }
13082     case CallingConv::X86_FastCall:
13083     case CallingConv::X86_ThisCall:
13084     case CallingConv::Fast:
13085       // Pass 'nest' parameter in EAX.
13086       // Must be kept in sync with X86CallingConv.td
13087       NestReg = X86::EAX;
13088       break;
13089     }
13090
13091     SDValue OutChains[4];
13092     SDValue Addr, Disp;
13093
13094     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13095                        DAG.getConstant(10, MVT::i32));
13096     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13097
13098     // This is storing the opcode for MOV32ri.
13099     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13100     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13101     OutChains[0] = DAG.getStore(Root, dl,
13102                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13103                                 Trmp, MachinePointerInfo(TrmpAddr),
13104                                 false, false, 0);
13105
13106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13107                        DAG.getConstant(1, MVT::i32));
13108     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13109                                 MachinePointerInfo(TrmpAddr, 1),
13110                                 false, false, 1);
13111
13112     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13114                        DAG.getConstant(5, MVT::i32));
13115     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13116                                 MachinePointerInfo(TrmpAddr, 5),
13117                                 false, false, 1);
13118
13119     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13120                        DAG.getConstant(6, MVT::i32));
13121     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13122                                 MachinePointerInfo(TrmpAddr, 6),
13123                                 false, false, 1);
13124
13125     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13126   }
13127 }
13128
13129 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13130                                             SelectionDAG &DAG) const {
13131   /*
13132    The rounding mode is in bits 11:10 of FPSR, and has the following
13133    settings:
13134      00 Round to nearest
13135      01 Round to -inf
13136      10 Round to +inf
13137      11 Round to 0
13138
13139   FLT_ROUNDS, on the other hand, expects the following:
13140     -1 Undefined
13141      0 Round to 0
13142      1 Round to nearest
13143      2 Round to +inf
13144      3 Round to -inf
13145
13146   To perform the conversion, we do:
13147     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13148   */
13149
13150   MachineFunction &MF = DAG.getMachineFunction();
13151   const TargetMachine &TM = MF.getTarget();
13152   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13153   unsigned StackAlignment = TFI.getStackAlignment();
13154   MVT VT = Op.getSimpleValueType();
13155   SDLoc DL(Op);
13156
13157   // Save FP Control Word to stack slot
13158   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13159   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13160
13161   MachineMemOperand *MMO =
13162    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13163                            MachineMemOperand::MOStore, 2, 2);
13164
13165   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13166   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13167                                           DAG.getVTList(MVT::Other),
13168                                           Ops, MVT::i16, MMO);
13169
13170   // Load FP Control Word from stack slot
13171   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13172                             MachinePointerInfo(), false, false, false, 0);
13173
13174   // Transform as necessary
13175   SDValue CWD1 =
13176     DAG.getNode(ISD::SRL, DL, MVT::i16,
13177                 DAG.getNode(ISD::AND, DL, MVT::i16,
13178                             CWD, DAG.getConstant(0x800, MVT::i16)),
13179                 DAG.getConstant(11, MVT::i8));
13180   SDValue CWD2 =
13181     DAG.getNode(ISD::SRL, DL, MVT::i16,
13182                 DAG.getNode(ISD::AND, DL, MVT::i16,
13183                             CWD, DAG.getConstant(0x400, MVT::i16)),
13184                 DAG.getConstant(9, MVT::i8));
13185
13186   SDValue RetVal =
13187     DAG.getNode(ISD::AND, DL, MVT::i16,
13188                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13189                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13190                             DAG.getConstant(1, MVT::i16)),
13191                 DAG.getConstant(3, MVT::i16));
13192
13193   return DAG.getNode((VT.getSizeInBits() < 16 ?
13194                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13195 }
13196
13197 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13198   MVT VT = Op.getSimpleValueType();
13199   EVT OpVT = VT;
13200   unsigned NumBits = VT.getSizeInBits();
13201   SDLoc dl(Op);
13202
13203   Op = Op.getOperand(0);
13204   if (VT == MVT::i8) {
13205     // Zero extend to i32 since there is not an i8 bsr.
13206     OpVT = MVT::i32;
13207     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13208   }
13209
13210   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13211   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13212   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13213
13214   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13215   SDValue Ops[] = {
13216     Op,
13217     DAG.getConstant(NumBits+NumBits-1, OpVT),
13218     DAG.getConstant(X86::COND_E, MVT::i8),
13219     Op.getValue(1)
13220   };
13221   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13222
13223   // Finally xor with NumBits-1.
13224   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13225
13226   if (VT == MVT::i8)
13227     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13228   return Op;
13229 }
13230
13231 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13232   MVT VT = Op.getSimpleValueType();
13233   EVT OpVT = VT;
13234   unsigned NumBits = VT.getSizeInBits();
13235   SDLoc dl(Op);
13236
13237   Op = Op.getOperand(0);
13238   if (VT == MVT::i8) {
13239     // Zero extend to i32 since there is not an i8 bsr.
13240     OpVT = MVT::i32;
13241     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13242   }
13243
13244   // Issue a bsr (scan bits in reverse).
13245   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13246   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13247
13248   // And xor with NumBits-1.
13249   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13250
13251   if (VT == MVT::i8)
13252     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13253   return Op;
13254 }
13255
13256 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13257   MVT VT = Op.getSimpleValueType();
13258   unsigned NumBits = VT.getSizeInBits();
13259   SDLoc dl(Op);
13260   Op = Op.getOperand(0);
13261
13262   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13263   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13264   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13265
13266   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13267   SDValue Ops[] = {
13268     Op,
13269     DAG.getConstant(NumBits, VT),
13270     DAG.getConstant(X86::COND_E, MVT::i8),
13271     Op.getValue(1)
13272   };
13273   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13274 }
13275
13276 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13277 // ones, and then concatenate the result back.
13278 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13279   MVT VT = Op.getSimpleValueType();
13280
13281   assert(VT.is256BitVector() && VT.isInteger() &&
13282          "Unsupported value type for operation");
13283
13284   unsigned NumElems = VT.getVectorNumElements();
13285   SDLoc dl(Op);
13286
13287   // Extract the LHS vectors
13288   SDValue LHS = Op.getOperand(0);
13289   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13290   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13291
13292   // Extract the RHS vectors
13293   SDValue RHS = Op.getOperand(1);
13294   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13295   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13296
13297   MVT EltVT = VT.getVectorElementType();
13298   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13299
13300   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13301                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13302                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13303 }
13304
13305 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13306   assert(Op.getSimpleValueType().is256BitVector() &&
13307          Op.getSimpleValueType().isInteger() &&
13308          "Only handle AVX 256-bit vector integer operation");
13309   return Lower256IntArith(Op, DAG);
13310 }
13311
13312 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13313   assert(Op.getSimpleValueType().is256BitVector() &&
13314          Op.getSimpleValueType().isInteger() &&
13315          "Only handle AVX 256-bit vector integer operation");
13316   return Lower256IntArith(Op, DAG);
13317 }
13318
13319 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13320                         SelectionDAG &DAG) {
13321   SDLoc dl(Op);
13322   MVT VT = Op.getSimpleValueType();
13323
13324   // Decompose 256-bit ops into smaller 128-bit ops.
13325   if (VT.is256BitVector() && !Subtarget->hasInt256())
13326     return Lower256IntArith(Op, DAG);
13327
13328   SDValue A = Op.getOperand(0);
13329   SDValue B = Op.getOperand(1);
13330
13331   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13332   if (VT == MVT::v4i32) {
13333     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13334            "Should not custom lower when pmuldq is available!");
13335
13336     // Extract the odd parts.
13337     static const int UnpackMask[] = { 1, -1, 3, -1 };
13338     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13339     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13340
13341     // Multiply the even parts.
13342     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13343     // Now multiply odd parts.
13344     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13345
13346     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13347     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13348
13349     // Merge the two vectors back together with a shuffle. This expands into 2
13350     // shuffles.
13351     static const int ShufMask[] = { 0, 4, 2, 6 };
13352     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13353   }
13354
13355   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13356          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13357
13358   //  Ahi = psrlqi(a, 32);
13359   //  Bhi = psrlqi(b, 32);
13360   //
13361   //  AloBlo = pmuludq(a, b);
13362   //  AloBhi = pmuludq(a, Bhi);
13363   //  AhiBlo = pmuludq(Ahi, b);
13364
13365   //  AloBhi = psllqi(AloBhi, 32);
13366   //  AhiBlo = psllqi(AhiBlo, 32);
13367   //  return AloBlo + AloBhi + AhiBlo;
13368
13369   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13370   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13371
13372   // Bit cast to 32-bit vectors for MULUDQ
13373   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13374                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13375   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13376   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13377   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13378   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13379
13380   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13381   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13382   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13383
13384   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13385   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13386
13387   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13388   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13389 }
13390
13391 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13392   assert(Subtarget->isTargetWin64() && "Unexpected target");
13393   EVT VT = Op.getValueType();
13394   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13395          "Unexpected return type for lowering");
13396
13397   RTLIB::Libcall LC;
13398   bool isSigned;
13399   switch (Op->getOpcode()) {
13400   default: llvm_unreachable("Unexpected request for libcall!");
13401   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13402   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13403   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13404   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13405   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13406   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13407   }
13408
13409   SDLoc dl(Op);
13410   SDValue InChain = DAG.getEntryNode();
13411
13412   TargetLowering::ArgListTy Args;
13413   TargetLowering::ArgListEntry Entry;
13414   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13415     EVT ArgVT = Op->getOperand(i).getValueType();
13416     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13417            "Unexpected argument type for lowering");
13418     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13419     Entry.Node = StackPtr;
13420     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13421                            false, false, 16);
13422     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13423     Entry.Ty = PointerType::get(ArgTy,0);
13424     Entry.isSExt = false;
13425     Entry.isZExt = false;
13426     Args.push_back(Entry);
13427   }
13428
13429   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13430                                          getPointerTy());
13431
13432   TargetLowering::CallLoweringInfo CLI(DAG);
13433   CLI.setDebugLoc(dl).setChain(InChain)
13434     .setCallee(getLibcallCallingConv(LC),
13435                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13436                Callee, &Args, 0)
13437     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13438
13439   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13440   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13441 }
13442
13443 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13444                              SelectionDAG &DAG) {
13445   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13446   EVT VT = Op0.getValueType();
13447   SDLoc dl(Op);
13448
13449   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13450          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13451
13452   // Get the high parts.
13453   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13454   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13455   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13456
13457   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13458   // ints.
13459   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13460   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13461   unsigned Opcode =
13462       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13463   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13464                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13465   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13466                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13467
13468   // Shuffle it back into the right order.
13469   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13470   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13471   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13472   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13473
13474   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13475   // unsigned multiply.
13476   if (IsSigned && !Subtarget->hasSSE41()) {
13477     SDValue ShAmt =
13478         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13479     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13480                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13481     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13482                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13483
13484     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13485     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13486   }
13487
13488   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13489 }
13490
13491 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13492                                          const X86Subtarget *Subtarget) {
13493   MVT VT = Op.getSimpleValueType();
13494   SDLoc dl(Op);
13495   SDValue R = Op.getOperand(0);
13496   SDValue Amt = Op.getOperand(1);
13497
13498   // Optimize shl/srl/sra with constant shift amount.
13499   if (isSplatVector(Amt.getNode())) {
13500     SDValue SclrAmt = Amt->getOperand(0);
13501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13502       uint64_t ShiftAmt = C->getZExtValue();
13503
13504       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13505           (Subtarget->hasInt256() &&
13506            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13507           (Subtarget->hasAVX512() &&
13508            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13509         if (Op.getOpcode() == ISD::SHL)
13510           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13511                                             DAG);
13512         if (Op.getOpcode() == ISD::SRL)
13513           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13514                                             DAG);
13515         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13516           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13517                                             DAG);
13518       }
13519
13520       if (VT == MVT::v16i8) {
13521         if (Op.getOpcode() == ISD::SHL) {
13522           // Make a large shift.
13523           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13524                                                    MVT::v8i16, R, ShiftAmt,
13525                                                    DAG);
13526           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13527           // Zero out the rightmost 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, SHL,
13532                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13533         }
13534         if (Op.getOpcode() == ISD::SRL) {
13535           // Make a large shift.
13536           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13537                                                    MVT::v8i16, R, ShiftAmt,
13538                                                    DAG);
13539           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13540           // Zero out the leftmost bits.
13541           SmallVector<SDValue, 16> V(16,
13542                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13543                                                      MVT::i8));
13544           return DAG.getNode(ISD::AND, dl, VT, SRL,
13545                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13546         }
13547         if (Op.getOpcode() == ISD::SRA) {
13548           if (ShiftAmt == 7) {
13549             // R s>> 7  ===  R s< 0
13550             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13551             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13552           }
13553
13554           // R s>> a === ((R u>> a) ^ m) - m
13555           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13556           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13557                                                          MVT::i8));
13558           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13559           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13560           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13561           return Res;
13562         }
13563         llvm_unreachable("Unknown shift opcode.");
13564       }
13565
13566       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13567         if (Op.getOpcode() == ISD::SHL) {
13568           // Make a large shift.
13569           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13570                                                    MVT::v16i16, R, ShiftAmt,
13571                                                    DAG);
13572           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13573           // Zero out the rightmost 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, SHL,
13578                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13579         }
13580         if (Op.getOpcode() == ISD::SRL) {
13581           // Make a large shift.
13582           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13583                                                    MVT::v16i16, R, ShiftAmt,
13584                                                    DAG);
13585           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13586           // Zero out the leftmost bits.
13587           SmallVector<SDValue, 32> V(32,
13588                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13589                                                      MVT::i8));
13590           return DAG.getNode(ISD::AND, dl, VT, SRL,
13591                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13592         }
13593         if (Op.getOpcode() == ISD::SRA) {
13594           if (ShiftAmt == 7) {
13595             // R s>> 7  ===  R s< 0
13596             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13597             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13598           }
13599
13600           // R s>> a === ((R u>> a) ^ m) - m
13601           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13602           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13603                                                          MVT::i8));
13604           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13605           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13606           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13607           return Res;
13608         }
13609         llvm_unreachable("Unknown shift opcode.");
13610       }
13611     }
13612   }
13613
13614   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13615   if (!Subtarget->is64Bit() &&
13616       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13617       Amt.getOpcode() == ISD::BITCAST &&
13618       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13619     Amt = Amt.getOperand(0);
13620     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13621                      VT.getVectorNumElements();
13622     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13623     uint64_t ShiftAmt = 0;
13624     for (unsigned i = 0; i != Ratio; ++i) {
13625       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13626       if (!C)
13627         return SDValue();
13628       // 6 == Log2(64)
13629       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13630     }
13631     // Check remaining shift amounts.
13632     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13633       uint64_t ShAmt = 0;
13634       for (unsigned j = 0; j != Ratio; ++j) {
13635         ConstantSDNode *C =
13636           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13637         if (!C)
13638           return SDValue();
13639         // 6 == Log2(64)
13640         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13641       }
13642       if (ShAmt != ShiftAmt)
13643         return SDValue();
13644     }
13645     switch (Op.getOpcode()) {
13646     default:
13647       llvm_unreachable("Unknown shift opcode!");
13648     case ISD::SHL:
13649       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13650                                         DAG);
13651     case ISD::SRL:
13652       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13653                                         DAG);
13654     case ISD::SRA:
13655       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13656                                         DAG);
13657     }
13658   }
13659
13660   return SDValue();
13661 }
13662
13663 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13664                                         const X86Subtarget* Subtarget) {
13665   MVT VT = Op.getSimpleValueType();
13666   SDLoc dl(Op);
13667   SDValue R = Op.getOperand(0);
13668   SDValue Amt = Op.getOperand(1);
13669
13670   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13671       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13672       (Subtarget->hasInt256() &&
13673        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13674         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13675        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13676     SDValue BaseShAmt;
13677     EVT EltVT = VT.getVectorElementType();
13678
13679     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13680       unsigned NumElts = VT.getVectorNumElements();
13681       unsigned i, j;
13682       for (i = 0; i != NumElts; ++i) {
13683         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13684           continue;
13685         break;
13686       }
13687       for (j = i; j != NumElts; ++j) {
13688         SDValue Arg = Amt.getOperand(j);
13689         if (Arg.getOpcode() == ISD::UNDEF) continue;
13690         if (Arg != Amt.getOperand(i))
13691           break;
13692       }
13693       if (i != NumElts && j == NumElts)
13694         BaseShAmt = Amt.getOperand(i);
13695     } else {
13696       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13697         Amt = Amt.getOperand(0);
13698       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13699                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13700         SDValue InVec = Amt.getOperand(0);
13701         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13702           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13703           unsigned i = 0;
13704           for (; i != NumElts; ++i) {
13705             SDValue Arg = InVec.getOperand(i);
13706             if (Arg.getOpcode() == ISD::UNDEF) continue;
13707             BaseShAmt = Arg;
13708             break;
13709           }
13710         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13711            if (ConstantSDNode *C =
13712                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13713              unsigned SplatIdx =
13714                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13715              if (C->getZExtValue() == SplatIdx)
13716                BaseShAmt = InVec.getOperand(1);
13717            }
13718         }
13719         if (!BaseShAmt.getNode())
13720           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13721                                   DAG.getIntPtrConstant(0));
13722       }
13723     }
13724
13725     if (BaseShAmt.getNode()) {
13726       if (EltVT.bitsGT(MVT::i32))
13727         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13728       else if (EltVT.bitsLT(MVT::i32))
13729         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13730
13731       switch (Op.getOpcode()) {
13732       default:
13733         llvm_unreachable("Unknown shift opcode!");
13734       case ISD::SHL:
13735         switch (VT.SimpleTy) {
13736         default: return SDValue();
13737         case MVT::v2i64:
13738         case MVT::v4i32:
13739         case MVT::v8i16:
13740         case MVT::v4i64:
13741         case MVT::v8i32:
13742         case MVT::v16i16:
13743         case MVT::v16i32:
13744         case MVT::v8i64:
13745           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13746         }
13747       case ISD::SRA:
13748         switch (VT.SimpleTy) {
13749         default: return SDValue();
13750         case MVT::v4i32:
13751         case MVT::v8i16:
13752         case MVT::v8i32:
13753         case MVT::v16i16:
13754         case MVT::v16i32:
13755         case MVT::v8i64:
13756           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13757         }
13758       case ISD::SRL:
13759         switch (VT.SimpleTy) {
13760         default: return SDValue();
13761         case MVT::v2i64:
13762         case MVT::v4i32:
13763         case MVT::v8i16:
13764         case MVT::v4i64:
13765         case MVT::v8i32:
13766         case MVT::v16i16:
13767         case MVT::v16i32:
13768         case MVT::v8i64:
13769           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13770         }
13771       }
13772     }
13773   }
13774
13775   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13776   if (!Subtarget->is64Bit() &&
13777       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13778       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13779       Amt.getOpcode() == ISD::BITCAST &&
13780       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13781     Amt = Amt.getOperand(0);
13782     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13783                      VT.getVectorNumElements();
13784     std::vector<SDValue> Vals(Ratio);
13785     for (unsigned i = 0; i != Ratio; ++i)
13786       Vals[i] = Amt.getOperand(i);
13787     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13788       for (unsigned j = 0; j != Ratio; ++j)
13789         if (Vals[j] != Amt.getOperand(i + j))
13790           return SDValue();
13791     }
13792     switch (Op.getOpcode()) {
13793     default:
13794       llvm_unreachable("Unknown shift opcode!");
13795     case ISD::SHL:
13796       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13797     case ISD::SRL:
13798       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13799     case ISD::SRA:
13800       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13801     }
13802   }
13803
13804   return SDValue();
13805 }
13806
13807 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13808                           SelectionDAG &DAG) {
13809
13810   MVT VT = Op.getSimpleValueType();
13811   SDLoc dl(Op);
13812   SDValue R = Op.getOperand(0);
13813   SDValue Amt = Op.getOperand(1);
13814   SDValue V;
13815
13816   if (!Subtarget->hasSSE2())
13817     return SDValue();
13818
13819   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13820   if (V.getNode())
13821     return V;
13822
13823   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13824   if (V.getNode())
13825       return V;
13826
13827   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13828     return Op;
13829   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13830   if (Subtarget->hasInt256()) {
13831     if (Op.getOpcode() == ISD::SRL &&
13832         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13833          VT == MVT::v4i64 || VT == MVT::v8i32))
13834       return Op;
13835     if (Op.getOpcode() == ISD::SHL &&
13836         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13837          VT == MVT::v4i64 || VT == MVT::v8i32))
13838       return Op;
13839     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13840       return Op;
13841   }
13842
13843   // If possible, lower this packed shift into a vector multiply instead of
13844   // expanding it into a sequence of scalar shifts.
13845   // Do this only if the vector shift count is a constant build_vector.
13846   if (Op.getOpcode() == ISD::SHL && 
13847       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13848        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13849       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13850     SmallVector<SDValue, 8> Elts;
13851     EVT SVT = VT.getScalarType();
13852     unsigned SVTBits = SVT.getSizeInBits();
13853     const APInt &One = APInt(SVTBits, 1);
13854     unsigned NumElems = VT.getVectorNumElements();
13855
13856     for (unsigned i=0; i !=NumElems; ++i) {
13857       SDValue Op = Amt->getOperand(i);
13858       if (Op->getOpcode() == ISD::UNDEF) {
13859         Elts.push_back(Op);
13860         continue;
13861       }
13862
13863       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13864       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13865       uint64_t ShAmt = C.getZExtValue();
13866       if (ShAmt >= SVTBits) {
13867         Elts.push_back(DAG.getUNDEF(SVT));
13868         continue;
13869       }
13870       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13871     }
13872     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13873     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13874   }
13875
13876   // Lower SHL with variable shift amount.
13877   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13878     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13879
13880     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13881     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13882     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13883     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13884   }
13885
13886   // If possible, lower this shift as a sequence of two shifts by
13887   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13888   // Example:
13889   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13890   //
13891   // Could be rewritten as:
13892   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13893   //
13894   // The advantage is that the two shifts from the example would be
13895   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13896   // the vector shift into four scalar shifts plus four pairs of vector
13897   // insert/extract.
13898   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13899       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13900     unsigned TargetOpcode = X86ISD::MOVSS;
13901     bool CanBeSimplified;
13902     // The splat value for the first packed shift (the 'X' from the example).
13903     SDValue Amt1 = Amt->getOperand(0);
13904     // The splat value for the second packed shift (the 'Y' from the example).
13905     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13906                                         Amt->getOperand(2);
13907
13908     // See if it is possible to replace this node with a sequence of
13909     // two shifts followed by a MOVSS/MOVSD
13910     if (VT == MVT::v4i32) {
13911       // Check if it is legal to use a MOVSS.
13912       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13913                         Amt2 == Amt->getOperand(3);
13914       if (!CanBeSimplified) {
13915         // Otherwise, check if we can still simplify this node using a MOVSD.
13916         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13917                           Amt->getOperand(2) == Amt->getOperand(3);
13918         TargetOpcode = X86ISD::MOVSD;
13919         Amt2 = Amt->getOperand(2);
13920       }
13921     } else {
13922       // Do similar checks for the case where the machine value type
13923       // is MVT::v8i16.
13924       CanBeSimplified = Amt1 == Amt->getOperand(1);
13925       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13926         CanBeSimplified = Amt2 == Amt->getOperand(i);
13927
13928       if (!CanBeSimplified) {
13929         TargetOpcode = X86ISD::MOVSD;
13930         CanBeSimplified = true;
13931         Amt2 = Amt->getOperand(4);
13932         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13933           CanBeSimplified = Amt1 == Amt->getOperand(i);
13934         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13935           CanBeSimplified = Amt2 == Amt->getOperand(j);
13936       }
13937     }
13938     
13939     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13940         isa<ConstantSDNode>(Amt2)) {
13941       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13942       EVT CastVT = MVT::v4i32;
13943       SDValue Splat1 = 
13944         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13945       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13946       SDValue Splat2 = 
13947         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13948       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13949       if (TargetOpcode == X86ISD::MOVSD)
13950         CastVT = MVT::v2i64;
13951       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13952       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13953       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13954                                             BitCast1, DAG);
13955       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13956     }
13957   }
13958
13959   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13960     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13961
13962     // a = a << 5;
13963     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13964     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13965
13966     // Turn 'a' into a mask suitable for VSELECT
13967     SDValue VSelM = DAG.getConstant(0x80, VT);
13968     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13969     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13970
13971     SDValue CM1 = DAG.getConstant(0x0f, VT);
13972     SDValue CM2 = DAG.getConstant(0x3f, VT);
13973
13974     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13975     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13976     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13977     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13978     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13979
13980     // a += a
13981     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13982     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13983     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13984
13985     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13986     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13987     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13988     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13989     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13990
13991     // a += a
13992     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13993     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13994     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13995
13996     // return VSELECT(r, r+r, a);
13997     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13998                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13999     return R;
14000   }
14001
14002   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14003   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14004   // solution better.
14005   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14006     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14007     unsigned ExtOpc =
14008         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14009     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14010     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14011     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14012                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14013     }
14014
14015   // Decompose 256-bit shifts into smaller 128-bit shifts.
14016   if (VT.is256BitVector()) {
14017     unsigned NumElems = VT.getVectorNumElements();
14018     MVT EltVT = VT.getVectorElementType();
14019     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14020
14021     // Extract the two vectors
14022     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14023     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14024
14025     // Recreate the shift amount vectors
14026     SDValue Amt1, Amt2;
14027     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14028       // Constant shift amount
14029       SmallVector<SDValue, 4> Amt1Csts;
14030       SmallVector<SDValue, 4> Amt2Csts;
14031       for (unsigned i = 0; i != NumElems/2; ++i)
14032         Amt1Csts.push_back(Amt->getOperand(i));
14033       for (unsigned i = NumElems/2; i != NumElems; ++i)
14034         Amt2Csts.push_back(Amt->getOperand(i));
14035
14036       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14037       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14038     } else {
14039       // Variable shift amount
14040       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14041       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14042     }
14043
14044     // Issue new vector shifts for the smaller types
14045     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14046     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14047
14048     // Concatenate the result back
14049     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14050   }
14051
14052   return SDValue();
14053 }
14054
14055 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14056   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14057   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14058   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14059   // has only one use.
14060   SDNode *N = Op.getNode();
14061   SDValue LHS = N->getOperand(0);
14062   SDValue RHS = N->getOperand(1);
14063   unsigned BaseOp = 0;
14064   unsigned Cond = 0;
14065   SDLoc DL(Op);
14066   switch (Op.getOpcode()) {
14067   default: llvm_unreachable("Unknown ovf instruction!");
14068   case ISD::SADDO:
14069     // A subtract of one will be selected as a INC. Note that INC doesn't
14070     // set CF, so we can't do this for UADDO.
14071     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14072       if (C->isOne()) {
14073         BaseOp = X86ISD::INC;
14074         Cond = X86::COND_O;
14075         break;
14076       }
14077     BaseOp = X86ISD::ADD;
14078     Cond = X86::COND_O;
14079     break;
14080   case ISD::UADDO:
14081     BaseOp = X86ISD::ADD;
14082     Cond = X86::COND_B;
14083     break;
14084   case ISD::SSUBO:
14085     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14086     // set CF, so we can't do this for USUBO.
14087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14088       if (C->isOne()) {
14089         BaseOp = X86ISD::DEC;
14090         Cond = X86::COND_O;
14091         break;
14092       }
14093     BaseOp = X86ISD::SUB;
14094     Cond = X86::COND_O;
14095     break;
14096   case ISD::USUBO:
14097     BaseOp = X86ISD::SUB;
14098     Cond = X86::COND_B;
14099     break;
14100   case ISD::SMULO:
14101     BaseOp = X86ISD::SMUL;
14102     Cond = X86::COND_O;
14103     break;
14104   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14105     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14106                                  MVT::i32);
14107     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14108
14109     SDValue SetCC =
14110       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14111                   DAG.getConstant(X86::COND_O, MVT::i32),
14112                   SDValue(Sum.getNode(), 2));
14113
14114     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14115   }
14116   }
14117
14118   // Also sets EFLAGS.
14119   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14120   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14121
14122   SDValue SetCC =
14123     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14124                 DAG.getConstant(Cond, MVT::i32),
14125                 SDValue(Sum.getNode(), 1));
14126
14127   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14128 }
14129
14130 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14131                                                   SelectionDAG &DAG) const {
14132   SDLoc dl(Op);
14133   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14134   MVT VT = Op.getSimpleValueType();
14135
14136   if (!Subtarget->hasSSE2() || !VT.isVector())
14137     return SDValue();
14138
14139   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14140                       ExtraVT.getScalarType().getSizeInBits();
14141
14142   switch (VT.SimpleTy) {
14143     default: return SDValue();
14144     case MVT::v8i32:
14145     case MVT::v16i16:
14146       if (!Subtarget->hasFp256())
14147         return SDValue();
14148       if (!Subtarget->hasInt256()) {
14149         // needs to be split
14150         unsigned NumElems = VT.getVectorNumElements();
14151
14152         // Extract the LHS vectors
14153         SDValue LHS = Op.getOperand(0);
14154         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14155         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14156
14157         MVT EltVT = VT.getVectorElementType();
14158         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14159
14160         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14161         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14162         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14163                                    ExtraNumElems/2);
14164         SDValue Extra = DAG.getValueType(ExtraVT);
14165
14166         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14167         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14168
14169         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14170       }
14171       // fall through
14172     case MVT::v4i32:
14173     case MVT::v8i16: {
14174       SDValue Op0 = Op.getOperand(0);
14175       SDValue Op00 = Op0.getOperand(0);
14176       SDValue Tmp1;
14177       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14178       if (Op0.getOpcode() == ISD::BITCAST &&
14179           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14180         // (sext (vzext x)) -> (vsext x)
14181         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14182         if (Tmp1.getNode()) {
14183           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14184           // This folding is only valid when the in-reg type is a vector of i8,
14185           // i16, or i32.
14186           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14187               ExtraEltVT == MVT::i32) {
14188             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14189             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14190                    "This optimization is invalid without a VZEXT.");
14191             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14192           }
14193           Op0 = Tmp1;
14194         }
14195       }
14196
14197       // If the above didn't work, then just use Shift-Left + Shift-Right.
14198       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14199                                         DAG);
14200       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14201                                         DAG);
14202     }
14203   }
14204 }
14205
14206 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14207                                  SelectionDAG &DAG) {
14208   SDLoc dl(Op);
14209   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14210     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14211   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14212     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14213
14214   // The only fence that needs an instruction is a sequentially-consistent
14215   // cross-thread fence.
14216   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14217     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14218     // no-sse2). There isn't any reason to disable it if the target processor
14219     // supports it.
14220     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14221       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14222
14223     SDValue Chain = Op.getOperand(0);
14224     SDValue Zero = DAG.getConstant(0, MVT::i32);
14225     SDValue Ops[] = {
14226       DAG.getRegister(X86::ESP, MVT::i32), // Base
14227       DAG.getTargetConstant(1, MVT::i8),   // Scale
14228       DAG.getRegister(0, MVT::i32),        // Index
14229       DAG.getTargetConstant(0, MVT::i32),  // Disp
14230       DAG.getRegister(0, MVT::i32),        // Segment.
14231       Zero,
14232       Chain
14233     };
14234     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14235     return SDValue(Res, 0);
14236   }
14237
14238   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14239   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14240 }
14241
14242 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14243                              SelectionDAG &DAG) {
14244   MVT T = Op.getSimpleValueType();
14245   SDLoc DL(Op);
14246   unsigned Reg = 0;
14247   unsigned size = 0;
14248   switch(T.SimpleTy) {
14249   default: llvm_unreachable("Invalid value type!");
14250   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14251   case MVT::i16: Reg = X86::AX;  size = 2; break;
14252   case MVT::i32: Reg = X86::EAX; size = 4; break;
14253   case MVT::i64:
14254     assert(Subtarget->is64Bit() && "Node not type legal!");
14255     Reg = X86::RAX; size = 8;
14256     break;
14257   }
14258   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14259                                     Op.getOperand(2), SDValue());
14260   SDValue Ops[] = { cpIn.getValue(0),
14261                     Op.getOperand(1),
14262                     Op.getOperand(3),
14263                     DAG.getTargetConstant(size, MVT::i8),
14264                     cpIn.getValue(1) };
14265   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14266   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14267   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14268                                            Ops, T, MMO);
14269   SDValue cpOut =
14270     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14271   return cpOut;
14272 }
14273
14274 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14275                             SelectionDAG &DAG) {
14276   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14277   MVT DstVT = Op.getSimpleValueType();
14278
14279   if (SrcVT == MVT::v2i32) {
14280     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14281     if (DstVT != MVT::f64)
14282       // This conversion needs to be expanded.
14283       return SDValue();
14284
14285     SDLoc dl(Op);
14286     SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14287                                Op->getOperand(0), DAG.getIntPtrConstant(0));
14288     SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14289                                Op->getOperand(0), DAG.getIntPtrConstant(1));
14290     SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14291     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14292     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14293     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14294                        DAG.getIntPtrConstant(0));
14295   }
14296
14297   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14298          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14299   assert((DstVT == MVT::i64 ||
14300           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14301          "Unexpected custom BITCAST");
14302   // i64 <=> MMX conversions are Legal.
14303   if (SrcVT==MVT::i64 && DstVT.isVector())
14304     return Op;
14305   if (DstVT==MVT::i64 && SrcVT.isVector())
14306     return Op;
14307   // MMX <=> MMX conversions are Legal.
14308   if (SrcVT.isVector() && DstVT.isVector())
14309     return Op;
14310   // All other conversions need to be expanded.
14311   return SDValue();
14312 }
14313
14314 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14315   SDNode *Node = Op.getNode();
14316   SDLoc dl(Node);
14317   EVT T = Node->getValueType(0);
14318   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14319                               DAG.getConstant(0, T), Node->getOperand(2));
14320   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14321                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14322                        Node->getOperand(0),
14323                        Node->getOperand(1), negOp,
14324                        cast<AtomicSDNode>(Node)->getMemOperand(),
14325                        cast<AtomicSDNode>(Node)->getOrdering(),
14326                        cast<AtomicSDNode>(Node)->getSynchScope());
14327 }
14328
14329 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14330   SDNode *Node = Op.getNode();
14331   SDLoc dl(Node);
14332   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14333
14334   // Convert seq_cst store -> xchg
14335   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14336   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14337   //        (The only way to get a 16-byte store is cmpxchg16b)
14338   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14339   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14340       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14341     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14342                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14343                                  Node->getOperand(0),
14344                                  Node->getOperand(1), Node->getOperand(2),
14345                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14346                                  cast<AtomicSDNode>(Node)->getOrdering(),
14347                                  cast<AtomicSDNode>(Node)->getSynchScope());
14348     return Swap.getValue(1);
14349   }
14350   // Other atomic stores have a simple pattern.
14351   return Op;
14352 }
14353
14354 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14355   EVT VT = Op.getNode()->getSimpleValueType(0);
14356
14357   // Let legalize expand this if it isn't a legal type yet.
14358   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14359     return SDValue();
14360
14361   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14362
14363   unsigned Opc;
14364   bool ExtraOp = false;
14365   switch (Op.getOpcode()) {
14366   default: llvm_unreachable("Invalid code");
14367   case ISD::ADDC: Opc = X86ISD::ADD; break;
14368   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14369   case ISD::SUBC: Opc = X86ISD::SUB; break;
14370   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14371   }
14372
14373   if (!ExtraOp)
14374     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14375                        Op.getOperand(1));
14376   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14377                      Op.getOperand(1), Op.getOperand(2));
14378 }
14379
14380 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14381                             SelectionDAG &DAG) {
14382   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14383
14384   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14385   // which returns the values as { float, float } (in XMM0) or
14386   // { double, double } (which is returned in XMM0, XMM1).
14387   SDLoc dl(Op);
14388   SDValue Arg = Op.getOperand(0);
14389   EVT ArgVT = Arg.getValueType();
14390   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14391
14392   TargetLowering::ArgListTy Args;
14393   TargetLowering::ArgListEntry Entry;
14394
14395   Entry.Node = Arg;
14396   Entry.Ty = ArgTy;
14397   Entry.isSExt = false;
14398   Entry.isZExt = false;
14399   Args.push_back(Entry);
14400
14401   bool isF64 = ArgVT == MVT::f64;
14402   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14403   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14404   // the results are returned via SRet in memory.
14405   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14407   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14408
14409   Type *RetTy = isF64
14410     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14411     : (Type*)VectorType::get(ArgTy, 4);
14412
14413   TargetLowering::CallLoweringInfo CLI(DAG);
14414   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14415     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14416
14417   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14418
14419   if (isF64)
14420     // Returned in xmm0 and xmm1.
14421     return CallResult.first;
14422
14423   // Returned in bits 0:31 and 32:64 xmm0.
14424   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14425                                CallResult.first, DAG.getIntPtrConstant(0));
14426   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14427                                CallResult.first, DAG.getIntPtrConstant(1));
14428   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14429   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14430 }
14431
14432 /// LowerOperation - Provide custom lowering hooks for some operations.
14433 ///
14434 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14435   switch (Op.getOpcode()) {
14436   default: llvm_unreachable("Should not custom lower this!");
14437   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14438   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14439   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14440   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14441   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14442   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14443   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14444   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14445   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14446   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14447   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14448   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14449   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14450   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14451   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14452   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14453   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14454   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14455   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14456   case ISD::SHL_PARTS:
14457   case ISD::SRA_PARTS:
14458   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14459   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14460   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14461   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14462   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14463   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14464   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14465   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14466   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14467   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14468   case ISD::FABS:               return LowerFABS(Op, DAG);
14469   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14470   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14471   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14472   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14473   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14474   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14475   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14476   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14477   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14478   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14479   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14480   case ISD::INTRINSIC_VOID:
14481   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14482   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14483   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14484   case ISD::FRAME_TO_ARGS_OFFSET:
14485                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14486   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14487   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14488   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14489   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14490   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14491   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14492   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14493   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14494   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14495   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14496   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14497   case ISD::UMUL_LOHI:
14498   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14499   case ISD::SRA:
14500   case ISD::SRL:
14501   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14502   case ISD::SADDO:
14503   case ISD::UADDO:
14504   case ISD::SSUBO:
14505   case ISD::USUBO:
14506   case ISD::SMULO:
14507   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14508   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14509   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14510   case ISD::ADDC:
14511   case ISD::ADDE:
14512   case ISD::SUBC:
14513   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14514   case ISD::ADD:                return LowerADD(Op, DAG);
14515   case ISD::SUB:                return LowerSUB(Op, DAG);
14516   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14517   }
14518 }
14519
14520 static void ReplaceATOMIC_LOAD(SDNode *Node,
14521                                   SmallVectorImpl<SDValue> &Results,
14522                                   SelectionDAG &DAG) {
14523   SDLoc dl(Node);
14524   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14525
14526   // Convert wide load -> cmpxchg8b/cmpxchg16b
14527   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14528   //        (The only way to get a 16-byte load is cmpxchg16b)
14529   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14530   SDValue Zero = DAG.getConstant(0, VT);
14531   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14532                                Node->getOperand(0),
14533                                Node->getOperand(1), Zero, Zero,
14534                                cast<AtomicSDNode>(Node)->getMemOperand(),
14535                                cast<AtomicSDNode>(Node)->getOrdering(),
14536                                cast<AtomicSDNode>(Node)->getOrdering(),
14537                                cast<AtomicSDNode>(Node)->getSynchScope());
14538   Results.push_back(Swap.getValue(0));
14539   Results.push_back(Swap.getValue(1));
14540 }
14541
14542 static void
14543 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14544                         SelectionDAG &DAG, unsigned NewOp) {
14545   SDLoc dl(Node);
14546   assert (Node->getValueType(0) == MVT::i64 &&
14547           "Only know how to expand i64 atomics");
14548
14549   SDValue Chain = Node->getOperand(0);
14550   SDValue In1 = Node->getOperand(1);
14551   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14552                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14553   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14554                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14555   SDValue Ops[] = { Chain, In1, In2L, In2H };
14556   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14557   SDValue Result =
14558     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14559                             cast<MemSDNode>(Node)->getMemOperand());
14560   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14561   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14562   Results.push_back(Result.getValue(2));
14563 }
14564
14565 /// ReplaceNodeResults - Replace a node with an illegal result type
14566 /// with a new node built out of custom code.
14567 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14568                                            SmallVectorImpl<SDValue>&Results,
14569                                            SelectionDAG &DAG) const {
14570   SDLoc dl(N);
14571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14572   switch (N->getOpcode()) {
14573   default:
14574     llvm_unreachable("Do not know how to custom type legalize this operation!");
14575   case ISD::SIGN_EXTEND_INREG:
14576   case ISD::ADDC:
14577   case ISD::ADDE:
14578   case ISD::SUBC:
14579   case ISD::SUBE:
14580     // We don't want to expand or promote these.
14581     return;
14582   case ISD::SDIV:
14583   case ISD::UDIV:
14584   case ISD::SREM:
14585   case ISD::UREM:
14586   case ISD::SDIVREM:
14587   case ISD::UDIVREM: {
14588     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14589     Results.push_back(V);
14590     return;
14591   }
14592   case ISD::FP_TO_SINT:
14593   case ISD::FP_TO_UINT: {
14594     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14595
14596     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14597       return;
14598
14599     std::pair<SDValue,SDValue> Vals =
14600         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14601     SDValue FIST = Vals.first, StackSlot = Vals.second;
14602     if (FIST.getNode()) {
14603       EVT VT = N->getValueType(0);
14604       // Return a load from the stack slot.
14605       if (StackSlot.getNode())
14606         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14607                                       MachinePointerInfo(),
14608                                       false, false, false, 0));
14609       else
14610         Results.push_back(FIST);
14611     }
14612     return;
14613   }
14614   case ISD::UINT_TO_FP: {
14615     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14616     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14617         N->getValueType(0) != MVT::v2f32)
14618       return;
14619     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14620                                  N->getOperand(0));
14621     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14622                                      MVT::f64);
14623     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14624     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14625                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14626     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14627     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14628     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14629     return;
14630   }
14631   case ISD::FP_ROUND: {
14632     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14633         return;
14634     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14635     Results.push_back(V);
14636     return;
14637   }
14638   case ISD::INTRINSIC_W_CHAIN: {
14639     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14640     switch (IntNo) {
14641     default : llvm_unreachable("Do not know how to custom type "
14642                                "legalize this intrinsic operation!");
14643     case Intrinsic::x86_rdtsc:
14644       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14645                                      Results);
14646     case Intrinsic::x86_rdtscp:
14647       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14648                                      Results);
14649     }
14650   }
14651   case ISD::READCYCLECOUNTER: {
14652     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14653                                    Results);
14654   }
14655   case ISD::ATOMIC_CMP_SWAP: {
14656     EVT T = N->getValueType(0);
14657     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14658     bool Regs64bit = T == MVT::i128;
14659     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14660     SDValue cpInL, cpInH;
14661     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14662                         DAG.getConstant(0, HalfT));
14663     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14664                         DAG.getConstant(1, HalfT));
14665     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14666                              Regs64bit ? X86::RAX : X86::EAX,
14667                              cpInL, SDValue());
14668     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14669                              Regs64bit ? X86::RDX : X86::EDX,
14670                              cpInH, cpInL.getValue(1));
14671     SDValue swapInL, swapInH;
14672     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14673                           DAG.getConstant(0, HalfT));
14674     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14675                           DAG.getConstant(1, HalfT));
14676     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14677                                Regs64bit ? X86::RBX : X86::EBX,
14678                                swapInL, cpInH.getValue(1));
14679     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14680                                Regs64bit ? X86::RCX : X86::ECX,
14681                                swapInH, swapInL.getValue(1));
14682     SDValue Ops[] = { swapInH.getValue(0),
14683                       N->getOperand(1),
14684                       swapInH.getValue(1) };
14685     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14686     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14687     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14688                                   X86ISD::LCMPXCHG8_DAG;
14689     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14690     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14691                                         Regs64bit ? X86::RAX : X86::EAX,
14692                                         HalfT, Result.getValue(1));
14693     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14694                                         Regs64bit ? X86::RDX : X86::EDX,
14695                                         HalfT, cpOutL.getValue(2));
14696     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14697     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14698     Results.push_back(cpOutH.getValue(1));
14699     return;
14700   }
14701   case ISD::ATOMIC_LOAD_ADD:
14702   case ISD::ATOMIC_LOAD_AND:
14703   case ISD::ATOMIC_LOAD_NAND:
14704   case ISD::ATOMIC_LOAD_OR:
14705   case ISD::ATOMIC_LOAD_SUB:
14706   case ISD::ATOMIC_LOAD_XOR:
14707   case ISD::ATOMIC_LOAD_MAX:
14708   case ISD::ATOMIC_LOAD_MIN:
14709   case ISD::ATOMIC_LOAD_UMAX:
14710   case ISD::ATOMIC_LOAD_UMIN:
14711   case ISD::ATOMIC_SWAP: {
14712     unsigned Opc;
14713     switch (N->getOpcode()) {
14714     default: llvm_unreachable("Unexpected opcode");
14715     case ISD::ATOMIC_LOAD_ADD:
14716       Opc = X86ISD::ATOMADD64_DAG;
14717       break;
14718     case ISD::ATOMIC_LOAD_AND:
14719       Opc = X86ISD::ATOMAND64_DAG;
14720       break;
14721     case ISD::ATOMIC_LOAD_NAND:
14722       Opc = X86ISD::ATOMNAND64_DAG;
14723       break;
14724     case ISD::ATOMIC_LOAD_OR:
14725       Opc = X86ISD::ATOMOR64_DAG;
14726       break;
14727     case ISD::ATOMIC_LOAD_SUB:
14728       Opc = X86ISD::ATOMSUB64_DAG;
14729       break;
14730     case ISD::ATOMIC_LOAD_XOR:
14731       Opc = X86ISD::ATOMXOR64_DAG;
14732       break;
14733     case ISD::ATOMIC_LOAD_MAX:
14734       Opc = X86ISD::ATOMMAX64_DAG;
14735       break;
14736     case ISD::ATOMIC_LOAD_MIN:
14737       Opc = X86ISD::ATOMMIN64_DAG;
14738       break;
14739     case ISD::ATOMIC_LOAD_UMAX:
14740       Opc = X86ISD::ATOMUMAX64_DAG;
14741       break;
14742     case ISD::ATOMIC_LOAD_UMIN:
14743       Opc = X86ISD::ATOMUMIN64_DAG;
14744       break;
14745     case ISD::ATOMIC_SWAP:
14746       Opc = X86ISD::ATOMSWAP64_DAG;
14747       break;
14748     }
14749     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14750     return;
14751   }
14752   case ISD::ATOMIC_LOAD: {
14753     ReplaceATOMIC_LOAD(N, Results, DAG);
14754     return;
14755   }
14756   case ISD::BITCAST: {
14757     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14758     EVT DstVT = N->getValueType(0);
14759     EVT SrcVT = N->getOperand(0)->getValueType(0);
14760
14761     if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14762       SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14763                                      MVT::v2f64, N->getOperand(0));
14764       SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14765       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14766                                  ToV4I32, DAG.getIntPtrConstant(0));
14767       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14768                                  ToV4I32, DAG.getIntPtrConstant(1));
14769       SDValue Elts[] = {Elt0, Elt1};
14770       Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14771     }
14772   }
14773   }
14774 }
14775
14776 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14777   switch (Opcode) {
14778   default: return nullptr;
14779   case X86ISD::BSF:                return "X86ISD::BSF";
14780   case X86ISD::BSR:                return "X86ISD::BSR";
14781   case X86ISD::SHLD:               return "X86ISD::SHLD";
14782   case X86ISD::SHRD:               return "X86ISD::SHRD";
14783   case X86ISD::FAND:               return "X86ISD::FAND";
14784   case X86ISD::FANDN:              return "X86ISD::FANDN";
14785   case X86ISD::FOR:                return "X86ISD::FOR";
14786   case X86ISD::FXOR:               return "X86ISD::FXOR";
14787   case X86ISD::FSRL:               return "X86ISD::FSRL";
14788   case X86ISD::FILD:               return "X86ISD::FILD";
14789   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14790   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14791   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14792   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14793   case X86ISD::FLD:                return "X86ISD::FLD";
14794   case X86ISD::FST:                return "X86ISD::FST";
14795   case X86ISD::CALL:               return "X86ISD::CALL";
14796   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14797   case X86ISD::BT:                 return "X86ISD::BT";
14798   case X86ISD::CMP:                return "X86ISD::CMP";
14799   case X86ISD::COMI:               return "X86ISD::COMI";
14800   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14801   case X86ISD::CMPM:               return "X86ISD::CMPM";
14802   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14803   case X86ISD::SETCC:              return "X86ISD::SETCC";
14804   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14805   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14806   case X86ISD::CMOV:               return "X86ISD::CMOV";
14807   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14808   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14809   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14810   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14811   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14812   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14813   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14814   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14815   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14816   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14817   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14818   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14819   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14820   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14821   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14822   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14823   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14824   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14825   case X86ISD::HADD:               return "X86ISD::HADD";
14826   case X86ISD::HSUB:               return "X86ISD::HSUB";
14827   case X86ISD::FHADD:              return "X86ISD::FHADD";
14828   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14829   case X86ISD::UMAX:               return "X86ISD::UMAX";
14830   case X86ISD::UMIN:               return "X86ISD::UMIN";
14831   case X86ISD::SMAX:               return "X86ISD::SMAX";
14832   case X86ISD::SMIN:               return "X86ISD::SMIN";
14833   case X86ISD::FMAX:               return "X86ISD::FMAX";
14834   case X86ISD::FMIN:               return "X86ISD::FMIN";
14835   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14836   case X86ISD::FMINC:              return "X86ISD::FMINC";
14837   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14838   case X86ISD::FRCP:               return "X86ISD::FRCP";
14839   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14840   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14841   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14842   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14843   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14844   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14845   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14846   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14847   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14848   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14849   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14850   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14851   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14852   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14853   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14854   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14855   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14856   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14857   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14858   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14859   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14860   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14861   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14862   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14863   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14864   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14865   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14866   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14867   case X86ISD::VSHL:               return "X86ISD::VSHL";
14868   case X86ISD::VSRL:               return "X86ISD::VSRL";
14869   case X86ISD::VSRA:               return "X86ISD::VSRA";
14870   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14871   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14872   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14873   case X86ISD::CMPP:               return "X86ISD::CMPP";
14874   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14875   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14876   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14877   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14878   case X86ISD::ADD:                return "X86ISD::ADD";
14879   case X86ISD::SUB:                return "X86ISD::SUB";
14880   case X86ISD::ADC:                return "X86ISD::ADC";
14881   case X86ISD::SBB:                return "X86ISD::SBB";
14882   case X86ISD::SMUL:               return "X86ISD::SMUL";
14883   case X86ISD::UMUL:               return "X86ISD::UMUL";
14884   case X86ISD::INC:                return "X86ISD::INC";
14885   case X86ISD::DEC:                return "X86ISD::DEC";
14886   case X86ISD::OR:                 return "X86ISD::OR";
14887   case X86ISD::XOR:                return "X86ISD::XOR";
14888   case X86ISD::AND:                return "X86ISD::AND";
14889   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14890   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14891   case X86ISD::PTEST:              return "X86ISD::PTEST";
14892   case X86ISD::TESTP:              return "X86ISD::TESTP";
14893   case X86ISD::TESTM:              return "X86ISD::TESTM";
14894   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14895   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14896   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14897   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14898   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14899   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14900   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14901   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14902   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14903   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14904   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14905   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14906   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14907   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14908   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14909   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14910   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14911   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14912   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14913   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14914   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14915   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14916   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14917   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14918   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14919   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14920   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14921   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14922   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14923   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14924   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14925   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14926   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14927   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14928   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14929   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14930   case X86ISD::SAHF:               return "X86ISD::SAHF";
14931   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14932   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14933   case X86ISD::FMADD:              return "X86ISD::FMADD";
14934   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14935   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14936   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14937   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14938   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14939   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14940   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14941   case X86ISD::XTEST:              return "X86ISD::XTEST";
14942   }
14943 }
14944
14945 // isLegalAddressingMode - Return true if the addressing mode represented
14946 // by AM is legal for this target, for a load/store of the specified type.
14947 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14948                                               Type *Ty) const {
14949   // X86 supports extremely general addressing modes.
14950   CodeModel::Model M = getTargetMachine().getCodeModel();
14951   Reloc::Model R = getTargetMachine().getRelocationModel();
14952
14953   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14954   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14955     return false;
14956
14957   if (AM.BaseGV) {
14958     unsigned GVFlags =
14959       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14960
14961     // If a reference to this global requires an extra load, we can't fold it.
14962     if (isGlobalStubReference(GVFlags))
14963       return false;
14964
14965     // If BaseGV requires a register for the PIC base, we cannot also have a
14966     // BaseReg specified.
14967     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14968       return false;
14969
14970     // If lower 4G is not available, then we must use rip-relative addressing.
14971     if ((M != CodeModel::Small || R != Reloc::Static) &&
14972         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14973       return false;
14974   }
14975
14976   switch (AM.Scale) {
14977   case 0:
14978   case 1:
14979   case 2:
14980   case 4:
14981   case 8:
14982     // These scales always work.
14983     break;
14984   case 3:
14985   case 5:
14986   case 9:
14987     // These scales are formed with basereg+scalereg.  Only accept if there is
14988     // no basereg yet.
14989     if (AM.HasBaseReg)
14990       return false;
14991     break;
14992   default:  // Other stuff never works.
14993     return false;
14994   }
14995
14996   return true;
14997 }
14998
14999 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15000   unsigned Bits = Ty->getScalarSizeInBits();
15001
15002   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15003   // particularly cheaper than those without.
15004   if (Bits == 8)
15005     return false;
15006
15007   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15008   // variable shifts just as cheap as scalar ones.
15009   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15010     return false;
15011
15012   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15013   // fully general vector.
15014   return true;
15015 }
15016
15017 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15018   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15019     return false;
15020   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15021   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15022   return NumBits1 > NumBits2;
15023 }
15024
15025 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15026   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15027     return false;
15028
15029   if (!isTypeLegal(EVT::getEVT(Ty1)))
15030     return false;
15031
15032   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15033
15034   // Assuming the caller doesn't have a zeroext or signext return parameter,
15035   // truncation all the way down to i1 is valid.
15036   return true;
15037 }
15038
15039 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15040   return isInt<32>(Imm);
15041 }
15042
15043 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15044   // Can also use sub to handle negated immediates.
15045   return isInt<32>(Imm);
15046 }
15047
15048 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15049   if (!VT1.isInteger() || !VT2.isInteger())
15050     return false;
15051   unsigned NumBits1 = VT1.getSizeInBits();
15052   unsigned NumBits2 = VT2.getSizeInBits();
15053   return NumBits1 > NumBits2;
15054 }
15055
15056 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15057   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15058   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15059 }
15060
15061 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15062   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15063   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15064 }
15065
15066 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15067   EVT VT1 = Val.getValueType();
15068   if (isZExtFree(VT1, VT2))
15069     return true;
15070
15071   if (Val.getOpcode() != ISD::LOAD)
15072     return false;
15073
15074   if (!VT1.isSimple() || !VT1.isInteger() ||
15075       !VT2.isSimple() || !VT2.isInteger())
15076     return false;
15077
15078   switch (VT1.getSimpleVT().SimpleTy) {
15079   default: break;
15080   case MVT::i8:
15081   case MVT::i16:
15082   case MVT::i32:
15083     // X86 has 8, 16, and 32-bit zero-extending loads.
15084     return true;
15085   }
15086
15087   return false;
15088 }
15089
15090 bool
15091 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15092   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15093     return false;
15094
15095   VT = VT.getScalarType();
15096
15097   if (!VT.isSimple())
15098     return false;
15099
15100   switch (VT.getSimpleVT().SimpleTy) {
15101   case MVT::f32:
15102   case MVT::f64:
15103     return true;
15104   default:
15105     break;
15106   }
15107
15108   return false;
15109 }
15110
15111 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15112   // i16 instructions are longer (0x66 prefix) and potentially slower.
15113   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15114 }
15115
15116 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15117 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15118 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15119 /// are assumed to be legal.
15120 bool
15121 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15122                                       EVT VT) const {
15123   if (!VT.isSimple())
15124     return false;
15125
15126   MVT SVT = VT.getSimpleVT();
15127
15128   // Very little shuffling can be done for 64-bit vectors right now.
15129   if (VT.getSizeInBits() == 64)
15130     return false;
15131
15132   // If this is a single-input shuffle with no 128 bit lane crossings we can
15133   // lower it into pshufb.
15134   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15135       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15136     bool isLegal = true;
15137     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15138       if (M[I] >= (int)SVT.getVectorNumElements() ||
15139           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15140         isLegal = false;
15141         break;
15142       }
15143     }
15144     if (isLegal)
15145       return true;
15146   }
15147
15148   // FIXME: blends, shifts.
15149   return (SVT.getVectorNumElements() == 2 ||
15150           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15151           isMOVLMask(M, SVT) ||
15152           isSHUFPMask(M, SVT) ||
15153           isPSHUFDMask(M, SVT) ||
15154           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15155           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15156           isPALIGNRMask(M, SVT, Subtarget) ||
15157           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15158           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15159           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15160           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15161 }
15162
15163 bool
15164 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15165                                           EVT VT) const {
15166   if (!VT.isSimple())
15167     return false;
15168
15169   MVT SVT = VT.getSimpleVT();
15170   unsigned NumElts = SVT.getVectorNumElements();
15171   // FIXME: This collection of masks seems suspect.
15172   if (NumElts == 2)
15173     return true;
15174   if (NumElts == 4 && SVT.is128BitVector()) {
15175     return (isMOVLMask(Mask, SVT)  ||
15176             isCommutedMOVLMask(Mask, SVT, true) ||
15177             isSHUFPMask(Mask, SVT) ||
15178             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15179   }
15180   return false;
15181 }
15182
15183 //===----------------------------------------------------------------------===//
15184 //                           X86 Scheduler Hooks
15185 //===----------------------------------------------------------------------===//
15186
15187 /// Utility function to emit xbegin specifying the start of an RTM region.
15188 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15189                                      const TargetInstrInfo *TII) {
15190   DebugLoc DL = MI->getDebugLoc();
15191
15192   const BasicBlock *BB = MBB->getBasicBlock();
15193   MachineFunction::iterator I = MBB;
15194   ++I;
15195
15196   // For the v = xbegin(), we generate
15197   //
15198   // thisMBB:
15199   //  xbegin sinkMBB
15200   //
15201   // mainMBB:
15202   //  eax = -1
15203   //
15204   // sinkMBB:
15205   //  v = eax
15206
15207   MachineBasicBlock *thisMBB = MBB;
15208   MachineFunction *MF = MBB->getParent();
15209   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15210   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15211   MF->insert(I, mainMBB);
15212   MF->insert(I, sinkMBB);
15213
15214   // Transfer the remainder of BB and its successor edges to sinkMBB.
15215   sinkMBB->splice(sinkMBB->begin(), MBB,
15216                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15217   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15218
15219   // thisMBB:
15220   //  xbegin sinkMBB
15221   //  # fallthrough to mainMBB
15222   //  # abortion to sinkMBB
15223   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15224   thisMBB->addSuccessor(mainMBB);
15225   thisMBB->addSuccessor(sinkMBB);
15226
15227   // mainMBB:
15228   //  EAX = -1
15229   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15230   mainMBB->addSuccessor(sinkMBB);
15231
15232   // sinkMBB:
15233   // EAX is live into the sinkMBB
15234   sinkMBB->addLiveIn(X86::EAX);
15235   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15236           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15237     .addReg(X86::EAX);
15238
15239   MI->eraseFromParent();
15240   return sinkMBB;
15241 }
15242
15243 // Get CMPXCHG opcode for the specified data type.
15244 static unsigned getCmpXChgOpcode(EVT VT) {
15245   switch (VT.getSimpleVT().SimpleTy) {
15246   case MVT::i8:  return X86::LCMPXCHG8;
15247   case MVT::i16: return X86::LCMPXCHG16;
15248   case MVT::i32: return X86::LCMPXCHG32;
15249   case MVT::i64: return X86::LCMPXCHG64;
15250   default:
15251     break;
15252   }
15253   llvm_unreachable("Invalid operand size!");
15254 }
15255
15256 // Get LOAD opcode for the specified data type.
15257 static unsigned getLoadOpcode(EVT VT) {
15258   switch (VT.getSimpleVT().SimpleTy) {
15259   case MVT::i8:  return X86::MOV8rm;
15260   case MVT::i16: return X86::MOV16rm;
15261   case MVT::i32: return X86::MOV32rm;
15262   case MVT::i64: return X86::MOV64rm;
15263   default:
15264     break;
15265   }
15266   llvm_unreachable("Invalid operand size!");
15267 }
15268
15269 // Get opcode of the non-atomic one from the specified atomic instruction.
15270 static unsigned getNonAtomicOpcode(unsigned Opc) {
15271   switch (Opc) {
15272   case X86::ATOMAND8:  return X86::AND8rr;
15273   case X86::ATOMAND16: return X86::AND16rr;
15274   case X86::ATOMAND32: return X86::AND32rr;
15275   case X86::ATOMAND64: return X86::AND64rr;
15276   case X86::ATOMOR8:   return X86::OR8rr;
15277   case X86::ATOMOR16:  return X86::OR16rr;
15278   case X86::ATOMOR32:  return X86::OR32rr;
15279   case X86::ATOMOR64:  return X86::OR64rr;
15280   case X86::ATOMXOR8:  return X86::XOR8rr;
15281   case X86::ATOMXOR16: return X86::XOR16rr;
15282   case X86::ATOMXOR32: return X86::XOR32rr;
15283   case X86::ATOMXOR64: return X86::XOR64rr;
15284   }
15285   llvm_unreachable("Unhandled atomic-load-op opcode!");
15286 }
15287
15288 // Get opcode of the non-atomic one from the specified atomic instruction with
15289 // extra opcode.
15290 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15291                                                unsigned &ExtraOpc) {
15292   switch (Opc) {
15293   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15294   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15295   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15296   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15297   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15298   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15299   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15300   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15301   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15302   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15303   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15304   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15305   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15306   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15307   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15308   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15309   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15310   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15311   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15312   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15313   }
15314   llvm_unreachable("Unhandled atomic-load-op opcode!");
15315 }
15316
15317 // Get opcode of the non-atomic one from the specified atomic instruction for
15318 // 64-bit data type on 32-bit target.
15319 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15320   switch (Opc) {
15321   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15322   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15323   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15324   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15325   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15326   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15327   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15328   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15329   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15330   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15331   }
15332   llvm_unreachable("Unhandled atomic-load-op opcode!");
15333 }
15334
15335 // Get opcode of the non-atomic one from the specified atomic instruction for
15336 // 64-bit data type on 32-bit target with extra opcode.
15337 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15338                                                    unsigned &HiOpc,
15339                                                    unsigned &ExtraOpc) {
15340   switch (Opc) {
15341   case X86::ATOMNAND6432:
15342     ExtraOpc = X86::NOT32r;
15343     HiOpc = X86::AND32rr;
15344     return X86::AND32rr;
15345   }
15346   llvm_unreachable("Unhandled atomic-load-op opcode!");
15347 }
15348
15349 // Get pseudo CMOV opcode from the specified data type.
15350 static unsigned getPseudoCMOVOpc(EVT VT) {
15351   switch (VT.getSimpleVT().SimpleTy) {
15352   case MVT::i8:  return X86::CMOV_GR8;
15353   case MVT::i16: return X86::CMOV_GR16;
15354   case MVT::i32: return X86::CMOV_GR32;
15355   default:
15356     break;
15357   }
15358   llvm_unreachable("Unknown CMOV opcode!");
15359 }
15360
15361 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15362 // They will be translated into a spin-loop or compare-exchange loop from
15363 //
15364 //    ...
15365 //    dst = atomic-fetch-op MI.addr, MI.val
15366 //    ...
15367 //
15368 // to
15369 //
15370 //    ...
15371 //    t1 = LOAD MI.addr
15372 // loop:
15373 //    t4 = phi(t1, t3 / loop)
15374 //    t2 = OP MI.val, t4
15375 //    EAX = t4
15376 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15377 //    t3 = EAX
15378 //    JNE loop
15379 // sink:
15380 //    dst = t3
15381 //    ...
15382 MachineBasicBlock *
15383 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15384                                        MachineBasicBlock *MBB) const {
15385   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15386   DebugLoc DL = MI->getDebugLoc();
15387
15388   MachineFunction *MF = MBB->getParent();
15389   MachineRegisterInfo &MRI = MF->getRegInfo();
15390
15391   const BasicBlock *BB = MBB->getBasicBlock();
15392   MachineFunction::iterator I = MBB;
15393   ++I;
15394
15395   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15396          "Unexpected number of operands");
15397
15398   assert(MI->hasOneMemOperand() &&
15399          "Expected atomic-load-op to have one memoperand");
15400
15401   // Memory Reference
15402   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15403   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15404
15405   unsigned DstReg, SrcReg;
15406   unsigned MemOpndSlot;
15407
15408   unsigned CurOp = 0;
15409
15410   DstReg = MI->getOperand(CurOp++).getReg();
15411   MemOpndSlot = CurOp;
15412   CurOp += X86::AddrNumOperands;
15413   SrcReg = MI->getOperand(CurOp++).getReg();
15414
15415   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15416   MVT::SimpleValueType VT = *RC->vt_begin();
15417   unsigned t1 = MRI.createVirtualRegister(RC);
15418   unsigned t2 = MRI.createVirtualRegister(RC);
15419   unsigned t3 = MRI.createVirtualRegister(RC);
15420   unsigned t4 = MRI.createVirtualRegister(RC);
15421   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15422
15423   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15424   unsigned LOADOpc = getLoadOpcode(VT);
15425
15426   // For the atomic load-arith operator, we generate
15427   //
15428   //  thisMBB:
15429   //    t1 = LOAD [MI.addr]
15430   //  mainMBB:
15431   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15432   //    t1 = OP MI.val, EAX
15433   //    EAX = t4
15434   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15435   //    t3 = EAX
15436   //    JNE mainMBB
15437   //  sinkMBB:
15438   //    dst = t3
15439
15440   MachineBasicBlock *thisMBB = MBB;
15441   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15442   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15443   MF->insert(I, mainMBB);
15444   MF->insert(I, sinkMBB);
15445
15446   MachineInstrBuilder MIB;
15447
15448   // Transfer the remainder of BB and its successor edges to sinkMBB.
15449   sinkMBB->splice(sinkMBB->begin(), MBB,
15450                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15451   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15452
15453   // thisMBB:
15454   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15455   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15456     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15457     if (NewMO.isReg())
15458       NewMO.setIsKill(false);
15459     MIB.addOperand(NewMO);
15460   }
15461   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15462     unsigned flags = (*MMOI)->getFlags();
15463     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15464     MachineMemOperand *MMO =
15465       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15466                                (*MMOI)->getSize(),
15467                                (*MMOI)->getBaseAlignment(),
15468                                (*MMOI)->getTBAAInfo(),
15469                                (*MMOI)->getRanges());
15470     MIB.addMemOperand(MMO);
15471   }
15472
15473   thisMBB->addSuccessor(mainMBB);
15474
15475   // mainMBB:
15476   MachineBasicBlock *origMainMBB = mainMBB;
15477
15478   // Add a PHI.
15479   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15480                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15481
15482   unsigned Opc = MI->getOpcode();
15483   switch (Opc) {
15484   default:
15485     llvm_unreachable("Unhandled atomic-load-op opcode!");
15486   case X86::ATOMAND8:
15487   case X86::ATOMAND16:
15488   case X86::ATOMAND32:
15489   case X86::ATOMAND64:
15490   case X86::ATOMOR8:
15491   case X86::ATOMOR16:
15492   case X86::ATOMOR32:
15493   case X86::ATOMOR64:
15494   case X86::ATOMXOR8:
15495   case X86::ATOMXOR16:
15496   case X86::ATOMXOR32:
15497   case X86::ATOMXOR64: {
15498     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15499     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15500       .addReg(t4);
15501     break;
15502   }
15503   case X86::ATOMNAND8:
15504   case X86::ATOMNAND16:
15505   case X86::ATOMNAND32:
15506   case X86::ATOMNAND64: {
15507     unsigned Tmp = MRI.createVirtualRegister(RC);
15508     unsigned NOTOpc;
15509     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15510     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15511       .addReg(t4);
15512     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15513     break;
15514   }
15515   case X86::ATOMMAX8:
15516   case X86::ATOMMAX16:
15517   case X86::ATOMMAX32:
15518   case X86::ATOMMAX64:
15519   case X86::ATOMMIN8:
15520   case X86::ATOMMIN16:
15521   case X86::ATOMMIN32:
15522   case X86::ATOMMIN64:
15523   case X86::ATOMUMAX8:
15524   case X86::ATOMUMAX16:
15525   case X86::ATOMUMAX32:
15526   case X86::ATOMUMAX64:
15527   case X86::ATOMUMIN8:
15528   case X86::ATOMUMIN16:
15529   case X86::ATOMUMIN32:
15530   case X86::ATOMUMIN64: {
15531     unsigned CMPOpc;
15532     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15533
15534     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15535       .addReg(SrcReg)
15536       .addReg(t4);
15537
15538     if (Subtarget->hasCMov()) {
15539       if (VT != MVT::i8) {
15540         // Native support
15541         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15542           .addReg(SrcReg)
15543           .addReg(t4);
15544       } else {
15545         // Promote i8 to i32 to use CMOV32
15546         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15547         const TargetRegisterClass *RC32 =
15548           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15549         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15550         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15551         unsigned Tmp = MRI.createVirtualRegister(RC32);
15552
15553         unsigned Undef = MRI.createVirtualRegister(RC32);
15554         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15555
15556         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15557           .addReg(Undef)
15558           .addReg(SrcReg)
15559           .addImm(X86::sub_8bit);
15560         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15561           .addReg(Undef)
15562           .addReg(t4)
15563           .addImm(X86::sub_8bit);
15564
15565         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15566           .addReg(SrcReg32)
15567           .addReg(AccReg32);
15568
15569         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15570           .addReg(Tmp, 0, X86::sub_8bit);
15571       }
15572     } else {
15573       // Use pseudo select and lower them.
15574       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15575              "Invalid atomic-load-op transformation!");
15576       unsigned SelOpc = getPseudoCMOVOpc(VT);
15577       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15578       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15579       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15580               .addReg(SrcReg).addReg(t4)
15581               .addImm(CC);
15582       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15583       // Replace the original PHI node as mainMBB is changed after CMOV
15584       // lowering.
15585       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15586         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15587       Phi->eraseFromParent();
15588     }
15589     break;
15590   }
15591   }
15592
15593   // Copy PhyReg back from virtual register.
15594   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15595     .addReg(t4);
15596
15597   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15598   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15599     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15600     if (NewMO.isReg())
15601       NewMO.setIsKill(false);
15602     MIB.addOperand(NewMO);
15603   }
15604   MIB.addReg(t2);
15605   MIB.setMemRefs(MMOBegin, MMOEnd);
15606
15607   // Copy PhyReg back to virtual register.
15608   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15609     .addReg(PhyReg);
15610
15611   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15612
15613   mainMBB->addSuccessor(origMainMBB);
15614   mainMBB->addSuccessor(sinkMBB);
15615
15616   // sinkMBB:
15617   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15618           TII->get(TargetOpcode::COPY), DstReg)
15619     .addReg(t3);
15620
15621   MI->eraseFromParent();
15622   return sinkMBB;
15623 }
15624
15625 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15626 // instructions. They will be translated into a spin-loop or compare-exchange
15627 // loop from
15628 //
15629 //    ...
15630 //    dst = atomic-fetch-op MI.addr, MI.val
15631 //    ...
15632 //
15633 // to
15634 //
15635 //    ...
15636 //    t1L = LOAD [MI.addr + 0]
15637 //    t1H = LOAD [MI.addr + 4]
15638 // loop:
15639 //    t4L = phi(t1L, t3L / loop)
15640 //    t4H = phi(t1H, t3H / loop)
15641 //    t2L = OP MI.val.lo, t4L
15642 //    t2H = OP MI.val.hi, t4H
15643 //    EAX = t4L
15644 //    EDX = t4H
15645 //    EBX = t2L
15646 //    ECX = t2H
15647 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15648 //    t3L = EAX
15649 //    t3H = EDX
15650 //    JNE loop
15651 // sink:
15652 //    dstL = t3L
15653 //    dstH = t3H
15654 //    ...
15655 MachineBasicBlock *
15656 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15657                                            MachineBasicBlock *MBB) const {
15658   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15659   DebugLoc DL = MI->getDebugLoc();
15660
15661   MachineFunction *MF = MBB->getParent();
15662   MachineRegisterInfo &MRI = MF->getRegInfo();
15663
15664   const BasicBlock *BB = MBB->getBasicBlock();
15665   MachineFunction::iterator I = MBB;
15666   ++I;
15667
15668   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15669          "Unexpected number of operands");
15670
15671   assert(MI->hasOneMemOperand() &&
15672          "Expected atomic-load-op32 to have one memoperand");
15673
15674   // Memory Reference
15675   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15676   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15677
15678   unsigned DstLoReg, DstHiReg;
15679   unsigned SrcLoReg, SrcHiReg;
15680   unsigned MemOpndSlot;
15681
15682   unsigned CurOp = 0;
15683
15684   DstLoReg = MI->getOperand(CurOp++).getReg();
15685   DstHiReg = MI->getOperand(CurOp++).getReg();
15686   MemOpndSlot = CurOp;
15687   CurOp += X86::AddrNumOperands;
15688   SrcLoReg = MI->getOperand(CurOp++).getReg();
15689   SrcHiReg = MI->getOperand(CurOp++).getReg();
15690
15691   const TargetRegisterClass *RC = &X86::GR32RegClass;
15692   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15693
15694   unsigned t1L = MRI.createVirtualRegister(RC);
15695   unsigned t1H = MRI.createVirtualRegister(RC);
15696   unsigned t2L = MRI.createVirtualRegister(RC);
15697   unsigned t2H = MRI.createVirtualRegister(RC);
15698   unsigned t3L = MRI.createVirtualRegister(RC);
15699   unsigned t3H = MRI.createVirtualRegister(RC);
15700   unsigned t4L = MRI.createVirtualRegister(RC);
15701   unsigned t4H = MRI.createVirtualRegister(RC);
15702
15703   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15704   unsigned LOADOpc = X86::MOV32rm;
15705
15706   // For the atomic load-arith operator, we generate
15707   //
15708   //  thisMBB:
15709   //    t1L = LOAD [MI.addr + 0]
15710   //    t1H = LOAD [MI.addr + 4]
15711   //  mainMBB:
15712   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15713   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15714   //    t2L = OP MI.val.lo, t4L
15715   //    t2H = OP MI.val.hi, t4H
15716   //    EBX = t2L
15717   //    ECX = t2H
15718   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15719   //    t3L = EAX
15720   //    t3H = EDX
15721   //    JNE loop
15722   //  sinkMBB:
15723   //    dstL = t3L
15724   //    dstH = t3H
15725
15726   MachineBasicBlock *thisMBB = MBB;
15727   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15728   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15729   MF->insert(I, mainMBB);
15730   MF->insert(I, sinkMBB);
15731
15732   MachineInstrBuilder MIB;
15733
15734   // Transfer the remainder of BB and its successor edges to sinkMBB.
15735   sinkMBB->splice(sinkMBB->begin(), MBB,
15736                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15737   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15738
15739   // thisMBB:
15740   // Lo
15741   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15742   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15743     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15744     if (NewMO.isReg())
15745       NewMO.setIsKill(false);
15746     MIB.addOperand(NewMO);
15747   }
15748   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15749     unsigned flags = (*MMOI)->getFlags();
15750     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15751     MachineMemOperand *MMO =
15752       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15753                                (*MMOI)->getSize(),
15754                                (*MMOI)->getBaseAlignment(),
15755                                (*MMOI)->getTBAAInfo(),
15756                                (*MMOI)->getRanges());
15757     MIB.addMemOperand(MMO);
15758   };
15759   MachineInstr *LowMI = MIB;
15760
15761   // Hi
15762   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15763   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15764     if (i == X86::AddrDisp) {
15765       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15766     } else {
15767       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15768       if (NewMO.isReg())
15769         NewMO.setIsKill(false);
15770       MIB.addOperand(NewMO);
15771     }
15772   }
15773   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15774
15775   thisMBB->addSuccessor(mainMBB);
15776
15777   // mainMBB:
15778   MachineBasicBlock *origMainMBB = mainMBB;
15779
15780   // Add PHIs.
15781   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15782                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15783   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15784                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15785
15786   unsigned Opc = MI->getOpcode();
15787   switch (Opc) {
15788   default:
15789     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15790   case X86::ATOMAND6432:
15791   case X86::ATOMOR6432:
15792   case X86::ATOMXOR6432:
15793   case X86::ATOMADD6432:
15794   case X86::ATOMSUB6432: {
15795     unsigned HiOpc;
15796     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15797     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15798       .addReg(SrcLoReg);
15799     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15800       .addReg(SrcHiReg);
15801     break;
15802   }
15803   case X86::ATOMNAND6432: {
15804     unsigned HiOpc, NOTOpc;
15805     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15806     unsigned TmpL = MRI.createVirtualRegister(RC);
15807     unsigned TmpH = MRI.createVirtualRegister(RC);
15808     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15809       .addReg(t4L);
15810     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15811       .addReg(t4H);
15812     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15813     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15814     break;
15815   }
15816   case X86::ATOMMAX6432:
15817   case X86::ATOMMIN6432:
15818   case X86::ATOMUMAX6432:
15819   case X86::ATOMUMIN6432: {
15820     unsigned HiOpc;
15821     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15822     unsigned cL = MRI.createVirtualRegister(RC8);
15823     unsigned cH = MRI.createVirtualRegister(RC8);
15824     unsigned cL32 = MRI.createVirtualRegister(RC);
15825     unsigned cH32 = MRI.createVirtualRegister(RC);
15826     unsigned cc = MRI.createVirtualRegister(RC);
15827     // cl := cmp src_lo, lo
15828     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15829       .addReg(SrcLoReg).addReg(t4L);
15830     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15831     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15832     // ch := cmp src_hi, hi
15833     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15834       .addReg(SrcHiReg).addReg(t4H);
15835     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15836     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15837     // cc := if (src_hi == hi) ? cl : ch;
15838     if (Subtarget->hasCMov()) {
15839       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15840         .addReg(cH32).addReg(cL32);
15841     } else {
15842       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15843               .addReg(cH32).addReg(cL32)
15844               .addImm(X86::COND_E);
15845       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15846     }
15847     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15848     if (Subtarget->hasCMov()) {
15849       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15850         .addReg(SrcLoReg).addReg(t4L);
15851       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15852         .addReg(SrcHiReg).addReg(t4H);
15853     } else {
15854       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15855               .addReg(SrcLoReg).addReg(t4L)
15856               .addImm(X86::COND_NE);
15857       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15858       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15859       // 2nd CMOV lowering.
15860       mainMBB->addLiveIn(X86::EFLAGS);
15861       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15862               .addReg(SrcHiReg).addReg(t4H)
15863               .addImm(X86::COND_NE);
15864       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15865       // Replace the original PHI node as mainMBB is changed after CMOV
15866       // lowering.
15867       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15868         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15869       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15870         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15871       PhiL->eraseFromParent();
15872       PhiH->eraseFromParent();
15873     }
15874     break;
15875   }
15876   case X86::ATOMSWAP6432: {
15877     unsigned HiOpc;
15878     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15879     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15880     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15881     break;
15882   }
15883   }
15884
15885   // Copy EDX:EAX back from HiReg:LoReg
15886   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15887   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15888   // Copy ECX:EBX from t1H:t1L
15889   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15890   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15891
15892   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15893   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15894     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15895     if (NewMO.isReg())
15896       NewMO.setIsKill(false);
15897     MIB.addOperand(NewMO);
15898   }
15899   MIB.setMemRefs(MMOBegin, MMOEnd);
15900
15901   // Copy EDX:EAX back to t3H:t3L
15902   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15903   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15904
15905   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15906
15907   mainMBB->addSuccessor(origMainMBB);
15908   mainMBB->addSuccessor(sinkMBB);
15909
15910   // sinkMBB:
15911   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15912           TII->get(TargetOpcode::COPY), DstLoReg)
15913     .addReg(t3L);
15914   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15915           TII->get(TargetOpcode::COPY), DstHiReg)
15916     .addReg(t3H);
15917
15918   MI->eraseFromParent();
15919   return sinkMBB;
15920 }
15921
15922 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15923 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15924 // in the .td file.
15925 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15926                                        const TargetInstrInfo *TII) {
15927   unsigned Opc;
15928   switch (MI->getOpcode()) {
15929   default: llvm_unreachable("illegal opcode!");
15930   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15931   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15932   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15933   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15934   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15935   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15936   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15937   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15938   }
15939
15940   DebugLoc dl = MI->getDebugLoc();
15941   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15942
15943   unsigned NumArgs = MI->getNumOperands();
15944   for (unsigned i = 1; i < NumArgs; ++i) {
15945     MachineOperand &Op = MI->getOperand(i);
15946     if (!(Op.isReg() && Op.isImplicit()))
15947       MIB.addOperand(Op);
15948   }
15949   if (MI->hasOneMemOperand())
15950     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15951
15952   BuildMI(*BB, MI, dl,
15953     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15954     .addReg(X86::XMM0);
15955
15956   MI->eraseFromParent();
15957   return BB;
15958 }
15959
15960 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15961 // defs in an instruction pattern
15962 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15963                                        const TargetInstrInfo *TII) {
15964   unsigned Opc;
15965   switch (MI->getOpcode()) {
15966   default: llvm_unreachable("illegal opcode!");
15967   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15968   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15969   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15970   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15971   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15972   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15973   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15974   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15975   }
15976
15977   DebugLoc dl = MI->getDebugLoc();
15978   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15979
15980   unsigned NumArgs = MI->getNumOperands(); // remove the results
15981   for (unsigned i = 1; i < NumArgs; ++i) {
15982     MachineOperand &Op = MI->getOperand(i);
15983     if (!(Op.isReg() && Op.isImplicit()))
15984       MIB.addOperand(Op);
15985   }
15986   if (MI->hasOneMemOperand())
15987     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15988
15989   BuildMI(*BB, MI, dl,
15990     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15991     .addReg(X86::ECX);
15992
15993   MI->eraseFromParent();
15994   return BB;
15995 }
15996
15997 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15998                                        const TargetInstrInfo *TII,
15999                                        const X86Subtarget* Subtarget) {
16000   DebugLoc dl = MI->getDebugLoc();
16001
16002   // Address into RAX/EAX, other two args into ECX, EDX.
16003   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16004   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16005   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16006   for (int i = 0; i < X86::AddrNumOperands; ++i)
16007     MIB.addOperand(MI->getOperand(i));
16008
16009   unsigned ValOps = X86::AddrNumOperands;
16010   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16011     .addReg(MI->getOperand(ValOps).getReg());
16012   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16013     .addReg(MI->getOperand(ValOps+1).getReg());
16014
16015   // The instruction doesn't actually take any operands though.
16016   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16017
16018   MI->eraseFromParent(); // The pseudo is gone now.
16019   return BB;
16020 }
16021
16022 MachineBasicBlock *
16023 X86TargetLowering::EmitVAARG64WithCustomInserter(
16024                    MachineInstr *MI,
16025                    MachineBasicBlock *MBB) const {
16026   // Emit va_arg instruction on X86-64.
16027
16028   // Operands to this pseudo-instruction:
16029   // 0  ) Output        : destination address (reg)
16030   // 1-5) Input         : va_list address (addr, i64mem)
16031   // 6  ) ArgSize       : Size (in bytes) of vararg type
16032   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16033   // 8  ) Align         : Alignment of type
16034   // 9  ) EFLAGS (implicit-def)
16035
16036   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16037   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16038
16039   unsigned DestReg = MI->getOperand(0).getReg();
16040   MachineOperand &Base = MI->getOperand(1);
16041   MachineOperand &Scale = MI->getOperand(2);
16042   MachineOperand &Index = MI->getOperand(3);
16043   MachineOperand &Disp = MI->getOperand(4);
16044   MachineOperand &Segment = MI->getOperand(5);
16045   unsigned ArgSize = MI->getOperand(6).getImm();
16046   unsigned ArgMode = MI->getOperand(7).getImm();
16047   unsigned Align = MI->getOperand(8).getImm();
16048
16049   // Memory Reference
16050   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16051   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16052   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16053
16054   // Machine Information
16055   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16056   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16057   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16058   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16059   DebugLoc DL = MI->getDebugLoc();
16060
16061   // struct va_list {
16062   //   i32   gp_offset
16063   //   i32   fp_offset
16064   //   i64   overflow_area (address)
16065   //   i64   reg_save_area (address)
16066   // }
16067   // sizeof(va_list) = 24
16068   // alignment(va_list) = 8
16069
16070   unsigned TotalNumIntRegs = 6;
16071   unsigned TotalNumXMMRegs = 8;
16072   bool UseGPOffset = (ArgMode == 1);
16073   bool UseFPOffset = (ArgMode == 2);
16074   unsigned MaxOffset = TotalNumIntRegs * 8 +
16075                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16076
16077   /* Align ArgSize to a multiple of 8 */
16078   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16079   bool NeedsAlign = (Align > 8);
16080
16081   MachineBasicBlock *thisMBB = MBB;
16082   MachineBasicBlock *overflowMBB;
16083   MachineBasicBlock *offsetMBB;
16084   MachineBasicBlock *endMBB;
16085
16086   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16087   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16088   unsigned OffsetReg = 0;
16089
16090   if (!UseGPOffset && !UseFPOffset) {
16091     // If we only pull from the overflow region, we don't create a branch.
16092     // We don't need to alter control flow.
16093     OffsetDestReg = 0; // unused
16094     OverflowDestReg = DestReg;
16095
16096     offsetMBB = nullptr;
16097     overflowMBB = thisMBB;
16098     endMBB = thisMBB;
16099   } else {
16100     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16101     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16102     // If not, pull from overflow_area. (branch to overflowMBB)
16103     //
16104     //       thisMBB
16105     //         |     .
16106     //         |        .
16107     //     offsetMBB   overflowMBB
16108     //         |        .
16109     //         |     .
16110     //        endMBB
16111
16112     // Registers for the PHI in endMBB
16113     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16114     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16115
16116     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16117     MachineFunction *MF = MBB->getParent();
16118     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16119     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16120     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16121
16122     MachineFunction::iterator MBBIter = MBB;
16123     ++MBBIter;
16124
16125     // Insert the new basic blocks
16126     MF->insert(MBBIter, offsetMBB);
16127     MF->insert(MBBIter, overflowMBB);
16128     MF->insert(MBBIter, endMBB);
16129
16130     // Transfer the remainder of MBB and its successor edges to endMBB.
16131     endMBB->splice(endMBB->begin(), thisMBB,
16132                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16133     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16134
16135     // Make offsetMBB and overflowMBB successors of thisMBB
16136     thisMBB->addSuccessor(offsetMBB);
16137     thisMBB->addSuccessor(overflowMBB);
16138
16139     // endMBB is a successor of both offsetMBB and overflowMBB
16140     offsetMBB->addSuccessor(endMBB);
16141     overflowMBB->addSuccessor(endMBB);
16142
16143     // Load the offset value into a register
16144     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16145     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16146       .addOperand(Base)
16147       .addOperand(Scale)
16148       .addOperand(Index)
16149       .addDisp(Disp, UseFPOffset ? 4 : 0)
16150       .addOperand(Segment)
16151       .setMemRefs(MMOBegin, MMOEnd);
16152
16153     // Check if there is enough room left to pull this argument.
16154     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16155       .addReg(OffsetReg)
16156       .addImm(MaxOffset + 8 - ArgSizeA8);
16157
16158     // Branch to "overflowMBB" if offset >= max
16159     // Fall through to "offsetMBB" otherwise
16160     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16161       .addMBB(overflowMBB);
16162   }
16163
16164   // In offsetMBB, emit code to use the reg_save_area.
16165   if (offsetMBB) {
16166     assert(OffsetReg != 0);
16167
16168     // Read the reg_save_area address.
16169     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16170     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16171       .addOperand(Base)
16172       .addOperand(Scale)
16173       .addOperand(Index)
16174       .addDisp(Disp, 16)
16175       .addOperand(Segment)
16176       .setMemRefs(MMOBegin, MMOEnd);
16177
16178     // Zero-extend the offset
16179     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16180       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16181         .addImm(0)
16182         .addReg(OffsetReg)
16183         .addImm(X86::sub_32bit);
16184
16185     // Add the offset to the reg_save_area to get the final address.
16186     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16187       .addReg(OffsetReg64)
16188       .addReg(RegSaveReg);
16189
16190     // Compute the offset for the next argument
16191     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16192     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16193       .addReg(OffsetReg)
16194       .addImm(UseFPOffset ? 16 : 8);
16195
16196     // Store it back into the va_list.
16197     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16198       .addOperand(Base)
16199       .addOperand(Scale)
16200       .addOperand(Index)
16201       .addDisp(Disp, UseFPOffset ? 4 : 0)
16202       .addOperand(Segment)
16203       .addReg(NextOffsetReg)
16204       .setMemRefs(MMOBegin, MMOEnd);
16205
16206     // Jump to endMBB
16207     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16208       .addMBB(endMBB);
16209   }
16210
16211   //
16212   // Emit code to use overflow area
16213   //
16214
16215   // Load the overflow_area address into a register.
16216   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16217   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16218     .addOperand(Base)
16219     .addOperand(Scale)
16220     .addOperand(Index)
16221     .addDisp(Disp, 8)
16222     .addOperand(Segment)
16223     .setMemRefs(MMOBegin, MMOEnd);
16224
16225   // If we need to align it, do so. Otherwise, just copy the address
16226   // to OverflowDestReg.
16227   if (NeedsAlign) {
16228     // Align the overflow address
16229     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16230     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16231
16232     // aligned_addr = (addr + (align-1)) & ~(align-1)
16233     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16234       .addReg(OverflowAddrReg)
16235       .addImm(Align-1);
16236
16237     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16238       .addReg(TmpReg)
16239       .addImm(~(uint64_t)(Align-1));
16240   } else {
16241     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16242       .addReg(OverflowAddrReg);
16243   }
16244
16245   // Compute the next overflow address after this argument.
16246   // (the overflow address should be kept 8-byte aligned)
16247   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16248   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16249     .addReg(OverflowDestReg)
16250     .addImm(ArgSizeA8);
16251
16252   // Store the new overflow address.
16253   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16254     .addOperand(Base)
16255     .addOperand(Scale)
16256     .addOperand(Index)
16257     .addDisp(Disp, 8)
16258     .addOperand(Segment)
16259     .addReg(NextAddrReg)
16260     .setMemRefs(MMOBegin, MMOEnd);
16261
16262   // If we branched, emit the PHI to the front of endMBB.
16263   if (offsetMBB) {
16264     BuildMI(*endMBB, endMBB->begin(), DL,
16265             TII->get(X86::PHI), DestReg)
16266       .addReg(OffsetDestReg).addMBB(offsetMBB)
16267       .addReg(OverflowDestReg).addMBB(overflowMBB);
16268   }
16269
16270   // Erase the pseudo instruction
16271   MI->eraseFromParent();
16272
16273   return endMBB;
16274 }
16275
16276 MachineBasicBlock *
16277 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16278                                                  MachineInstr *MI,
16279                                                  MachineBasicBlock *MBB) const {
16280   // Emit code to save XMM registers to the stack. The ABI says that the
16281   // number of registers to save is given in %al, so it's theoretically
16282   // possible to do an indirect jump trick to avoid saving all of them,
16283   // however this code takes a simpler approach and just executes all
16284   // of the stores if %al is non-zero. It's less code, and it's probably
16285   // easier on the hardware branch predictor, and stores aren't all that
16286   // expensive anyway.
16287
16288   // Create the new basic blocks. One block contains all the XMM stores,
16289   // and one block is the final destination regardless of whether any
16290   // stores were performed.
16291   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16292   MachineFunction *F = MBB->getParent();
16293   MachineFunction::iterator MBBIter = MBB;
16294   ++MBBIter;
16295   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16296   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16297   F->insert(MBBIter, XMMSaveMBB);
16298   F->insert(MBBIter, EndMBB);
16299
16300   // Transfer the remainder of MBB and its successor edges to EndMBB.
16301   EndMBB->splice(EndMBB->begin(), MBB,
16302                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16303   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16304
16305   // The original block will now fall through to the XMM save block.
16306   MBB->addSuccessor(XMMSaveMBB);
16307   // The XMMSaveMBB will fall through to the end block.
16308   XMMSaveMBB->addSuccessor(EndMBB);
16309
16310   // Now add the instructions.
16311   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16312   DebugLoc DL = MI->getDebugLoc();
16313
16314   unsigned CountReg = MI->getOperand(0).getReg();
16315   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16316   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16317
16318   if (!Subtarget->isTargetWin64()) {
16319     // If %al is 0, branch around the XMM save block.
16320     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16321     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16322     MBB->addSuccessor(EndMBB);
16323   }
16324
16325   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16326   // that was just emitted, but clearly shouldn't be "saved".
16327   assert((MI->getNumOperands() <= 3 ||
16328           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16329           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16330          && "Expected last argument to be EFLAGS");
16331   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16332   // In the XMM save block, save all the XMM argument registers.
16333   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16334     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16335     MachineMemOperand *MMO =
16336       F->getMachineMemOperand(
16337           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16338         MachineMemOperand::MOStore,
16339         /*Size=*/16, /*Align=*/16);
16340     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16341       .addFrameIndex(RegSaveFrameIndex)
16342       .addImm(/*Scale=*/1)
16343       .addReg(/*IndexReg=*/0)
16344       .addImm(/*Disp=*/Offset)
16345       .addReg(/*Segment=*/0)
16346       .addReg(MI->getOperand(i).getReg())
16347       .addMemOperand(MMO);
16348   }
16349
16350   MI->eraseFromParent();   // The pseudo instruction is gone now.
16351
16352   return EndMBB;
16353 }
16354
16355 // The EFLAGS operand of SelectItr might be missing a kill marker
16356 // because there were multiple uses of EFLAGS, and ISel didn't know
16357 // which to mark. Figure out whether SelectItr should have had a
16358 // kill marker, and set it if it should. Returns the correct kill
16359 // marker value.
16360 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16361                                      MachineBasicBlock* BB,
16362                                      const TargetRegisterInfo* TRI) {
16363   // Scan forward through BB for a use/def of EFLAGS.
16364   MachineBasicBlock::iterator miI(std::next(SelectItr));
16365   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16366     const MachineInstr& mi = *miI;
16367     if (mi.readsRegister(X86::EFLAGS))
16368       return false;
16369     if (mi.definesRegister(X86::EFLAGS))
16370       break; // Should have kill-flag - update below.
16371   }
16372
16373   // If we hit the end of the block, check whether EFLAGS is live into a
16374   // successor.
16375   if (miI == BB->end()) {
16376     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16377                                           sEnd = BB->succ_end();
16378          sItr != sEnd; ++sItr) {
16379       MachineBasicBlock* succ = *sItr;
16380       if (succ->isLiveIn(X86::EFLAGS))
16381         return false;
16382     }
16383   }
16384
16385   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16386   // out. SelectMI should have a kill flag on EFLAGS.
16387   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16388   return true;
16389 }
16390
16391 MachineBasicBlock *
16392 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16393                                      MachineBasicBlock *BB) const {
16394   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16395   DebugLoc DL = MI->getDebugLoc();
16396
16397   // To "insert" a SELECT_CC instruction, we actually have to insert the
16398   // diamond control-flow pattern.  The incoming instruction knows the
16399   // destination vreg to set, the condition code register to branch on, the
16400   // true/false values to select between, and a branch opcode to use.
16401   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16402   MachineFunction::iterator It = BB;
16403   ++It;
16404
16405   //  thisMBB:
16406   //  ...
16407   //   TrueVal = ...
16408   //   cmpTY ccX, r1, r2
16409   //   bCC copy1MBB
16410   //   fallthrough --> copy0MBB
16411   MachineBasicBlock *thisMBB = BB;
16412   MachineFunction *F = BB->getParent();
16413   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16414   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16415   F->insert(It, copy0MBB);
16416   F->insert(It, sinkMBB);
16417
16418   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16419   // live into the sink and copy blocks.
16420   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16421   if (!MI->killsRegister(X86::EFLAGS) &&
16422       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16423     copy0MBB->addLiveIn(X86::EFLAGS);
16424     sinkMBB->addLiveIn(X86::EFLAGS);
16425   }
16426
16427   // Transfer the remainder of BB and its successor edges to sinkMBB.
16428   sinkMBB->splice(sinkMBB->begin(), BB,
16429                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16430   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16431
16432   // Add the true and fallthrough blocks as its successors.
16433   BB->addSuccessor(copy0MBB);
16434   BB->addSuccessor(sinkMBB);
16435
16436   // Create the conditional branch instruction.
16437   unsigned Opc =
16438     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16439   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16440
16441   //  copy0MBB:
16442   //   %FalseValue = ...
16443   //   # fallthrough to sinkMBB
16444   copy0MBB->addSuccessor(sinkMBB);
16445
16446   //  sinkMBB:
16447   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16448   //  ...
16449   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16450           TII->get(X86::PHI), MI->getOperand(0).getReg())
16451     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16452     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16453
16454   MI->eraseFromParent();   // The pseudo instruction is gone now.
16455   return sinkMBB;
16456 }
16457
16458 MachineBasicBlock *
16459 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16460                                         bool Is64Bit) const {
16461   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16462   DebugLoc DL = MI->getDebugLoc();
16463   MachineFunction *MF = BB->getParent();
16464   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16465
16466   assert(MF->shouldSplitStack());
16467
16468   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16469   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16470
16471   // BB:
16472   //  ... [Till the alloca]
16473   // If stacklet is not large enough, jump to mallocMBB
16474   //
16475   // bumpMBB:
16476   //  Allocate by subtracting from RSP
16477   //  Jump to continueMBB
16478   //
16479   // mallocMBB:
16480   //  Allocate by call to runtime
16481   //
16482   // continueMBB:
16483   //  ...
16484   //  [rest of original BB]
16485   //
16486
16487   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16488   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16489   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16490
16491   MachineRegisterInfo &MRI = MF->getRegInfo();
16492   const TargetRegisterClass *AddrRegClass =
16493     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16494
16495   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16496     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16497     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16498     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16499     sizeVReg = MI->getOperand(1).getReg(),
16500     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16501
16502   MachineFunction::iterator MBBIter = BB;
16503   ++MBBIter;
16504
16505   MF->insert(MBBIter, bumpMBB);
16506   MF->insert(MBBIter, mallocMBB);
16507   MF->insert(MBBIter, continueMBB);
16508
16509   continueMBB->splice(continueMBB->begin(), BB,
16510                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16511   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16512
16513   // Add code to the main basic block to check if the stack limit has been hit,
16514   // and if so, jump to mallocMBB otherwise to bumpMBB.
16515   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16516   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16517     .addReg(tmpSPVReg).addReg(sizeVReg);
16518   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16519     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16520     .addReg(SPLimitVReg);
16521   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16522
16523   // bumpMBB simply decreases the stack pointer, since we know the current
16524   // stacklet has enough space.
16525   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16526     .addReg(SPLimitVReg);
16527   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16528     .addReg(SPLimitVReg);
16529   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16530
16531   // Calls into a routine in libgcc to allocate more space from the heap.
16532   const uint32_t *RegMask =
16533     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16534   if (Is64Bit) {
16535     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16536       .addReg(sizeVReg);
16537     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16538       .addExternalSymbol("__morestack_allocate_stack_space")
16539       .addRegMask(RegMask)
16540       .addReg(X86::RDI, RegState::Implicit)
16541       .addReg(X86::RAX, RegState::ImplicitDefine);
16542   } else {
16543     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16544       .addImm(12);
16545     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16546     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16547       .addExternalSymbol("__morestack_allocate_stack_space")
16548       .addRegMask(RegMask)
16549       .addReg(X86::EAX, RegState::ImplicitDefine);
16550   }
16551
16552   if (!Is64Bit)
16553     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16554       .addImm(16);
16555
16556   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16557     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16558   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16559
16560   // Set up the CFG correctly.
16561   BB->addSuccessor(bumpMBB);
16562   BB->addSuccessor(mallocMBB);
16563   mallocMBB->addSuccessor(continueMBB);
16564   bumpMBB->addSuccessor(continueMBB);
16565
16566   // Take care of the PHI nodes.
16567   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16568           MI->getOperand(0).getReg())
16569     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16570     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16571
16572   // Delete the original pseudo instruction.
16573   MI->eraseFromParent();
16574
16575   // And we're done.
16576   return continueMBB;
16577 }
16578
16579 MachineBasicBlock *
16580 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16581                                           MachineBasicBlock *BB) const {
16582   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16583   DebugLoc DL = MI->getDebugLoc();
16584
16585   assert(!Subtarget->isTargetMacho());
16586
16587   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16588   // non-trivial part is impdef of ESP.
16589
16590   if (Subtarget->isTargetWin64()) {
16591     if (Subtarget->isTargetCygMing()) {
16592       // ___chkstk(Mingw64):
16593       // Clobbers R10, R11, RAX and EFLAGS.
16594       // Updates RSP.
16595       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16596         .addExternalSymbol("___chkstk")
16597         .addReg(X86::RAX, RegState::Implicit)
16598         .addReg(X86::RSP, RegState::Implicit)
16599         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16600         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16601         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16602     } else {
16603       // __chkstk(MSVCRT): does not update stack pointer.
16604       // Clobbers R10, R11 and EFLAGS.
16605       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16606         .addExternalSymbol("__chkstk")
16607         .addReg(X86::RAX, RegState::Implicit)
16608         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16609       // RAX has the offset to be subtracted from RSP.
16610       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16611         .addReg(X86::RSP)
16612         .addReg(X86::RAX);
16613     }
16614   } else {
16615     const char *StackProbeSymbol =
16616       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16617
16618     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16619       .addExternalSymbol(StackProbeSymbol)
16620       .addReg(X86::EAX, RegState::Implicit)
16621       .addReg(X86::ESP, RegState::Implicit)
16622       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16623       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16624       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16625   }
16626
16627   MI->eraseFromParent();   // The pseudo instruction is gone now.
16628   return BB;
16629 }
16630
16631 MachineBasicBlock *
16632 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16633                                       MachineBasicBlock *BB) const {
16634   // This is pretty easy.  We're taking the value that we received from
16635   // our load from the relocation, sticking it in either RDI (x86-64)
16636   // or EAX and doing an indirect call.  The return value will then
16637   // be in the normal return register.
16638   const X86InstrInfo *TII
16639     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16640   DebugLoc DL = MI->getDebugLoc();
16641   MachineFunction *F = BB->getParent();
16642
16643   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16644   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16645
16646   // Get a register mask for the lowered call.
16647   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16648   // proper register mask.
16649   const uint32_t *RegMask =
16650     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16651   if (Subtarget->is64Bit()) {
16652     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16653                                       TII->get(X86::MOV64rm), X86::RDI)
16654     .addReg(X86::RIP)
16655     .addImm(0).addReg(0)
16656     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16657                       MI->getOperand(3).getTargetFlags())
16658     .addReg(0);
16659     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16660     addDirectMem(MIB, X86::RDI);
16661     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16662   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16663     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16664                                       TII->get(X86::MOV32rm), X86::EAX)
16665     .addReg(0)
16666     .addImm(0).addReg(0)
16667     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16668                       MI->getOperand(3).getTargetFlags())
16669     .addReg(0);
16670     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16671     addDirectMem(MIB, X86::EAX);
16672     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16673   } else {
16674     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16675                                       TII->get(X86::MOV32rm), X86::EAX)
16676     .addReg(TII->getGlobalBaseReg(F))
16677     .addImm(0).addReg(0)
16678     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16679                       MI->getOperand(3).getTargetFlags())
16680     .addReg(0);
16681     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16682     addDirectMem(MIB, X86::EAX);
16683     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16684   }
16685
16686   MI->eraseFromParent(); // The pseudo instruction is gone now.
16687   return BB;
16688 }
16689
16690 MachineBasicBlock *
16691 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16692                                     MachineBasicBlock *MBB) const {
16693   DebugLoc DL = MI->getDebugLoc();
16694   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16695
16696   MachineFunction *MF = MBB->getParent();
16697   MachineRegisterInfo &MRI = MF->getRegInfo();
16698
16699   const BasicBlock *BB = MBB->getBasicBlock();
16700   MachineFunction::iterator I = MBB;
16701   ++I;
16702
16703   // Memory Reference
16704   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16705   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16706
16707   unsigned DstReg;
16708   unsigned MemOpndSlot = 0;
16709
16710   unsigned CurOp = 0;
16711
16712   DstReg = MI->getOperand(CurOp++).getReg();
16713   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16714   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16715   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16716   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16717
16718   MemOpndSlot = CurOp;
16719
16720   MVT PVT = getPointerTy();
16721   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16722          "Invalid Pointer Size!");
16723
16724   // For v = setjmp(buf), we generate
16725   //
16726   // thisMBB:
16727   //  buf[LabelOffset] = restoreMBB
16728   //  SjLjSetup restoreMBB
16729   //
16730   // mainMBB:
16731   //  v_main = 0
16732   //
16733   // sinkMBB:
16734   //  v = phi(main, restore)
16735   //
16736   // restoreMBB:
16737   //  v_restore = 1
16738
16739   MachineBasicBlock *thisMBB = MBB;
16740   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16741   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16742   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16743   MF->insert(I, mainMBB);
16744   MF->insert(I, sinkMBB);
16745   MF->push_back(restoreMBB);
16746
16747   MachineInstrBuilder MIB;
16748
16749   // Transfer the remainder of BB and its successor edges to sinkMBB.
16750   sinkMBB->splice(sinkMBB->begin(), MBB,
16751                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16752   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16753
16754   // thisMBB:
16755   unsigned PtrStoreOpc = 0;
16756   unsigned LabelReg = 0;
16757   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16758   Reloc::Model RM = getTargetMachine().getRelocationModel();
16759   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16760                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16761
16762   // Prepare IP either in reg or imm.
16763   if (!UseImmLabel) {
16764     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16765     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16766     LabelReg = MRI.createVirtualRegister(PtrRC);
16767     if (Subtarget->is64Bit()) {
16768       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16769               .addReg(X86::RIP)
16770               .addImm(0)
16771               .addReg(0)
16772               .addMBB(restoreMBB)
16773               .addReg(0);
16774     } else {
16775       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16776       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16777               .addReg(XII->getGlobalBaseReg(MF))
16778               .addImm(0)
16779               .addReg(0)
16780               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16781               .addReg(0);
16782     }
16783   } else
16784     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16785   // Store IP
16786   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16787   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16788     if (i == X86::AddrDisp)
16789       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16790     else
16791       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16792   }
16793   if (!UseImmLabel)
16794     MIB.addReg(LabelReg);
16795   else
16796     MIB.addMBB(restoreMBB);
16797   MIB.setMemRefs(MMOBegin, MMOEnd);
16798   // Setup
16799   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16800           .addMBB(restoreMBB);
16801
16802   const X86RegisterInfo *RegInfo =
16803     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16804   MIB.addRegMask(RegInfo->getNoPreservedMask());
16805   thisMBB->addSuccessor(mainMBB);
16806   thisMBB->addSuccessor(restoreMBB);
16807
16808   // mainMBB:
16809   //  EAX = 0
16810   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16811   mainMBB->addSuccessor(sinkMBB);
16812
16813   // sinkMBB:
16814   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16815           TII->get(X86::PHI), DstReg)
16816     .addReg(mainDstReg).addMBB(mainMBB)
16817     .addReg(restoreDstReg).addMBB(restoreMBB);
16818
16819   // restoreMBB:
16820   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16821   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16822   restoreMBB->addSuccessor(sinkMBB);
16823
16824   MI->eraseFromParent();
16825   return sinkMBB;
16826 }
16827
16828 MachineBasicBlock *
16829 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16830                                      MachineBasicBlock *MBB) const {
16831   DebugLoc DL = MI->getDebugLoc();
16832   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16833
16834   MachineFunction *MF = MBB->getParent();
16835   MachineRegisterInfo &MRI = MF->getRegInfo();
16836
16837   // Memory Reference
16838   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16839   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16840
16841   MVT PVT = getPointerTy();
16842   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16843          "Invalid Pointer Size!");
16844
16845   const TargetRegisterClass *RC =
16846     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16847   unsigned Tmp = MRI.createVirtualRegister(RC);
16848   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16849   const X86RegisterInfo *RegInfo =
16850     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16851   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16852   unsigned SP = RegInfo->getStackRegister();
16853
16854   MachineInstrBuilder MIB;
16855
16856   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16857   const int64_t SPOffset = 2 * PVT.getStoreSize();
16858
16859   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16860   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16861
16862   // Reload FP
16863   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16864   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16865     MIB.addOperand(MI->getOperand(i));
16866   MIB.setMemRefs(MMOBegin, MMOEnd);
16867   // Reload IP
16868   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16869   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16870     if (i == X86::AddrDisp)
16871       MIB.addDisp(MI->getOperand(i), LabelOffset);
16872     else
16873       MIB.addOperand(MI->getOperand(i));
16874   }
16875   MIB.setMemRefs(MMOBegin, MMOEnd);
16876   // Reload SP
16877   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16878   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16879     if (i == X86::AddrDisp)
16880       MIB.addDisp(MI->getOperand(i), SPOffset);
16881     else
16882       MIB.addOperand(MI->getOperand(i));
16883   }
16884   MIB.setMemRefs(MMOBegin, MMOEnd);
16885   // Jump
16886   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16887
16888   MI->eraseFromParent();
16889   return MBB;
16890 }
16891
16892 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16893 // accumulator loops. Writing back to the accumulator allows the coalescer
16894 // to remove extra copies in the loop.   
16895 MachineBasicBlock *
16896 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16897                                  MachineBasicBlock *MBB) const {
16898   MachineOperand &AddendOp = MI->getOperand(3);
16899
16900   // Bail out early if the addend isn't a register - we can't switch these.
16901   if (!AddendOp.isReg())
16902     return MBB;
16903
16904   MachineFunction &MF = *MBB->getParent();
16905   MachineRegisterInfo &MRI = MF.getRegInfo();
16906
16907   // Check whether the addend is defined by a PHI:
16908   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16909   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16910   if (!AddendDef.isPHI())
16911     return MBB;
16912
16913   // Look for the following pattern:
16914   // loop:
16915   //   %addend = phi [%entry, 0], [%loop, %result]
16916   //   ...
16917   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16918
16919   // Replace with:
16920   //   loop:
16921   //   %addend = phi [%entry, 0], [%loop, %result]
16922   //   ...
16923   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16924
16925   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16926     assert(AddendDef.getOperand(i).isReg());
16927     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16928     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16929     if (&PHISrcInst == MI) {
16930       // Found a matching instruction.
16931       unsigned NewFMAOpc = 0;
16932       switch (MI->getOpcode()) {
16933         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16934         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16935         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16936         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16937         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16938         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16939         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16940         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16941         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16942         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16943         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16944         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16945         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16946         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16947         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16948         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16949         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16950         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16951         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16952         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16953         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16954         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16955         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16956         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16957         default: llvm_unreachable("Unrecognized FMA variant.");
16958       }
16959
16960       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16961       MachineInstrBuilder MIB =
16962         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16963         .addOperand(MI->getOperand(0))
16964         .addOperand(MI->getOperand(3))
16965         .addOperand(MI->getOperand(2))
16966         .addOperand(MI->getOperand(1));
16967       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16968       MI->eraseFromParent();
16969     }
16970   }
16971
16972   return MBB;
16973 }
16974
16975 MachineBasicBlock *
16976 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16977                                                MachineBasicBlock *BB) const {
16978   switch (MI->getOpcode()) {
16979   default: llvm_unreachable("Unexpected instr type to insert");
16980   case X86::TAILJMPd64:
16981   case X86::TAILJMPr64:
16982   case X86::TAILJMPm64:
16983     llvm_unreachable("TAILJMP64 would not be touched here.");
16984   case X86::TCRETURNdi64:
16985   case X86::TCRETURNri64:
16986   case X86::TCRETURNmi64:
16987     return BB;
16988   case X86::WIN_ALLOCA:
16989     return EmitLoweredWinAlloca(MI, BB);
16990   case X86::SEG_ALLOCA_32:
16991     return EmitLoweredSegAlloca(MI, BB, false);
16992   case X86::SEG_ALLOCA_64:
16993     return EmitLoweredSegAlloca(MI, BB, true);
16994   case X86::TLSCall_32:
16995   case X86::TLSCall_64:
16996     return EmitLoweredTLSCall(MI, BB);
16997   case X86::CMOV_GR8:
16998   case X86::CMOV_FR32:
16999   case X86::CMOV_FR64:
17000   case X86::CMOV_V4F32:
17001   case X86::CMOV_V2F64:
17002   case X86::CMOV_V2I64:
17003   case X86::CMOV_V8F32:
17004   case X86::CMOV_V4F64:
17005   case X86::CMOV_V4I64:
17006   case X86::CMOV_V16F32:
17007   case X86::CMOV_V8F64:
17008   case X86::CMOV_V8I64:
17009   case X86::CMOV_GR16:
17010   case X86::CMOV_GR32:
17011   case X86::CMOV_RFP32:
17012   case X86::CMOV_RFP64:
17013   case X86::CMOV_RFP80:
17014     return EmitLoweredSelect(MI, BB);
17015
17016   case X86::FP32_TO_INT16_IN_MEM:
17017   case X86::FP32_TO_INT32_IN_MEM:
17018   case X86::FP32_TO_INT64_IN_MEM:
17019   case X86::FP64_TO_INT16_IN_MEM:
17020   case X86::FP64_TO_INT32_IN_MEM:
17021   case X86::FP64_TO_INT64_IN_MEM:
17022   case X86::FP80_TO_INT16_IN_MEM:
17023   case X86::FP80_TO_INT32_IN_MEM:
17024   case X86::FP80_TO_INT64_IN_MEM: {
17025     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17026     DebugLoc DL = MI->getDebugLoc();
17027
17028     // Change the floating point control register to use "round towards zero"
17029     // mode when truncating to an integer value.
17030     MachineFunction *F = BB->getParent();
17031     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17032     addFrameReference(BuildMI(*BB, MI, DL,
17033                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17034
17035     // Load the old value of the high byte of the control word...
17036     unsigned OldCW =
17037       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17038     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17039                       CWFrameIdx);
17040
17041     // Set the high part to be round to zero...
17042     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17043       .addImm(0xC7F);
17044
17045     // Reload the modified control word now...
17046     addFrameReference(BuildMI(*BB, MI, DL,
17047                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17048
17049     // Restore the memory image of control word to original value
17050     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17051       .addReg(OldCW);
17052
17053     // Get the X86 opcode to use.
17054     unsigned Opc;
17055     switch (MI->getOpcode()) {
17056     default: llvm_unreachable("illegal opcode!");
17057     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17058     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17059     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17060     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17061     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17062     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17063     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17064     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17065     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17066     }
17067
17068     X86AddressMode AM;
17069     MachineOperand &Op = MI->getOperand(0);
17070     if (Op.isReg()) {
17071       AM.BaseType = X86AddressMode::RegBase;
17072       AM.Base.Reg = Op.getReg();
17073     } else {
17074       AM.BaseType = X86AddressMode::FrameIndexBase;
17075       AM.Base.FrameIndex = Op.getIndex();
17076     }
17077     Op = MI->getOperand(1);
17078     if (Op.isImm())
17079       AM.Scale = Op.getImm();
17080     Op = MI->getOperand(2);
17081     if (Op.isImm())
17082       AM.IndexReg = Op.getImm();
17083     Op = MI->getOperand(3);
17084     if (Op.isGlobal()) {
17085       AM.GV = Op.getGlobal();
17086     } else {
17087       AM.Disp = Op.getImm();
17088     }
17089     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17090                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17091
17092     // Reload the original control word now.
17093     addFrameReference(BuildMI(*BB, MI, DL,
17094                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17095
17096     MI->eraseFromParent();   // The pseudo instruction is gone now.
17097     return BB;
17098   }
17099     // String/text processing lowering.
17100   case X86::PCMPISTRM128REG:
17101   case X86::VPCMPISTRM128REG:
17102   case X86::PCMPISTRM128MEM:
17103   case X86::VPCMPISTRM128MEM:
17104   case X86::PCMPESTRM128REG:
17105   case X86::VPCMPESTRM128REG:
17106   case X86::PCMPESTRM128MEM:
17107   case X86::VPCMPESTRM128MEM:
17108     assert(Subtarget->hasSSE42() &&
17109            "Target must have SSE4.2 or AVX features enabled");
17110     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17111
17112   // String/text processing lowering.
17113   case X86::PCMPISTRIREG:
17114   case X86::VPCMPISTRIREG:
17115   case X86::PCMPISTRIMEM:
17116   case X86::VPCMPISTRIMEM:
17117   case X86::PCMPESTRIREG:
17118   case X86::VPCMPESTRIREG:
17119   case X86::PCMPESTRIMEM:
17120   case X86::VPCMPESTRIMEM:
17121     assert(Subtarget->hasSSE42() &&
17122            "Target must have SSE4.2 or AVX features enabled");
17123     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17124
17125   // Thread synchronization.
17126   case X86::MONITOR:
17127     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17128
17129   // xbegin
17130   case X86::XBEGIN:
17131     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17132
17133   // Atomic Lowering.
17134   case X86::ATOMAND8:
17135   case X86::ATOMAND16:
17136   case X86::ATOMAND32:
17137   case X86::ATOMAND64:
17138     // Fall through
17139   case X86::ATOMOR8:
17140   case X86::ATOMOR16:
17141   case X86::ATOMOR32:
17142   case X86::ATOMOR64:
17143     // Fall through
17144   case X86::ATOMXOR16:
17145   case X86::ATOMXOR8:
17146   case X86::ATOMXOR32:
17147   case X86::ATOMXOR64:
17148     // Fall through
17149   case X86::ATOMNAND8:
17150   case X86::ATOMNAND16:
17151   case X86::ATOMNAND32:
17152   case X86::ATOMNAND64:
17153     // Fall through
17154   case X86::ATOMMAX8:
17155   case X86::ATOMMAX16:
17156   case X86::ATOMMAX32:
17157   case X86::ATOMMAX64:
17158     // Fall through
17159   case X86::ATOMMIN8:
17160   case X86::ATOMMIN16:
17161   case X86::ATOMMIN32:
17162   case X86::ATOMMIN64:
17163     // Fall through
17164   case X86::ATOMUMAX8:
17165   case X86::ATOMUMAX16:
17166   case X86::ATOMUMAX32:
17167   case X86::ATOMUMAX64:
17168     // Fall through
17169   case X86::ATOMUMIN8:
17170   case X86::ATOMUMIN16:
17171   case X86::ATOMUMIN32:
17172   case X86::ATOMUMIN64:
17173     return EmitAtomicLoadArith(MI, BB);
17174
17175   // This group does 64-bit operations on a 32-bit host.
17176   case X86::ATOMAND6432:
17177   case X86::ATOMOR6432:
17178   case X86::ATOMXOR6432:
17179   case X86::ATOMNAND6432:
17180   case X86::ATOMADD6432:
17181   case X86::ATOMSUB6432:
17182   case X86::ATOMMAX6432:
17183   case X86::ATOMMIN6432:
17184   case X86::ATOMUMAX6432:
17185   case X86::ATOMUMIN6432:
17186   case X86::ATOMSWAP6432:
17187     return EmitAtomicLoadArith6432(MI, BB);
17188
17189   case X86::VASTART_SAVE_XMM_REGS:
17190     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17191
17192   case X86::VAARG_64:
17193     return EmitVAARG64WithCustomInserter(MI, BB);
17194
17195   case X86::EH_SjLj_SetJmp32:
17196   case X86::EH_SjLj_SetJmp64:
17197     return emitEHSjLjSetJmp(MI, BB);
17198
17199   case X86::EH_SjLj_LongJmp32:
17200   case X86::EH_SjLj_LongJmp64:
17201     return emitEHSjLjLongJmp(MI, BB);
17202
17203   case TargetOpcode::STACKMAP:
17204   case TargetOpcode::PATCHPOINT:
17205     return emitPatchPoint(MI, BB);
17206
17207   case X86::VFMADDPDr213r:
17208   case X86::VFMADDPSr213r:
17209   case X86::VFMADDSDr213r:
17210   case X86::VFMADDSSr213r:
17211   case X86::VFMSUBPDr213r:
17212   case X86::VFMSUBPSr213r:
17213   case X86::VFMSUBSDr213r:
17214   case X86::VFMSUBSSr213r:
17215   case X86::VFNMADDPDr213r:
17216   case X86::VFNMADDPSr213r:
17217   case X86::VFNMADDSDr213r:
17218   case X86::VFNMADDSSr213r:
17219   case X86::VFNMSUBPDr213r:
17220   case X86::VFNMSUBPSr213r:
17221   case X86::VFNMSUBSDr213r:
17222   case X86::VFNMSUBSSr213r:
17223   case X86::VFMADDPDr213rY:
17224   case X86::VFMADDPSr213rY:
17225   case X86::VFMSUBPDr213rY:
17226   case X86::VFMSUBPSr213rY:
17227   case X86::VFNMADDPDr213rY:
17228   case X86::VFNMADDPSr213rY:
17229   case X86::VFNMSUBPDr213rY:
17230   case X86::VFNMSUBPSr213rY:
17231     return emitFMA3Instr(MI, BB);
17232   }
17233 }
17234
17235 //===----------------------------------------------------------------------===//
17236 //                           X86 Optimization Hooks
17237 //===----------------------------------------------------------------------===//
17238
17239 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17240                                                       APInt &KnownZero,
17241                                                       APInt &KnownOne,
17242                                                       const SelectionDAG &DAG,
17243                                                       unsigned Depth) const {
17244   unsigned BitWidth = KnownZero.getBitWidth();
17245   unsigned Opc = Op.getOpcode();
17246   assert((Opc >= ISD::BUILTIN_OP_END ||
17247           Opc == ISD::INTRINSIC_WO_CHAIN ||
17248           Opc == ISD::INTRINSIC_W_CHAIN ||
17249           Opc == ISD::INTRINSIC_VOID) &&
17250          "Should use MaskedValueIsZero if you don't know whether Op"
17251          " is a target node!");
17252
17253   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17254   switch (Opc) {
17255   default: break;
17256   case X86ISD::ADD:
17257   case X86ISD::SUB:
17258   case X86ISD::ADC:
17259   case X86ISD::SBB:
17260   case X86ISD::SMUL:
17261   case X86ISD::UMUL:
17262   case X86ISD::INC:
17263   case X86ISD::DEC:
17264   case X86ISD::OR:
17265   case X86ISD::XOR:
17266   case X86ISD::AND:
17267     // These nodes' second result is a boolean.
17268     if (Op.getResNo() == 0)
17269       break;
17270     // Fallthrough
17271   case X86ISD::SETCC:
17272     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17273     break;
17274   case ISD::INTRINSIC_WO_CHAIN: {
17275     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17276     unsigned NumLoBits = 0;
17277     switch (IntId) {
17278     default: break;
17279     case Intrinsic::x86_sse_movmsk_ps:
17280     case Intrinsic::x86_avx_movmsk_ps_256:
17281     case Intrinsic::x86_sse2_movmsk_pd:
17282     case Intrinsic::x86_avx_movmsk_pd_256:
17283     case Intrinsic::x86_mmx_pmovmskb:
17284     case Intrinsic::x86_sse2_pmovmskb_128:
17285     case Intrinsic::x86_avx2_pmovmskb: {
17286       // High bits of movmskp{s|d}, pmovmskb are known zero.
17287       switch (IntId) {
17288         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17289         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17290         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17291         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17292         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17293         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17294         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17295         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17296       }
17297       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17298       break;
17299     }
17300     }
17301     break;
17302   }
17303   }
17304 }
17305
17306 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17307   SDValue Op,
17308   const SelectionDAG &,
17309   unsigned Depth) const {
17310   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17311   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17312     return Op.getValueType().getScalarType().getSizeInBits();
17313
17314   // Fallback case.
17315   return 1;
17316 }
17317
17318 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17319 /// node is a GlobalAddress + offset.
17320 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17321                                        const GlobalValue* &GA,
17322                                        int64_t &Offset) const {
17323   if (N->getOpcode() == X86ISD::Wrapper) {
17324     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17325       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17326       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17327       return true;
17328     }
17329   }
17330   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17331 }
17332
17333 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17334 /// same as extracting the high 128-bit part of 256-bit vector and then
17335 /// inserting the result into the low part of a new 256-bit vector
17336 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17337   EVT VT = SVOp->getValueType(0);
17338   unsigned NumElems = VT.getVectorNumElements();
17339
17340   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17341   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17342     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17343         SVOp->getMaskElt(j) >= 0)
17344       return false;
17345
17346   return true;
17347 }
17348
17349 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17350 /// same as extracting the low 128-bit part of 256-bit vector and then
17351 /// inserting the result into the high part of a new 256-bit vector
17352 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17353   EVT VT = SVOp->getValueType(0);
17354   unsigned NumElems = VT.getVectorNumElements();
17355
17356   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17357   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17358     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17359         SVOp->getMaskElt(j) >= 0)
17360       return false;
17361
17362   return true;
17363 }
17364
17365 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17366 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17367                                         TargetLowering::DAGCombinerInfo &DCI,
17368                                         const X86Subtarget* Subtarget) {
17369   SDLoc dl(N);
17370   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17371   SDValue V1 = SVOp->getOperand(0);
17372   SDValue V2 = SVOp->getOperand(1);
17373   EVT VT = SVOp->getValueType(0);
17374   unsigned NumElems = VT.getVectorNumElements();
17375
17376   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17377       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17378     //
17379     //                   0,0,0,...
17380     //                      |
17381     //    V      UNDEF    BUILD_VECTOR    UNDEF
17382     //     \      /           \           /
17383     //  CONCAT_VECTOR         CONCAT_VECTOR
17384     //         \                  /
17385     //          \                /
17386     //          RESULT: V + zero extended
17387     //
17388     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17389         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17390         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17391       return SDValue();
17392
17393     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17394       return SDValue();
17395
17396     // To match the shuffle mask, the first half of the mask should
17397     // be exactly the first vector, and all the rest a splat with the
17398     // first element of the second one.
17399     for (unsigned i = 0; i != NumElems/2; ++i)
17400       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17401           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17402         return SDValue();
17403
17404     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17405     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17406       if (Ld->hasNUsesOfValue(1, 0)) {
17407         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17408         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17409         SDValue ResNode =
17410           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17411                                   Ld->getMemoryVT(),
17412                                   Ld->getPointerInfo(),
17413                                   Ld->getAlignment(),
17414                                   false/*isVolatile*/, true/*ReadMem*/,
17415                                   false/*WriteMem*/);
17416
17417         // Make sure the newly-created LOAD is in the same position as Ld in
17418         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17419         // and update uses of Ld's output chain to use the TokenFactor.
17420         if (Ld->hasAnyUseOfValue(1)) {
17421           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17422                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17423           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17424           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17425                                  SDValue(ResNode.getNode(), 1));
17426         }
17427
17428         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17429       }
17430     }
17431
17432     // Emit a zeroed vector and insert the desired subvector on its
17433     // first half.
17434     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17435     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17436     return DCI.CombineTo(N, InsV);
17437   }
17438
17439   //===--------------------------------------------------------------------===//
17440   // Combine some shuffles into subvector extracts and inserts:
17441   //
17442
17443   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17444   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17445     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17446     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17447     return DCI.CombineTo(N, InsV);
17448   }
17449
17450   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17451   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17452     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17453     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17454     return DCI.CombineTo(N, InsV);
17455   }
17456
17457   return SDValue();
17458 }
17459
17460 /// PerformShuffleCombine - Performs several different shuffle combines.
17461 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17462                                      TargetLowering::DAGCombinerInfo &DCI,
17463                                      const X86Subtarget *Subtarget) {
17464   SDLoc dl(N);
17465   EVT VT = N->getValueType(0);
17466
17467   // Don't create instructions with illegal types after legalize types has run.
17468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17469   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17470     return SDValue();
17471
17472   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17473   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17474       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17475     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17476
17477   // Only handle 128 wide vector from here on.
17478   if (!VT.is128BitVector())
17479     return SDValue();
17480
17481   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17482   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17483   // consecutive, non-overlapping, and in the right order.
17484   SmallVector<SDValue, 16> Elts;
17485   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17486     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17487
17488   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17489 }
17490
17491 /// PerformTruncateCombine - Converts truncate operation to
17492 /// a sequence of vector shuffle operations.
17493 /// It is possible when we truncate 256-bit vector to 128-bit vector
17494 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17495                                       TargetLowering::DAGCombinerInfo &DCI,
17496                                       const X86Subtarget *Subtarget)  {
17497   return SDValue();
17498 }
17499
17500 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17501 /// specific shuffle of a load can be folded into a single element load.
17502 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17503 /// shuffles have been customed lowered so we need to handle those here.
17504 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17505                                          TargetLowering::DAGCombinerInfo &DCI) {
17506   if (DCI.isBeforeLegalizeOps())
17507     return SDValue();
17508
17509   SDValue InVec = N->getOperand(0);
17510   SDValue EltNo = N->getOperand(1);
17511
17512   if (!isa<ConstantSDNode>(EltNo))
17513     return SDValue();
17514
17515   EVT VT = InVec.getValueType();
17516
17517   bool HasShuffleIntoBitcast = false;
17518   if (InVec.getOpcode() == ISD::BITCAST) {
17519     // Don't duplicate a load with other uses.
17520     if (!InVec.hasOneUse())
17521       return SDValue();
17522     EVT BCVT = InVec.getOperand(0).getValueType();
17523     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17524       return SDValue();
17525     InVec = InVec.getOperand(0);
17526     HasShuffleIntoBitcast = true;
17527   }
17528
17529   if (!isTargetShuffle(InVec.getOpcode()))
17530     return SDValue();
17531
17532   // Don't duplicate a load with other uses.
17533   if (!InVec.hasOneUse())
17534     return SDValue();
17535
17536   SmallVector<int, 16> ShuffleMask;
17537   bool UnaryShuffle;
17538   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17539                             UnaryShuffle))
17540     return SDValue();
17541
17542   // Select the input vector, guarding against out of range extract vector.
17543   unsigned NumElems = VT.getVectorNumElements();
17544   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17545   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17546   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17547                                          : InVec.getOperand(1);
17548
17549   // If inputs to shuffle are the same for both ops, then allow 2 uses
17550   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17551
17552   if (LdNode.getOpcode() == ISD::BITCAST) {
17553     // Don't duplicate a load with other uses.
17554     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17555       return SDValue();
17556
17557     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17558     LdNode = LdNode.getOperand(0);
17559   }
17560
17561   if (!ISD::isNormalLoad(LdNode.getNode()))
17562     return SDValue();
17563
17564   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17565
17566   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17567     return SDValue();
17568
17569   if (HasShuffleIntoBitcast) {
17570     // If there's a bitcast before the shuffle, check if the load type and
17571     // alignment is valid.
17572     unsigned Align = LN0->getAlignment();
17573     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17574     unsigned NewAlign = TLI.getDataLayout()->
17575       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17576
17577     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17578       return SDValue();
17579   }
17580
17581   // All checks match so transform back to vector_shuffle so that DAG combiner
17582   // can finish the job
17583   SDLoc dl(N);
17584
17585   // Create shuffle node taking into account the case that its a unary shuffle
17586   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17587   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17588                                  InVec.getOperand(0), Shuffle,
17589                                  &ShuffleMask[0]);
17590   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17591   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17592                      EltNo);
17593 }
17594
17595 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17596 /// generation and convert it from being a bunch of shuffles and extracts
17597 /// to a simple store and scalar loads to extract the elements.
17598 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17599                                          TargetLowering::DAGCombinerInfo &DCI) {
17600   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17601   if (NewOp.getNode())
17602     return NewOp;
17603
17604   SDValue InputVector = N->getOperand(0);
17605
17606   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17607   // from mmx to v2i32 has a single usage.
17608   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17609       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17610       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17611     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17612                        N->getValueType(0),
17613                        InputVector.getNode()->getOperand(0));
17614
17615   // Only operate on vectors of 4 elements, where the alternative shuffling
17616   // gets to be more expensive.
17617   if (InputVector.getValueType() != MVT::v4i32)
17618     return SDValue();
17619
17620   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17621   // single use which is a sign-extend or zero-extend, and all elements are
17622   // used.
17623   SmallVector<SDNode *, 4> Uses;
17624   unsigned ExtractedElements = 0;
17625   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17626        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17627     if (UI.getUse().getResNo() != InputVector.getResNo())
17628       return SDValue();
17629
17630     SDNode *Extract = *UI;
17631     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17632       return SDValue();
17633
17634     if (Extract->getValueType(0) != MVT::i32)
17635       return SDValue();
17636     if (!Extract->hasOneUse())
17637       return SDValue();
17638     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17639         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17640       return SDValue();
17641     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17642       return SDValue();
17643
17644     // Record which element was extracted.
17645     ExtractedElements |=
17646       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17647
17648     Uses.push_back(Extract);
17649   }
17650
17651   // If not all the elements were used, this may not be worthwhile.
17652   if (ExtractedElements != 15)
17653     return SDValue();
17654
17655   // Ok, we've now decided to do the transformation.
17656   SDLoc dl(InputVector);
17657
17658   // Store the value to a temporary stack slot.
17659   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17660   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17661                             MachinePointerInfo(), false, false, 0);
17662
17663   // Replace each use (extract) with a load of the appropriate element.
17664   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17665        UE = Uses.end(); UI != UE; ++UI) {
17666     SDNode *Extract = *UI;
17667
17668     // cOMpute the element's address.
17669     SDValue Idx = Extract->getOperand(1);
17670     unsigned EltSize =
17671         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17672     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17673     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17674     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17675
17676     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17677                                      StackPtr, OffsetVal);
17678
17679     // Load the scalar.
17680     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17681                                      ScalarAddr, MachinePointerInfo(),
17682                                      false, false, false, 0);
17683
17684     // Replace the exact with the load.
17685     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17686   }
17687
17688   // The replacement was made in place; don't return anything.
17689   return SDValue();
17690 }
17691
17692 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17693 static std::pair<unsigned, bool>
17694 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17695                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17696   if (!VT.isVector())
17697     return std::make_pair(0, false);
17698
17699   bool NeedSplit = false;
17700   switch (VT.getSimpleVT().SimpleTy) {
17701   default: return std::make_pair(0, false);
17702   case MVT::v32i8:
17703   case MVT::v16i16:
17704   case MVT::v8i32:
17705     if (!Subtarget->hasAVX2())
17706       NeedSplit = true;
17707     if (!Subtarget->hasAVX())
17708       return std::make_pair(0, false);
17709     break;
17710   case MVT::v16i8:
17711   case MVT::v8i16:
17712   case MVT::v4i32:
17713     if (!Subtarget->hasSSE2())
17714       return std::make_pair(0, false);
17715   }
17716
17717   // SSE2 has only a small subset of the operations.
17718   bool hasUnsigned = Subtarget->hasSSE41() ||
17719                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17720   bool hasSigned = Subtarget->hasSSE41() ||
17721                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17722
17723   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17724
17725   unsigned Opc = 0;
17726   // Check for x CC y ? x : y.
17727   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17728       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17729     switch (CC) {
17730     default: break;
17731     case ISD::SETULT:
17732     case ISD::SETULE:
17733       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17734     case ISD::SETUGT:
17735     case ISD::SETUGE:
17736       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17737     case ISD::SETLT:
17738     case ISD::SETLE:
17739       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17740     case ISD::SETGT:
17741     case ISD::SETGE:
17742       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17743     }
17744   // Check for x CC y ? y : x -- a min/max with reversed arms.
17745   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17746              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17747     switch (CC) {
17748     default: break;
17749     case ISD::SETULT:
17750     case ISD::SETULE:
17751       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17752     case ISD::SETUGT:
17753     case ISD::SETUGE:
17754       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17755     case ISD::SETLT:
17756     case ISD::SETLE:
17757       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17758     case ISD::SETGT:
17759     case ISD::SETGE:
17760       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17761     }
17762   }
17763
17764   return std::make_pair(Opc, NeedSplit);
17765 }
17766
17767 static SDValue
17768 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17769                                       const X86Subtarget *Subtarget) {
17770   SDLoc dl(N);
17771   SDValue Cond = N->getOperand(0);
17772   SDValue LHS = N->getOperand(1);
17773   SDValue RHS = N->getOperand(2);
17774
17775   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17776     SDValue CondSrc = Cond->getOperand(0);
17777     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17778       Cond = CondSrc->getOperand(0);
17779   }
17780
17781   MVT VT = N->getSimpleValueType(0);
17782   MVT EltVT = VT.getVectorElementType();
17783   unsigned NumElems = VT.getVectorNumElements();
17784   // There is no blend with immediate in AVX-512.
17785   if (VT.is512BitVector())
17786     return SDValue();
17787
17788   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17789     return SDValue();
17790   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17791     return SDValue();
17792
17793   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17794     return SDValue();
17795
17796   unsigned MaskValue = 0;
17797   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17798     return SDValue();
17799
17800   SmallVector<int, 8> ShuffleMask(NumElems, -1);
17801   for (unsigned i = 0; i < NumElems; ++i) {
17802     // Be sure we emit undef where we can.
17803     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17804       ShuffleMask[i] = -1;
17805     else
17806       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17807   }
17808
17809   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17810 }
17811
17812 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17813 /// nodes.
17814 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17815                                     TargetLowering::DAGCombinerInfo &DCI,
17816                                     const X86Subtarget *Subtarget) {
17817   SDLoc DL(N);
17818   SDValue Cond = N->getOperand(0);
17819   // Get the LHS/RHS of the select.
17820   SDValue LHS = N->getOperand(1);
17821   SDValue RHS = N->getOperand(2);
17822   EVT VT = LHS.getValueType();
17823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17824
17825   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17826   // instructions match the semantics of the common C idiom x<y?x:y but not
17827   // x<=y?x:y, because of how they handle negative zero (which can be
17828   // ignored in unsafe-math mode).
17829   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17830       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17831       (Subtarget->hasSSE2() ||
17832        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17833     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17834
17835     unsigned Opcode = 0;
17836     // Check for x CC y ? x : y.
17837     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17838         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17839       switch (CC) {
17840       default: break;
17841       case ISD::SETULT:
17842         // Converting this to a min would handle NaNs incorrectly, and swapping
17843         // the operands would cause it to handle comparisons between positive
17844         // and negative zero incorrectly.
17845         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17846           if (!DAG.getTarget().Options.UnsafeFPMath &&
17847               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17848             break;
17849           std::swap(LHS, RHS);
17850         }
17851         Opcode = X86ISD::FMIN;
17852         break;
17853       case ISD::SETOLE:
17854         // Converting this to a min would handle comparisons between positive
17855         // and negative zero incorrectly.
17856         if (!DAG.getTarget().Options.UnsafeFPMath &&
17857             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17858           break;
17859         Opcode = X86ISD::FMIN;
17860         break;
17861       case ISD::SETULE:
17862         // Converting this to a min would handle both negative zeros and NaNs
17863         // incorrectly, but we can swap the operands to fix both.
17864         std::swap(LHS, RHS);
17865       case ISD::SETOLT:
17866       case ISD::SETLT:
17867       case ISD::SETLE:
17868         Opcode = X86ISD::FMIN;
17869         break;
17870
17871       case ISD::SETOGE:
17872         // Converting this to a max would handle comparisons between positive
17873         // and negative zero incorrectly.
17874         if (!DAG.getTarget().Options.UnsafeFPMath &&
17875             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17876           break;
17877         Opcode = X86ISD::FMAX;
17878         break;
17879       case ISD::SETUGT:
17880         // Converting this to a max would handle NaNs incorrectly, and swapping
17881         // the operands would cause it to handle comparisons between positive
17882         // and negative zero incorrectly.
17883         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17884           if (!DAG.getTarget().Options.UnsafeFPMath &&
17885               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17886             break;
17887           std::swap(LHS, RHS);
17888         }
17889         Opcode = X86ISD::FMAX;
17890         break;
17891       case ISD::SETUGE:
17892         // Converting this to a max would handle both negative zeros and NaNs
17893         // incorrectly, but we can swap the operands to fix both.
17894         std::swap(LHS, RHS);
17895       case ISD::SETOGT:
17896       case ISD::SETGT:
17897       case ISD::SETGE:
17898         Opcode = X86ISD::FMAX;
17899         break;
17900       }
17901     // Check for x CC y ? y : x -- a min/max with reversed arms.
17902     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17903                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17904       switch (CC) {
17905       default: break;
17906       case ISD::SETOGE:
17907         // Converting this to a min would handle comparisons between positive
17908         // and negative zero incorrectly, and swapping the operands would
17909         // cause it to handle NaNs incorrectly.
17910         if (!DAG.getTarget().Options.UnsafeFPMath &&
17911             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17912           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17913             break;
17914           std::swap(LHS, RHS);
17915         }
17916         Opcode = X86ISD::FMIN;
17917         break;
17918       case ISD::SETUGT:
17919         // Converting this to a min would handle NaNs incorrectly.
17920         if (!DAG.getTarget().Options.UnsafeFPMath &&
17921             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17922           break;
17923         Opcode = X86ISD::FMIN;
17924         break;
17925       case ISD::SETUGE:
17926         // Converting this to a min would handle both negative zeros and NaNs
17927         // incorrectly, but we can swap the operands to fix both.
17928         std::swap(LHS, RHS);
17929       case ISD::SETOGT:
17930       case ISD::SETGT:
17931       case ISD::SETGE:
17932         Opcode = X86ISD::FMIN;
17933         break;
17934
17935       case ISD::SETULT:
17936         // Converting this to a max would handle NaNs incorrectly.
17937         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17938           break;
17939         Opcode = X86ISD::FMAX;
17940         break;
17941       case ISD::SETOLE:
17942         // Converting this to a max would handle comparisons between positive
17943         // and negative zero incorrectly, and swapping the operands would
17944         // cause it to handle NaNs incorrectly.
17945         if (!DAG.getTarget().Options.UnsafeFPMath &&
17946             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17947           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17948             break;
17949           std::swap(LHS, RHS);
17950         }
17951         Opcode = X86ISD::FMAX;
17952         break;
17953       case ISD::SETULE:
17954         // Converting this to a max would handle both negative zeros and NaNs
17955         // incorrectly, but we can swap the operands to fix both.
17956         std::swap(LHS, RHS);
17957       case ISD::SETOLT:
17958       case ISD::SETLT:
17959       case ISD::SETLE:
17960         Opcode = X86ISD::FMAX;
17961         break;
17962       }
17963     }
17964
17965     if (Opcode)
17966       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17967   }
17968
17969   EVT CondVT = Cond.getValueType();
17970   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17971       CondVT.getVectorElementType() == MVT::i1) {
17972     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17973     // lowering on AVX-512. In this case we convert it to
17974     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17975     // The same situation for all 128 and 256-bit vectors of i8 and i16
17976     EVT OpVT = LHS.getValueType();
17977     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17978         (OpVT.getVectorElementType() == MVT::i8 ||
17979          OpVT.getVectorElementType() == MVT::i16)) {
17980       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17981       DCI.AddToWorklist(Cond.getNode());
17982       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17983     }
17984   }
17985   // If this is a select between two integer constants, try to do some
17986   // optimizations.
17987   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17988     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17989       // Don't do this for crazy integer types.
17990       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17991         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17992         // so that TrueC (the true value) is larger than FalseC.
17993         bool NeedsCondInvert = false;
17994
17995         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17996             // Efficiently invertible.
17997             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17998              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17999               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18000           NeedsCondInvert = true;
18001           std::swap(TrueC, FalseC);
18002         }
18003
18004         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18005         if (FalseC->getAPIntValue() == 0 &&
18006             TrueC->getAPIntValue().isPowerOf2()) {
18007           if (NeedsCondInvert) // Invert the condition if needed.
18008             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18009                                DAG.getConstant(1, Cond.getValueType()));
18010
18011           // Zero extend the condition if needed.
18012           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18013
18014           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18015           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18016                              DAG.getConstant(ShAmt, MVT::i8));
18017         }
18018
18019         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18020         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18021           if (NeedsCondInvert) // Invert the condition if needed.
18022             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18023                                DAG.getConstant(1, Cond.getValueType()));
18024
18025           // Zero extend the condition if needed.
18026           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18027                              FalseC->getValueType(0), Cond);
18028           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18029                              SDValue(FalseC, 0));
18030         }
18031
18032         // Optimize cases that will turn into an LEA instruction.  This requires
18033         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18034         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18035           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18036           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18037
18038           bool isFastMultiplier = false;
18039           if (Diff < 10) {
18040             switch ((unsigned char)Diff) {
18041               default: break;
18042               case 1:  // result = add base, cond
18043               case 2:  // result = lea base(    , cond*2)
18044               case 3:  // result = lea base(cond, cond*2)
18045               case 4:  // result = lea base(    , cond*4)
18046               case 5:  // result = lea base(cond, cond*4)
18047               case 8:  // result = lea base(    , cond*8)
18048               case 9:  // result = lea base(cond, cond*8)
18049                 isFastMultiplier = true;
18050                 break;
18051             }
18052           }
18053
18054           if (isFastMultiplier) {
18055             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18056             if (NeedsCondInvert) // Invert the condition if needed.
18057               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18058                                  DAG.getConstant(1, Cond.getValueType()));
18059
18060             // Zero extend the condition if needed.
18061             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18062                                Cond);
18063             // Scale the condition by the difference.
18064             if (Diff != 1)
18065               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18066                                  DAG.getConstant(Diff, Cond.getValueType()));
18067
18068             // Add the base if non-zero.
18069             if (FalseC->getAPIntValue() != 0)
18070               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18071                                  SDValue(FalseC, 0));
18072             return Cond;
18073           }
18074         }
18075       }
18076   }
18077
18078   // Canonicalize max and min:
18079   // (x > y) ? x : y -> (x >= y) ? x : y
18080   // (x < y) ? x : y -> (x <= y) ? x : y
18081   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18082   // the need for an extra compare
18083   // against zero. e.g.
18084   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18085   // subl   %esi, %edi
18086   // testl  %edi, %edi
18087   // movl   $0, %eax
18088   // cmovgl %edi, %eax
18089   // =>
18090   // xorl   %eax, %eax
18091   // subl   %esi, $edi
18092   // cmovsl %eax, %edi
18093   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18094       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18095       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18096     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18097     switch (CC) {
18098     default: break;
18099     case ISD::SETLT:
18100     case ISD::SETGT: {
18101       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18102       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18103                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18104       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18105     }
18106     }
18107   }
18108
18109   // Early exit check
18110   if (!TLI.isTypeLegal(VT))
18111     return SDValue();
18112
18113   // Match VSELECTs into subs with unsigned saturation.
18114   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18115       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18116       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18117        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18118     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18119
18120     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18121     // left side invert the predicate to simplify logic below.
18122     SDValue Other;
18123     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18124       Other = RHS;
18125       CC = ISD::getSetCCInverse(CC, true);
18126     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18127       Other = LHS;
18128     }
18129
18130     if (Other.getNode() && Other->getNumOperands() == 2 &&
18131         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18132       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18133       SDValue CondRHS = Cond->getOperand(1);
18134
18135       // Look for a general sub with unsigned saturation first.
18136       // x >= y ? x-y : 0 --> subus x, y
18137       // x >  y ? x-y : 0 --> subus x, y
18138       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18139           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18140         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18141
18142       // If the RHS is a constant we have to reverse the const canonicalization.
18143       // x > C-1 ? x+-C : 0 --> subus x, C
18144       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18145           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18146         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18147         if (CondRHS.getConstantOperandVal(0) == -A-1)
18148           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18149                              DAG.getConstant(-A, VT));
18150       }
18151
18152       // Another special case: If C was a sign bit, the sub has been
18153       // canonicalized into a xor.
18154       // FIXME: Would it be better to use computeKnownBits to determine whether
18155       //        it's safe to decanonicalize the xor?
18156       // x s< 0 ? x^C : 0 --> subus x, C
18157       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18158           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18159           isSplatVector(OpRHS.getNode())) {
18160         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18161         if (A.isSignBit())
18162           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18163       }
18164     }
18165   }
18166
18167   // Try to match a min/max vector operation.
18168   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18169     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18170     unsigned Opc = ret.first;
18171     bool NeedSplit = ret.second;
18172
18173     if (Opc && NeedSplit) {
18174       unsigned NumElems = VT.getVectorNumElements();
18175       // Extract the LHS vectors
18176       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18177       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18178
18179       // Extract the RHS vectors
18180       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18181       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18182
18183       // Create min/max for each subvector
18184       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18185       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18186
18187       // Merge the result
18188       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18189     } else if (Opc)
18190       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18191   }
18192
18193   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18194   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18195       // Check if SETCC has already been promoted
18196       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18197       // Check that condition value type matches vselect operand type
18198       CondVT == VT) { 
18199
18200     assert(Cond.getValueType().isVector() &&
18201            "vector select expects a vector selector!");
18202
18203     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18204     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18205
18206     if (!TValIsAllOnes && !FValIsAllZeros) {
18207       // Try invert the condition if true value is not all 1s and false value
18208       // is not all 0s.
18209       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18210       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18211
18212       if (TValIsAllZeros || FValIsAllOnes) {
18213         SDValue CC = Cond.getOperand(2);
18214         ISD::CondCode NewCC =
18215           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18216                                Cond.getOperand(0).getValueType().isInteger());
18217         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18218         std::swap(LHS, RHS);
18219         TValIsAllOnes = FValIsAllOnes;
18220         FValIsAllZeros = TValIsAllZeros;
18221       }
18222     }
18223
18224     if (TValIsAllOnes || FValIsAllZeros) {
18225       SDValue Ret;
18226
18227       if (TValIsAllOnes && FValIsAllZeros)
18228         Ret = Cond;
18229       else if (TValIsAllOnes)
18230         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18231                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18232       else if (FValIsAllZeros)
18233         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18234                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18235
18236       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18237     }
18238   }
18239
18240   // Try to fold this VSELECT into a MOVSS/MOVSD
18241   if (N->getOpcode() == ISD::VSELECT &&
18242       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18243     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18244         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18245       bool CanFold = false;
18246       unsigned NumElems = Cond.getNumOperands();
18247       SDValue A = LHS;
18248       SDValue B = RHS;
18249       
18250       if (isZero(Cond.getOperand(0))) {
18251         CanFold = true;
18252
18253         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18254         // fold (vselect <0,-1> -> (movsd A, B)
18255         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18256           CanFold = isAllOnes(Cond.getOperand(i));
18257       } else if (isAllOnes(Cond.getOperand(0))) {
18258         CanFold = true;
18259         std::swap(A, B);
18260
18261         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18262         // fold (vselect <-1,0> -> (movsd B, A)
18263         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18264           CanFold = isZero(Cond.getOperand(i));
18265       }
18266
18267       if (CanFold) {
18268         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18269           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18270         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18271       }
18272
18273       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18274         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18275         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18276         //                             (v2i64 (bitcast B)))))
18277         //
18278         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18279         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18280         //                             (v2f64 (bitcast B)))))
18281         //
18282         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18283         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18284         //                             (v2i64 (bitcast A)))))
18285         //
18286         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18287         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18288         //                             (v2f64 (bitcast A)))))
18289
18290         CanFold = (isZero(Cond.getOperand(0)) &&
18291                    isZero(Cond.getOperand(1)) &&
18292                    isAllOnes(Cond.getOperand(2)) &&
18293                    isAllOnes(Cond.getOperand(3)));
18294
18295         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18296             isAllOnes(Cond.getOperand(1)) &&
18297             isZero(Cond.getOperand(2)) &&
18298             isZero(Cond.getOperand(3))) {
18299           CanFold = true;
18300           std::swap(LHS, RHS);
18301         }
18302
18303         if (CanFold) {
18304           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18305           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18306           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18307           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18308                                                 NewB, DAG);
18309           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18310         }
18311       }
18312     }
18313   }
18314
18315   // If we know that this node is legal then we know that it is going to be
18316   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18317   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18318   // to simplify previous instructions.
18319   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18320       !DCI.isBeforeLegalize() &&
18321       // We explicitly check against v8i16 and v16i16 because, although
18322       // they're marked as Custom, they might only be legal when Cond is a
18323       // build_vector of constants. This will be taken care in a later
18324       // condition.
18325       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18326        VT != MVT::v8i16)) {
18327     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18328
18329     // Don't optimize vector selects that map to mask-registers.
18330     if (BitWidth == 1)
18331       return SDValue();
18332
18333     // Check all uses of that condition operand to check whether it will be
18334     // consumed by non-BLEND instructions, which may depend on all bits are set
18335     // properly.
18336     for (SDNode::use_iterator I = Cond->use_begin(),
18337                               E = Cond->use_end(); I != E; ++I)
18338       if (I->getOpcode() != ISD::VSELECT)
18339         // TODO: Add other opcodes eventually lowered into BLEND.
18340         return SDValue();
18341
18342     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18343     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18344
18345     APInt KnownZero, KnownOne;
18346     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18347                                           DCI.isBeforeLegalizeOps());
18348     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18349         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18350       DCI.CommitTargetLoweringOpt(TLO);
18351   }
18352
18353   // We should generate an X86ISD::BLENDI from a vselect if its argument
18354   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18355   // constants. This specific pattern gets generated when we split a
18356   // selector for a 512 bit vector in a machine without AVX512 (but with
18357   // 256-bit vectors), during legalization:
18358   //
18359   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18360   //
18361   // Iff we find this pattern and the build_vectors are built from
18362   // constants, we translate the vselect into a shuffle_vector that we
18363   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18364   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18365     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18366     if (Shuffle.getNode())
18367       return Shuffle;
18368   }
18369
18370   return SDValue();
18371 }
18372
18373 // Check whether a boolean test is testing a boolean value generated by
18374 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18375 // code.
18376 //
18377 // Simplify the following patterns:
18378 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18379 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18380 // to (Op EFLAGS Cond)
18381 //
18382 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18383 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18384 // to (Op EFLAGS !Cond)
18385 //
18386 // where Op could be BRCOND or CMOV.
18387 //
18388 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18389   // Quit if not CMP and SUB with its value result used.
18390   if (Cmp.getOpcode() != X86ISD::CMP &&
18391       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18392       return SDValue();
18393
18394   // Quit if not used as a boolean value.
18395   if (CC != X86::COND_E && CC != X86::COND_NE)
18396     return SDValue();
18397
18398   // Check CMP operands. One of them should be 0 or 1 and the other should be
18399   // an SetCC or extended from it.
18400   SDValue Op1 = Cmp.getOperand(0);
18401   SDValue Op2 = Cmp.getOperand(1);
18402
18403   SDValue SetCC;
18404   const ConstantSDNode* C = nullptr;
18405   bool needOppositeCond = (CC == X86::COND_E);
18406   bool checkAgainstTrue = false; // Is it a comparison against 1?
18407
18408   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18409     SetCC = Op2;
18410   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18411     SetCC = Op1;
18412   else // Quit if all operands are not constants.
18413     return SDValue();
18414
18415   if (C->getZExtValue() == 1) {
18416     needOppositeCond = !needOppositeCond;
18417     checkAgainstTrue = true;
18418   } else if (C->getZExtValue() != 0)
18419     // Quit if the constant is neither 0 or 1.
18420     return SDValue();
18421
18422   bool truncatedToBoolWithAnd = false;
18423   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18424   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18425          SetCC.getOpcode() == ISD::TRUNCATE ||
18426          SetCC.getOpcode() == ISD::AND) {
18427     if (SetCC.getOpcode() == ISD::AND) {
18428       int OpIdx = -1;
18429       ConstantSDNode *CS;
18430       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18431           CS->getZExtValue() == 1)
18432         OpIdx = 1;
18433       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18434           CS->getZExtValue() == 1)
18435         OpIdx = 0;
18436       if (OpIdx == -1)
18437         break;
18438       SetCC = SetCC.getOperand(OpIdx);
18439       truncatedToBoolWithAnd = true;
18440     } else
18441       SetCC = SetCC.getOperand(0);
18442   }
18443
18444   switch (SetCC.getOpcode()) {
18445   case X86ISD::SETCC_CARRY:
18446     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18447     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18448     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18449     // truncated to i1 using 'and'.
18450     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18451       break;
18452     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18453            "Invalid use of SETCC_CARRY!");
18454     // FALL THROUGH
18455   case X86ISD::SETCC:
18456     // Set the condition code or opposite one if necessary.
18457     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18458     if (needOppositeCond)
18459       CC = X86::GetOppositeBranchCondition(CC);
18460     return SetCC.getOperand(1);
18461   case X86ISD::CMOV: {
18462     // Check whether false/true value has canonical one, i.e. 0 or 1.
18463     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18464     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18465     // Quit if true value is not a constant.
18466     if (!TVal)
18467       return SDValue();
18468     // Quit if false value is not a constant.
18469     if (!FVal) {
18470       SDValue Op = SetCC.getOperand(0);
18471       // Skip 'zext' or 'trunc' node.
18472       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18473           Op.getOpcode() == ISD::TRUNCATE)
18474         Op = Op.getOperand(0);
18475       // A special case for rdrand/rdseed, where 0 is set if false cond is
18476       // found.
18477       if ((Op.getOpcode() != X86ISD::RDRAND &&
18478            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18479         return SDValue();
18480     }
18481     // Quit if false value is not the constant 0 or 1.
18482     bool FValIsFalse = true;
18483     if (FVal && FVal->getZExtValue() != 0) {
18484       if (FVal->getZExtValue() != 1)
18485         return SDValue();
18486       // If FVal is 1, opposite cond is needed.
18487       needOppositeCond = !needOppositeCond;
18488       FValIsFalse = false;
18489     }
18490     // Quit if TVal is not the constant opposite of FVal.
18491     if (FValIsFalse && TVal->getZExtValue() != 1)
18492       return SDValue();
18493     if (!FValIsFalse && TVal->getZExtValue() != 0)
18494       return SDValue();
18495     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18496     if (needOppositeCond)
18497       CC = X86::GetOppositeBranchCondition(CC);
18498     return SetCC.getOperand(3);
18499   }
18500   }
18501
18502   return SDValue();
18503 }
18504
18505 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18506 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18507                                   TargetLowering::DAGCombinerInfo &DCI,
18508                                   const X86Subtarget *Subtarget) {
18509   SDLoc DL(N);
18510
18511   // If the flag operand isn't dead, don't touch this CMOV.
18512   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18513     return SDValue();
18514
18515   SDValue FalseOp = N->getOperand(0);
18516   SDValue TrueOp = N->getOperand(1);
18517   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18518   SDValue Cond = N->getOperand(3);
18519
18520   if (CC == X86::COND_E || CC == X86::COND_NE) {
18521     switch (Cond.getOpcode()) {
18522     default: break;
18523     case X86ISD::BSR:
18524     case X86ISD::BSF:
18525       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18526       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18527         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18528     }
18529   }
18530
18531   SDValue Flags;
18532
18533   Flags = checkBoolTestSetCCCombine(Cond, CC);
18534   if (Flags.getNode() &&
18535       // Extra check as FCMOV only supports a subset of X86 cond.
18536       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18537     SDValue Ops[] = { FalseOp, TrueOp,
18538                       DAG.getConstant(CC, MVT::i8), Flags };
18539     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18540   }
18541
18542   // If this is a select between two integer constants, try to do some
18543   // optimizations.  Note that the operands are ordered the opposite of SELECT
18544   // operands.
18545   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18546     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18547       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18548       // larger than FalseC (the false value).
18549       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18550         CC = X86::GetOppositeBranchCondition(CC);
18551         std::swap(TrueC, FalseC);
18552         std::swap(TrueOp, FalseOp);
18553       }
18554
18555       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18556       // This is efficient for any integer data type (including i8/i16) and
18557       // shift amount.
18558       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18559         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18560                            DAG.getConstant(CC, MVT::i8), Cond);
18561
18562         // Zero extend the condition if needed.
18563         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18564
18565         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18566         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18567                            DAG.getConstant(ShAmt, MVT::i8));
18568         if (N->getNumValues() == 2)  // Dead flag value?
18569           return DCI.CombineTo(N, Cond, SDValue());
18570         return Cond;
18571       }
18572
18573       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18574       // for any integer data type, including i8/i16.
18575       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18576         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18577                            DAG.getConstant(CC, MVT::i8), Cond);
18578
18579         // Zero extend the condition if needed.
18580         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18581                            FalseC->getValueType(0), Cond);
18582         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18583                            SDValue(FalseC, 0));
18584
18585         if (N->getNumValues() == 2)  // Dead flag value?
18586           return DCI.CombineTo(N, Cond, SDValue());
18587         return Cond;
18588       }
18589
18590       // Optimize cases that will turn into an LEA instruction.  This requires
18591       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18592       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18593         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18594         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18595
18596         bool isFastMultiplier = false;
18597         if (Diff < 10) {
18598           switch ((unsigned char)Diff) {
18599           default: break;
18600           case 1:  // result = add base, cond
18601           case 2:  // result = lea base(    , cond*2)
18602           case 3:  // result = lea base(cond, cond*2)
18603           case 4:  // result = lea base(    , cond*4)
18604           case 5:  // result = lea base(cond, cond*4)
18605           case 8:  // result = lea base(    , cond*8)
18606           case 9:  // result = lea base(cond, cond*8)
18607             isFastMultiplier = true;
18608             break;
18609           }
18610         }
18611
18612         if (isFastMultiplier) {
18613           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18614           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18615                              DAG.getConstant(CC, MVT::i8), Cond);
18616           // Zero extend the condition if needed.
18617           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18618                              Cond);
18619           // Scale the condition by the difference.
18620           if (Diff != 1)
18621             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18622                                DAG.getConstant(Diff, Cond.getValueType()));
18623
18624           // Add the base if non-zero.
18625           if (FalseC->getAPIntValue() != 0)
18626             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18627                                SDValue(FalseC, 0));
18628           if (N->getNumValues() == 2)  // Dead flag value?
18629             return DCI.CombineTo(N, Cond, SDValue());
18630           return Cond;
18631         }
18632       }
18633     }
18634   }
18635
18636   // Handle these cases:
18637   //   (select (x != c), e, c) -> select (x != c), e, x),
18638   //   (select (x == c), c, e) -> select (x == c), x, e)
18639   // where the c is an integer constant, and the "select" is the combination
18640   // of CMOV and CMP.
18641   //
18642   // The rationale for this change is that the conditional-move from a constant
18643   // needs two instructions, however, conditional-move from a register needs
18644   // only one instruction.
18645   //
18646   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18647   //  some instruction-combining opportunities. This opt needs to be
18648   //  postponed as late as possible.
18649   //
18650   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18651     // the DCI.xxxx conditions are provided to postpone the optimization as
18652     // late as possible.
18653
18654     ConstantSDNode *CmpAgainst = nullptr;
18655     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18656         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18657         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18658
18659       if (CC == X86::COND_NE &&
18660           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18661         CC = X86::GetOppositeBranchCondition(CC);
18662         std::swap(TrueOp, FalseOp);
18663       }
18664
18665       if (CC == X86::COND_E &&
18666           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18667         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18668                           DAG.getConstant(CC, MVT::i8), Cond };
18669         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18670       }
18671     }
18672   }
18673
18674   return SDValue();
18675 }
18676
18677 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18678                                                 const X86Subtarget *Subtarget) {
18679   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18680   switch (IntNo) {
18681   default: return SDValue();
18682   // SSE/AVX/AVX2 blend intrinsics.
18683   case Intrinsic::x86_avx2_pblendvb:
18684   case Intrinsic::x86_avx2_pblendw:
18685   case Intrinsic::x86_avx2_pblendd_128:
18686   case Intrinsic::x86_avx2_pblendd_256:
18687     // Don't try to simplify this intrinsic if we don't have AVX2.
18688     if (!Subtarget->hasAVX2())
18689       return SDValue();
18690     // FALL-THROUGH
18691   case Intrinsic::x86_avx_blend_pd_256:
18692   case Intrinsic::x86_avx_blend_ps_256:
18693   case Intrinsic::x86_avx_blendv_pd_256:
18694   case Intrinsic::x86_avx_blendv_ps_256:
18695     // Don't try to simplify this intrinsic if we don't have AVX.
18696     if (!Subtarget->hasAVX())
18697       return SDValue();
18698     // FALL-THROUGH
18699   case Intrinsic::x86_sse41_pblendw:
18700   case Intrinsic::x86_sse41_blendpd:
18701   case Intrinsic::x86_sse41_blendps:
18702   case Intrinsic::x86_sse41_blendvps:
18703   case Intrinsic::x86_sse41_blendvpd:
18704   case Intrinsic::x86_sse41_pblendvb: {
18705     SDValue Op0 = N->getOperand(1);
18706     SDValue Op1 = N->getOperand(2);
18707     SDValue Mask = N->getOperand(3);
18708
18709     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18710     if (!Subtarget->hasSSE41())
18711       return SDValue();
18712
18713     // fold (blend A, A, Mask) -> A
18714     if (Op0 == Op1)
18715       return Op0;
18716     // fold (blend A, B, allZeros) -> A
18717     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18718       return Op0;
18719     // fold (blend A, B, allOnes) -> B
18720     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18721       return Op1;
18722     
18723     // Simplify the case where the mask is a constant i32 value.
18724     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18725       if (C->isNullValue())
18726         return Op0;
18727       if (C->isAllOnesValue())
18728         return Op1;
18729     }
18730   }
18731
18732   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18733   case Intrinsic::x86_sse2_psrai_w:
18734   case Intrinsic::x86_sse2_psrai_d:
18735   case Intrinsic::x86_avx2_psrai_w:
18736   case Intrinsic::x86_avx2_psrai_d:
18737   case Intrinsic::x86_sse2_psra_w:
18738   case Intrinsic::x86_sse2_psra_d:
18739   case Intrinsic::x86_avx2_psra_w:
18740   case Intrinsic::x86_avx2_psra_d: {
18741     SDValue Op0 = N->getOperand(1);
18742     SDValue Op1 = N->getOperand(2);
18743     EVT VT = Op0.getValueType();
18744     assert(VT.isVector() && "Expected a vector type!");
18745
18746     if (isa<BuildVectorSDNode>(Op1))
18747       Op1 = Op1.getOperand(0);
18748
18749     if (!isa<ConstantSDNode>(Op1))
18750       return SDValue();
18751
18752     EVT SVT = VT.getVectorElementType();
18753     unsigned SVTBits = SVT.getSizeInBits();
18754
18755     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18756     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18757     uint64_t ShAmt = C.getZExtValue();
18758
18759     // Don't try to convert this shift into a ISD::SRA if the shift
18760     // count is bigger than or equal to the element size.
18761     if (ShAmt >= SVTBits)
18762       return SDValue();
18763
18764     // Trivial case: if the shift count is zero, then fold this
18765     // into the first operand.
18766     if (ShAmt == 0)
18767       return Op0;
18768
18769     // Replace this packed shift intrinsic with a target independent
18770     // shift dag node.
18771     SDValue Splat = DAG.getConstant(C, VT);
18772     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18773   }
18774   }
18775 }
18776
18777 /// PerformMulCombine - Optimize a single multiply with constant into two
18778 /// in order to implement it with two cheaper instructions, e.g.
18779 /// LEA + SHL, LEA + LEA.
18780 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18781                                  TargetLowering::DAGCombinerInfo &DCI) {
18782   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18783     return SDValue();
18784
18785   EVT VT = N->getValueType(0);
18786   if (VT != MVT::i64)
18787     return SDValue();
18788
18789   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18790   if (!C)
18791     return SDValue();
18792   uint64_t MulAmt = C->getZExtValue();
18793   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18794     return SDValue();
18795
18796   uint64_t MulAmt1 = 0;
18797   uint64_t MulAmt2 = 0;
18798   if ((MulAmt % 9) == 0) {
18799     MulAmt1 = 9;
18800     MulAmt2 = MulAmt / 9;
18801   } else if ((MulAmt % 5) == 0) {
18802     MulAmt1 = 5;
18803     MulAmt2 = MulAmt / 5;
18804   } else if ((MulAmt % 3) == 0) {
18805     MulAmt1 = 3;
18806     MulAmt2 = MulAmt / 3;
18807   }
18808   if (MulAmt2 &&
18809       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18810     SDLoc DL(N);
18811
18812     if (isPowerOf2_64(MulAmt2) &&
18813         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18814       // If second multiplifer is pow2, issue it first. We want the multiply by
18815       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18816       // is an add.
18817       std::swap(MulAmt1, MulAmt2);
18818
18819     SDValue NewMul;
18820     if (isPowerOf2_64(MulAmt1))
18821       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18822                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18823     else
18824       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18825                            DAG.getConstant(MulAmt1, VT));
18826
18827     if (isPowerOf2_64(MulAmt2))
18828       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18829                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18830     else
18831       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18832                            DAG.getConstant(MulAmt2, VT));
18833
18834     // Do not add new nodes to DAG combiner worklist.
18835     DCI.CombineTo(N, NewMul, false);
18836   }
18837   return SDValue();
18838 }
18839
18840 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18841   SDValue N0 = N->getOperand(0);
18842   SDValue N1 = N->getOperand(1);
18843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18844   EVT VT = N0.getValueType();
18845
18846   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18847   // since the result of setcc_c is all zero's or all ones.
18848   if (VT.isInteger() && !VT.isVector() &&
18849       N1C && N0.getOpcode() == ISD::AND &&
18850       N0.getOperand(1).getOpcode() == ISD::Constant) {
18851     SDValue N00 = N0.getOperand(0);
18852     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18853         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18854           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18855          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18856       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18857       APInt ShAmt = N1C->getAPIntValue();
18858       Mask = Mask.shl(ShAmt);
18859       if (Mask != 0)
18860         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18861                            N00, DAG.getConstant(Mask, VT));
18862     }
18863   }
18864
18865   // Hardware support for vector shifts is sparse which makes us scalarize the
18866   // vector operations in many cases. Also, on sandybridge ADD is faster than
18867   // shl.
18868   // (shl V, 1) -> add V,V
18869   if (isSplatVector(N1.getNode())) {
18870     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18871     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18872     // We shift all of the values by one. In many cases we do not have
18873     // hardware support for this operation. This is better expressed as an ADD
18874     // of two values.
18875     if (N1C && (1 == N1C->getZExtValue())) {
18876       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18877     }
18878   }
18879
18880   return SDValue();
18881 }
18882
18883 /// \brief Returns a vector of 0s if the node in input is a vector logical
18884 /// shift by a constant amount which is known to be bigger than or equal
18885 /// to the vector element size in bits.
18886 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18887                                       const X86Subtarget *Subtarget) {
18888   EVT VT = N->getValueType(0);
18889
18890   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18891       (!Subtarget->hasInt256() ||
18892        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18893     return SDValue();
18894
18895   SDValue Amt = N->getOperand(1);
18896   SDLoc DL(N);
18897   if (isSplatVector(Amt.getNode())) {
18898     SDValue SclrAmt = Amt->getOperand(0);
18899     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18900       APInt ShiftAmt = C->getAPIntValue();
18901       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18902
18903       // SSE2/AVX2 logical shifts always return a vector of 0s
18904       // if the shift amount is bigger than or equal to
18905       // the element size. The constant shift amount will be
18906       // encoded as a 8-bit immediate.
18907       if (ShiftAmt.trunc(8).uge(MaxAmount))
18908         return getZeroVector(VT, Subtarget, DAG, DL);
18909     }
18910   }
18911
18912   return SDValue();
18913 }
18914
18915 /// PerformShiftCombine - Combine shifts.
18916 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18917                                    TargetLowering::DAGCombinerInfo &DCI,
18918                                    const X86Subtarget *Subtarget) {
18919   if (N->getOpcode() == ISD::SHL) {
18920     SDValue V = PerformSHLCombine(N, DAG);
18921     if (V.getNode()) return V;
18922   }
18923
18924   if (N->getOpcode() != ISD::SRA) {
18925     // Try to fold this logical shift into a zero vector.
18926     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18927     if (V.getNode()) return V;
18928   }
18929
18930   return SDValue();
18931 }
18932
18933 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18934 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18935 // and friends.  Likewise for OR -> CMPNEQSS.
18936 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18937                             TargetLowering::DAGCombinerInfo &DCI,
18938                             const X86Subtarget *Subtarget) {
18939   unsigned opcode;
18940
18941   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18942   // we're requiring SSE2 for both.
18943   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18944     SDValue N0 = N->getOperand(0);
18945     SDValue N1 = N->getOperand(1);
18946     SDValue CMP0 = N0->getOperand(1);
18947     SDValue CMP1 = N1->getOperand(1);
18948     SDLoc DL(N);
18949
18950     // The SETCCs should both refer to the same CMP.
18951     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18952       return SDValue();
18953
18954     SDValue CMP00 = CMP0->getOperand(0);
18955     SDValue CMP01 = CMP0->getOperand(1);
18956     EVT     VT    = CMP00.getValueType();
18957
18958     if (VT == MVT::f32 || VT == MVT::f64) {
18959       bool ExpectingFlags = false;
18960       // Check for any users that want flags:
18961       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18962            !ExpectingFlags && UI != UE; ++UI)
18963         switch (UI->getOpcode()) {
18964         default:
18965         case ISD::BR_CC:
18966         case ISD::BRCOND:
18967         case ISD::SELECT:
18968           ExpectingFlags = true;
18969           break;
18970         case ISD::CopyToReg:
18971         case ISD::SIGN_EXTEND:
18972         case ISD::ZERO_EXTEND:
18973         case ISD::ANY_EXTEND:
18974           break;
18975         }
18976
18977       if (!ExpectingFlags) {
18978         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18979         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18980
18981         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18982           X86::CondCode tmp = cc0;
18983           cc0 = cc1;
18984           cc1 = tmp;
18985         }
18986
18987         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18988             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18989           // FIXME: need symbolic constants for these magic numbers.
18990           // See X86ATTInstPrinter.cpp:printSSECC().
18991           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18992           if (Subtarget->hasAVX512()) {
18993             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18994                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18995             if (N->getValueType(0) != MVT::i1)
18996               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18997                                  FSetCC);
18998             return FSetCC;
18999           }
19000           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19001                                               CMP00.getValueType(), CMP00, CMP01,
19002                                               DAG.getConstant(x86cc, MVT::i8));
19003
19004           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19005           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19006
19007           if (is64BitFP && !Subtarget->is64Bit()) {
19008             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19009             // 64-bit integer, since that's not a legal type. Since
19010             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19011             // bits, but can do this little dance to extract the lowest 32 bits
19012             // and work with those going forward.
19013             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19014                                            OnesOrZeroesF);
19015             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19016                                            Vector64);
19017             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19018                                         Vector32, DAG.getIntPtrConstant(0));
19019             IntVT = MVT::i32;
19020           }
19021
19022           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19023           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19024                                       DAG.getConstant(1, IntVT));
19025           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19026           return OneBitOfTruth;
19027         }
19028       }
19029     }
19030   }
19031   return SDValue();
19032 }
19033
19034 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19035 /// so it can be folded inside ANDNP.
19036 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19037   EVT VT = N->getValueType(0);
19038
19039   // Match direct AllOnes for 128 and 256-bit vectors
19040   if (ISD::isBuildVectorAllOnes(N))
19041     return true;
19042
19043   // Look through a bit convert.
19044   if (N->getOpcode() == ISD::BITCAST)
19045     N = N->getOperand(0).getNode();
19046
19047   // Sometimes the operand may come from a insert_subvector building a 256-bit
19048   // allones vector
19049   if (VT.is256BitVector() &&
19050       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19051     SDValue V1 = N->getOperand(0);
19052     SDValue V2 = N->getOperand(1);
19053
19054     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19055         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19056         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19057         ISD::isBuildVectorAllOnes(V2.getNode()))
19058       return true;
19059   }
19060
19061   return false;
19062 }
19063
19064 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19065 // register. In most cases we actually compare or select YMM-sized registers
19066 // and mixing the two types creates horrible code. This method optimizes
19067 // some of the transition sequences.
19068 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19069                                  TargetLowering::DAGCombinerInfo &DCI,
19070                                  const X86Subtarget *Subtarget) {
19071   EVT VT = N->getValueType(0);
19072   if (!VT.is256BitVector())
19073     return SDValue();
19074
19075   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19076           N->getOpcode() == ISD::ZERO_EXTEND ||
19077           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19078
19079   SDValue Narrow = N->getOperand(0);
19080   EVT NarrowVT = Narrow->getValueType(0);
19081   if (!NarrowVT.is128BitVector())
19082     return SDValue();
19083
19084   if (Narrow->getOpcode() != ISD::XOR &&
19085       Narrow->getOpcode() != ISD::AND &&
19086       Narrow->getOpcode() != ISD::OR)
19087     return SDValue();
19088
19089   SDValue N0  = Narrow->getOperand(0);
19090   SDValue N1  = Narrow->getOperand(1);
19091   SDLoc DL(Narrow);
19092
19093   // The Left side has to be a trunc.
19094   if (N0.getOpcode() != ISD::TRUNCATE)
19095     return SDValue();
19096
19097   // The type of the truncated inputs.
19098   EVT WideVT = N0->getOperand(0)->getValueType(0);
19099   if (WideVT != VT)
19100     return SDValue();
19101
19102   // The right side has to be a 'trunc' or a constant vector.
19103   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19104   bool RHSConst = (isSplatVector(N1.getNode()) &&
19105                    isa<ConstantSDNode>(N1->getOperand(0)));
19106   if (!RHSTrunc && !RHSConst)
19107     return SDValue();
19108
19109   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19110
19111   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19112     return SDValue();
19113
19114   // Set N0 and N1 to hold the inputs to the new wide operation.
19115   N0 = N0->getOperand(0);
19116   if (RHSConst) {
19117     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19118                      N1->getOperand(0));
19119     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19120     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19121   } else if (RHSTrunc) {
19122     N1 = N1->getOperand(0);
19123   }
19124
19125   // Generate the wide operation.
19126   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19127   unsigned Opcode = N->getOpcode();
19128   switch (Opcode) {
19129   case ISD::ANY_EXTEND:
19130     return Op;
19131   case ISD::ZERO_EXTEND: {
19132     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19133     APInt Mask = APInt::getAllOnesValue(InBits);
19134     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19135     return DAG.getNode(ISD::AND, DL, VT,
19136                        Op, DAG.getConstant(Mask, VT));
19137   }
19138   case ISD::SIGN_EXTEND:
19139     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19140                        Op, DAG.getValueType(NarrowVT));
19141   default:
19142     llvm_unreachable("Unexpected opcode");
19143   }
19144 }
19145
19146 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19147                                  TargetLowering::DAGCombinerInfo &DCI,
19148                                  const X86Subtarget *Subtarget) {
19149   EVT VT = N->getValueType(0);
19150   if (DCI.isBeforeLegalizeOps())
19151     return SDValue();
19152
19153   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19154   if (R.getNode())
19155     return R;
19156
19157   // Create BEXTR instructions
19158   // BEXTR is ((X >> imm) & (2**size-1))
19159   if (VT == MVT::i32 || VT == MVT::i64) {
19160     SDValue N0 = N->getOperand(0);
19161     SDValue N1 = N->getOperand(1);
19162     SDLoc DL(N);
19163
19164     // Check for BEXTR.
19165     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19166         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19167       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19168       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19169       if (MaskNode && ShiftNode) {
19170         uint64_t Mask = MaskNode->getZExtValue();
19171         uint64_t Shift = ShiftNode->getZExtValue();
19172         if (isMask_64(Mask)) {
19173           uint64_t MaskSize = CountPopulation_64(Mask);
19174           if (Shift + MaskSize <= VT.getSizeInBits())
19175             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19176                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19177         }
19178       }
19179     } // BEXTR
19180
19181     return SDValue();
19182   }
19183
19184   // Want to form ANDNP nodes:
19185   // 1) In the hopes of then easily combining them with OR and AND nodes
19186   //    to form PBLEND/PSIGN.
19187   // 2) To match ANDN packed intrinsics
19188   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19189     return SDValue();
19190
19191   SDValue N0 = N->getOperand(0);
19192   SDValue N1 = N->getOperand(1);
19193   SDLoc DL(N);
19194
19195   // Check LHS for vnot
19196   if (N0.getOpcode() == ISD::XOR &&
19197       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19198       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19199     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19200
19201   // Check RHS for vnot
19202   if (N1.getOpcode() == ISD::XOR &&
19203       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19204       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19205     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19206
19207   return SDValue();
19208 }
19209
19210 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19211                                 TargetLowering::DAGCombinerInfo &DCI,
19212                                 const X86Subtarget *Subtarget) {
19213   if (DCI.isBeforeLegalizeOps())
19214     return SDValue();
19215
19216   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19217   if (R.getNode())
19218     return R;
19219
19220   SDValue N0 = N->getOperand(0);
19221   SDValue N1 = N->getOperand(1);
19222   EVT VT = N->getValueType(0);
19223
19224   // look for psign/blend
19225   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19226     if (!Subtarget->hasSSSE3() ||
19227         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19228       return SDValue();
19229
19230     // Canonicalize pandn to RHS
19231     if (N0.getOpcode() == X86ISD::ANDNP)
19232       std::swap(N0, N1);
19233     // or (and (m, y), (pandn m, x))
19234     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19235       SDValue Mask = N1.getOperand(0);
19236       SDValue X    = N1.getOperand(1);
19237       SDValue Y;
19238       if (N0.getOperand(0) == Mask)
19239         Y = N0.getOperand(1);
19240       if (N0.getOperand(1) == Mask)
19241         Y = N0.getOperand(0);
19242
19243       // Check to see if the mask appeared in both the AND and ANDNP and
19244       if (!Y.getNode())
19245         return SDValue();
19246
19247       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19248       // Look through mask bitcast.
19249       if (Mask.getOpcode() == ISD::BITCAST)
19250         Mask = Mask.getOperand(0);
19251       if (X.getOpcode() == ISD::BITCAST)
19252         X = X.getOperand(0);
19253       if (Y.getOpcode() == ISD::BITCAST)
19254         Y = Y.getOperand(0);
19255
19256       EVT MaskVT = Mask.getValueType();
19257
19258       // Validate that the Mask operand is a vector sra node.
19259       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19260       // there is no psrai.b
19261       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19262       unsigned SraAmt = ~0;
19263       if (Mask.getOpcode() == ISD::SRA) {
19264         SDValue Amt = Mask.getOperand(1);
19265         if (isSplatVector(Amt.getNode())) {
19266           SDValue SclrAmt = Amt->getOperand(0);
19267           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19268             SraAmt = C->getZExtValue();
19269         }
19270       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19271         SDValue SraC = Mask.getOperand(1);
19272         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19273       }
19274       if ((SraAmt + 1) != EltBits)
19275         return SDValue();
19276
19277       SDLoc DL(N);
19278
19279       // Now we know we at least have a plendvb with the mask val.  See if
19280       // we can form a psignb/w/d.
19281       // psign = x.type == y.type == mask.type && y = sub(0, x);
19282       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19283           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19284           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19285         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19286                "Unsupported VT for PSIGN");
19287         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19288         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19289       }
19290       // PBLENDVB only available on SSE 4.1
19291       if (!Subtarget->hasSSE41())
19292         return SDValue();
19293
19294       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19295
19296       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19297       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19298       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19299       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19300       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19301     }
19302   }
19303
19304   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19305     return SDValue();
19306
19307   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19308   MachineFunction &MF = DAG.getMachineFunction();
19309   bool OptForSize = MF.getFunction()->getAttributes().
19310     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19311
19312   // SHLD/SHRD instructions have lower register pressure, but on some
19313   // platforms they have higher latency than the equivalent
19314   // series of shifts/or that would otherwise be generated.
19315   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19316   // have higher latencies and we are not optimizing for size.
19317   if (!OptForSize && Subtarget->isSHLDSlow())
19318     return SDValue();
19319
19320   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19321     std::swap(N0, N1);
19322   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19323     return SDValue();
19324   if (!N0.hasOneUse() || !N1.hasOneUse())
19325     return SDValue();
19326
19327   SDValue ShAmt0 = N0.getOperand(1);
19328   if (ShAmt0.getValueType() != MVT::i8)
19329     return SDValue();
19330   SDValue ShAmt1 = N1.getOperand(1);
19331   if (ShAmt1.getValueType() != MVT::i8)
19332     return SDValue();
19333   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19334     ShAmt0 = ShAmt0.getOperand(0);
19335   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19336     ShAmt1 = ShAmt1.getOperand(0);
19337
19338   SDLoc DL(N);
19339   unsigned Opc = X86ISD::SHLD;
19340   SDValue Op0 = N0.getOperand(0);
19341   SDValue Op1 = N1.getOperand(0);
19342   if (ShAmt0.getOpcode() == ISD::SUB) {
19343     Opc = X86ISD::SHRD;
19344     std::swap(Op0, Op1);
19345     std::swap(ShAmt0, ShAmt1);
19346   }
19347
19348   unsigned Bits = VT.getSizeInBits();
19349   if (ShAmt1.getOpcode() == ISD::SUB) {
19350     SDValue Sum = ShAmt1.getOperand(0);
19351     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19352       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19353       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19354         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19355       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19356         return DAG.getNode(Opc, DL, VT,
19357                            Op0, Op1,
19358                            DAG.getNode(ISD::TRUNCATE, DL,
19359                                        MVT::i8, ShAmt0));
19360     }
19361   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19362     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19363     if (ShAmt0C &&
19364         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19365       return DAG.getNode(Opc, DL, VT,
19366                          N0.getOperand(0), N1.getOperand(0),
19367                          DAG.getNode(ISD::TRUNCATE, DL,
19368                                        MVT::i8, ShAmt0));
19369   }
19370
19371   return SDValue();
19372 }
19373
19374 // Generate NEG and CMOV for integer abs.
19375 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19376   EVT VT = N->getValueType(0);
19377
19378   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19379   // 8-bit integer abs to NEG and CMOV.
19380   if (VT.isInteger() && VT.getSizeInBits() == 8)
19381     return SDValue();
19382
19383   SDValue N0 = N->getOperand(0);
19384   SDValue N1 = N->getOperand(1);
19385   SDLoc DL(N);
19386
19387   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19388   // and change it to SUB and CMOV.
19389   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19390       N0.getOpcode() == ISD::ADD &&
19391       N0.getOperand(1) == N1 &&
19392       N1.getOpcode() == ISD::SRA &&
19393       N1.getOperand(0) == N0.getOperand(0))
19394     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19395       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19396         // Generate SUB & CMOV.
19397         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19398                                   DAG.getConstant(0, VT), N0.getOperand(0));
19399
19400         SDValue Ops[] = { N0.getOperand(0), Neg,
19401                           DAG.getConstant(X86::COND_GE, MVT::i8),
19402                           SDValue(Neg.getNode(), 1) };
19403         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19404       }
19405   return SDValue();
19406 }
19407
19408 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19409 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19410                                  TargetLowering::DAGCombinerInfo &DCI,
19411                                  const X86Subtarget *Subtarget) {
19412   if (DCI.isBeforeLegalizeOps())
19413     return SDValue();
19414
19415   if (Subtarget->hasCMov()) {
19416     SDValue RV = performIntegerAbsCombine(N, DAG);
19417     if (RV.getNode())
19418       return RV;
19419   }
19420
19421   return SDValue();
19422 }
19423
19424 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19425 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19426                                   TargetLowering::DAGCombinerInfo &DCI,
19427                                   const X86Subtarget *Subtarget) {
19428   LoadSDNode *Ld = cast<LoadSDNode>(N);
19429   EVT RegVT = Ld->getValueType(0);
19430   EVT MemVT = Ld->getMemoryVT();
19431   SDLoc dl(Ld);
19432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19433   unsigned RegSz = RegVT.getSizeInBits();
19434
19435   // On Sandybridge unaligned 256bit loads are inefficient.
19436   ISD::LoadExtType Ext = Ld->getExtensionType();
19437   unsigned Alignment = Ld->getAlignment();
19438   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19439   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19440       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19441     unsigned NumElems = RegVT.getVectorNumElements();
19442     if (NumElems < 2)
19443       return SDValue();
19444
19445     SDValue Ptr = Ld->getBasePtr();
19446     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19447
19448     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19449                                   NumElems/2);
19450     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19451                                 Ld->getPointerInfo(), Ld->isVolatile(),
19452                                 Ld->isNonTemporal(), Ld->isInvariant(),
19453                                 Alignment);
19454     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19455     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19456                                 Ld->getPointerInfo(), Ld->isVolatile(),
19457                                 Ld->isNonTemporal(), Ld->isInvariant(),
19458                                 std::min(16U, Alignment));
19459     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19460                              Load1.getValue(1),
19461                              Load2.getValue(1));
19462
19463     SDValue NewVec = DAG.getUNDEF(RegVT);
19464     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19465     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19466     return DCI.CombineTo(N, NewVec, TF, true);
19467   }
19468
19469   // If this is a vector EXT Load then attempt to optimize it using a
19470   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19471   // expansion is still better than scalar code.
19472   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19473   // emit a shuffle and a arithmetic shift.
19474   // TODO: It is possible to support ZExt by zeroing the undef values
19475   // during the shuffle phase or after the shuffle.
19476   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19477       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19478     assert(MemVT != RegVT && "Cannot extend to the same type");
19479     assert(MemVT.isVector() && "Must load a vector from memory");
19480
19481     unsigned NumElems = RegVT.getVectorNumElements();
19482     unsigned MemSz = MemVT.getSizeInBits();
19483     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19484
19485     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19486       return SDValue();
19487
19488     // All sizes must be a power of two.
19489     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19490       return SDValue();
19491
19492     // Attempt to load the original value using scalar loads.
19493     // Find the largest scalar type that divides the total loaded size.
19494     MVT SclrLoadTy = MVT::i8;
19495     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19496          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19497       MVT Tp = (MVT::SimpleValueType)tp;
19498       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19499         SclrLoadTy = Tp;
19500       }
19501     }
19502
19503     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19504     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19505         (64 <= MemSz))
19506       SclrLoadTy = MVT::f64;
19507
19508     // Calculate the number of scalar loads that we need to perform
19509     // in order to load our vector from memory.
19510     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19511     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19512       return SDValue();
19513
19514     unsigned loadRegZize = RegSz;
19515     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19516       loadRegZize /= 2;
19517
19518     // Represent our vector as a sequence of elements which are the
19519     // largest scalar that we can load.
19520     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19521       loadRegZize/SclrLoadTy.getSizeInBits());
19522
19523     // Represent the data using the same element type that is stored in
19524     // memory. In practice, we ''widen'' MemVT.
19525     EVT WideVecVT =
19526           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19527                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19528
19529     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19530       "Invalid vector type");
19531
19532     // We can't shuffle using an illegal type.
19533     if (!TLI.isTypeLegal(WideVecVT))
19534       return SDValue();
19535
19536     SmallVector<SDValue, 8> Chains;
19537     SDValue Ptr = Ld->getBasePtr();
19538     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19539                                         TLI.getPointerTy());
19540     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19541
19542     for (unsigned i = 0; i < NumLoads; ++i) {
19543       // Perform a single load.
19544       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19545                                        Ptr, Ld->getPointerInfo(),
19546                                        Ld->isVolatile(), Ld->isNonTemporal(),
19547                                        Ld->isInvariant(), Ld->getAlignment());
19548       Chains.push_back(ScalarLoad.getValue(1));
19549       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19550       // another round of DAGCombining.
19551       if (i == 0)
19552         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19553       else
19554         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19555                           ScalarLoad, DAG.getIntPtrConstant(i));
19556
19557       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19558     }
19559
19560     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19561
19562     // Bitcast the loaded value to a vector of the original element type, in
19563     // the size of the target vector type.
19564     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19565     unsigned SizeRatio = RegSz/MemSz;
19566
19567     if (Ext == ISD::SEXTLOAD) {
19568       // If we have SSE4.1 we can directly emit a VSEXT node.
19569       if (Subtarget->hasSSE41()) {
19570         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19571         return DCI.CombineTo(N, Sext, TF, true);
19572       }
19573
19574       // Otherwise we'll shuffle the small elements in the high bits of the
19575       // larger type and perform an arithmetic shift. If the shift is not legal
19576       // it's better to scalarize.
19577       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19578         return SDValue();
19579
19580       // Redistribute the loaded elements into the different locations.
19581       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19582       for (unsigned i = 0; i != NumElems; ++i)
19583         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19584
19585       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19586                                            DAG.getUNDEF(WideVecVT),
19587                                            &ShuffleVec[0]);
19588
19589       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19590
19591       // Build the arithmetic shift.
19592       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19593                      MemVT.getVectorElementType().getSizeInBits();
19594       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19595                           DAG.getConstant(Amt, RegVT));
19596
19597       return DCI.CombineTo(N, Shuff, TF, true);
19598     }
19599
19600     // Redistribute the loaded elements into the different locations.
19601     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19602     for (unsigned i = 0; i != NumElems; ++i)
19603       ShuffleVec[i*SizeRatio] = i;
19604
19605     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19606                                          DAG.getUNDEF(WideVecVT),
19607                                          &ShuffleVec[0]);
19608
19609     // Bitcast to the requested type.
19610     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19611     // Replace the original load with the new sequence
19612     // and return the new chain.
19613     return DCI.CombineTo(N, Shuff, TF, true);
19614   }
19615
19616   return SDValue();
19617 }
19618
19619 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19620 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19621                                    const X86Subtarget *Subtarget) {
19622   StoreSDNode *St = cast<StoreSDNode>(N);
19623   EVT VT = St->getValue().getValueType();
19624   EVT StVT = St->getMemoryVT();
19625   SDLoc dl(St);
19626   SDValue StoredVal = St->getOperand(1);
19627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19628
19629   // If we are saving a concatenation of two XMM registers, perform two stores.
19630   // On Sandy Bridge, 256-bit memory operations are executed by two
19631   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19632   // memory  operation.
19633   unsigned Alignment = St->getAlignment();
19634   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19635   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19636       StVT == VT && !IsAligned) {
19637     unsigned NumElems = VT.getVectorNumElements();
19638     if (NumElems < 2)
19639       return SDValue();
19640
19641     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19642     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19643
19644     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19645     SDValue Ptr0 = St->getBasePtr();
19646     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19647
19648     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19649                                 St->getPointerInfo(), St->isVolatile(),
19650                                 St->isNonTemporal(), Alignment);
19651     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19652                                 St->getPointerInfo(), St->isVolatile(),
19653                                 St->isNonTemporal(),
19654                                 std::min(16U, Alignment));
19655     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19656   }
19657
19658   // Optimize trunc store (of multiple scalars) to shuffle and store.
19659   // First, pack all of the elements in one place. Next, store to memory
19660   // in fewer chunks.
19661   if (St->isTruncatingStore() && VT.isVector()) {
19662     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19663     unsigned NumElems = VT.getVectorNumElements();
19664     assert(StVT != VT && "Cannot truncate to the same type");
19665     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19666     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19667
19668     // From, To sizes and ElemCount must be pow of two
19669     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19670     // We are going to use the original vector elt for storing.
19671     // Accumulated smaller vector elements must be a multiple of the store size.
19672     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19673
19674     unsigned SizeRatio  = FromSz / ToSz;
19675
19676     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19677
19678     // Create a type on which we perform the shuffle
19679     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19680             StVT.getScalarType(), NumElems*SizeRatio);
19681
19682     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19683
19684     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19685     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19686     for (unsigned i = 0; i != NumElems; ++i)
19687       ShuffleVec[i] = i * SizeRatio;
19688
19689     // Can't shuffle using an illegal type.
19690     if (!TLI.isTypeLegal(WideVecVT))
19691       return SDValue();
19692
19693     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19694                                          DAG.getUNDEF(WideVecVT),
19695                                          &ShuffleVec[0]);
19696     // At this point all of the data is stored at the bottom of the
19697     // register. We now need to save it to mem.
19698
19699     // Find the largest store unit
19700     MVT StoreType = MVT::i8;
19701     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19702          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19703       MVT Tp = (MVT::SimpleValueType)tp;
19704       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19705         StoreType = Tp;
19706     }
19707
19708     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19709     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19710         (64 <= NumElems * ToSz))
19711       StoreType = MVT::f64;
19712
19713     // Bitcast the original vector into a vector of store-size units
19714     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19715             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19716     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19717     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19718     SmallVector<SDValue, 8> Chains;
19719     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19720                                         TLI.getPointerTy());
19721     SDValue Ptr = St->getBasePtr();
19722
19723     // Perform one or more big stores into memory.
19724     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19725       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19726                                    StoreType, ShuffWide,
19727                                    DAG.getIntPtrConstant(i));
19728       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19729                                 St->getPointerInfo(), St->isVolatile(),
19730                                 St->isNonTemporal(), St->getAlignment());
19731       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19732       Chains.push_back(Ch);
19733     }
19734
19735     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19736   }
19737
19738   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19739   // the FP state in cases where an emms may be missing.
19740   // A preferable solution to the general problem is to figure out the right
19741   // places to insert EMMS.  This qualifies as a quick hack.
19742
19743   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19744   if (VT.getSizeInBits() != 64)
19745     return SDValue();
19746
19747   const Function *F = DAG.getMachineFunction().getFunction();
19748   bool NoImplicitFloatOps = F->getAttributes().
19749     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19750   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19751                      && Subtarget->hasSSE2();
19752   if ((VT.isVector() ||
19753        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19754       isa<LoadSDNode>(St->getValue()) &&
19755       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19756       St->getChain().hasOneUse() && !St->isVolatile()) {
19757     SDNode* LdVal = St->getValue().getNode();
19758     LoadSDNode *Ld = nullptr;
19759     int TokenFactorIndex = -1;
19760     SmallVector<SDValue, 8> Ops;
19761     SDNode* ChainVal = St->getChain().getNode();
19762     // Must be a store of a load.  We currently handle two cases:  the load
19763     // is a direct child, and it's under an intervening TokenFactor.  It is
19764     // possible to dig deeper under nested TokenFactors.
19765     if (ChainVal == LdVal)
19766       Ld = cast<LoadSDNode>(St->getChain());
19767     else if (St->getValue().hasOneUse() &&
19768              ChainVal->getOpcode() == ISD::TokenFactor) {
19769       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19770         if (ChainVal->getOperand(i).getNode() == LdVal) {
19771           TokenFactorIndex = i;
19772           Ld = cast<LoadSDNode>(St->getValue());
19773         } else
19774           Ops.push_back(ChainVal->getOperand(i));
19775       }
19776     }
19777
19778     if (!Ld || !ISD::isNormalLoad(Ld))
19779       return SDValue();
19780
19781     // If this is not the MMX case, i.e. we are just turning i64 load/store
19782     // into f64 load/store, avoid the transformation if there are multiple
19783     // uses of the loaded value.
19784     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19785       return SDValue();
19786
19787     SDLoc LdDL(Ld);
19788     SDLoc StDL(N);
19789     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19790     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19791     // pair instead.
19792     if (Subtarget->is64Bit() || F64IsLegal) {
19793       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19794       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19795                                   Ld->getPointerInfo(), Ld->isVolatile(),
19796                                   Ld->isNonTemporal(), Ld->isInvariant(),
19797                                   Ld->getAlignment());
19798       SDValue NewChain = NewLd.getValue(1);
19799       if (TokenFactorIndex != -1) {
19800         Ops.push_back(NewChain);
19801         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19802       }
19803       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19804                           St->getPointerInfo(),
19805                           St->isVolatile(), St->isNonTemporal(),
19806                           St->getAlignment());
19807     }
19808
19809     // Otherwise, lower to two pairs of 32-bit loads / stores.
19810     SDValue LoAddr = Ld->getBasePtr();
19811     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19812                                  DAG.getConstant(4, MVT::i32));
19813
19814     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19815                                Ld->getPointerInfo(),
19816                                Ld->isVolatile(), Ld->isNonTemporal(),
19817                                Ld->isInvariant(), Ld->getAlignment());
19818     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19819                                Ld->getPointerInfo().getWithOffset(4),
19820                                Ld->isVolatile(), Ld->isNonTemporal(),
19821                                Ld->isInvariant(),
19822                                MinAlign(Ld->getAlignment(), 4));
19823
19824     SDValue NewChain = LoLd.getValue(1);
19825     if (TokenFactorIndex != -1) {
19826       Ops.push_back(LoLd);
19827       Ops.push_back(HiLd);
19828       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19829     }
19830
19831     LoAddr = St->getBasePtr();
19832     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19833                          DAG.getConstant(4, MVT::i32));
19834
19835     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19836                                 St->getPointerInfo(),
19837                                 St->isVolatile(), St->isNonTemporal(),
19838                                 St->getAlignment());
19839     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19840                                 St->getPointerInfo().getWithOffset(4),
19841                                 St->isVolatile(),
19842                                 St->isNonTemporal(),
19843                                 MinAlign(St->getAlignment(), 4));
19844     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19845   }
19846   return SDValue();
19847 }
19848
19849 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19850 /// and return the operands for the horizontal operation in LHS and RHS.  A
19851 /// horizontal operation performs the binary operation on successive elements
19852 /// of its first operand, then on successive elements of its second operand,
19853 /// returning the resulting values in a vector.  For example, if
19854 ///   A = < float a0, float a1, float a2, float a3 >
19855 /// and
19856 ///   B = < float b0, float b1, float b2, float b3 >
19857 /// then the result of doing a horizontal operation on A and B is
19858 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19859 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19860 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19861 /// set to A, RHS to B, and the routine returns 'true'.
19862 /// Note that the binary operation should have the property that if one of the
19863 /// operands is UNDEF then the result is UNDEF.
19864 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19865   // Look for the following pattern: if
19866   //   A = < float a0, float a1, float a2, float a3 >
19867   //   B = < float b0, float b1, float b2, float b3 >
19868   // and
19869   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19870   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19871   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19872   // which is A horizontal-op B.
19873
19874   // At least one of the operands should be a vector shuffle.
19875   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19876       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19877     return false;
19878
19879   MVT VT = LHS.getSimpleValueType();
19880
19881   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19882          "Unsupported vector type for horizontal add/sub");
19883
19884   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19885   // operate independently on 128-bit lanes.
19886   unsigned NumElts = VT.getVectorNumElements();
19887   unsigned NumLanes = VT.getSizeInBits()/128;
19888   unsigned NumLaneElts = NumElts / NumLanes;
19889   assert((NumLaneElts % 2 == 0) &&
19890          "Vector type should have an even number of elements in each lane");
19891   unsigned HalfLaneElts = NumLaneElts/2;
19892
19893   // View LHS in the form
19894   //   LHS = VECTOR_SHUFFLE A, B, LMask
19895   // If LHS is not a shuffle then pretend it is the shuffle
19896   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19897   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19898   // type VT.
19899   SDValue A, B;
19900   SmallVector<int, 16> LMask(NumElts);
19901   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19902     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19903       A = LHS.getOperand(0);
19904     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19905       B = LHS.getOperand(1);
19906     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19907     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19908   } else {
19909     if (LHS.getOpcode() != ISD::UNDEF)
19910       A = LHS;
19911     for (unsigned i = 0; i != NumElts; ++i)
19912       LMask[i] = i;
19913   }
19914
19915   // Likewise, view RHS in the form
19916   //   RHS = VECTOR_SHUFFLE C, D, RMask
19917   SDValue C, D;
19918   SmallVector<int, 16> RMask(NumElts);
19919   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19920     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19921       C = RHS.getOperand(0);
19922     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19923       D = RHS.getOperand(1);
19924     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19925     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19926   } else {
19927     if (RHS.getOpcode() != ISD::UNDEF)
19928       C = RHS;
19929     for (unsigned i = 0; i != NumElts; ++i)
19930       RMask[i] = i;
19931   }
19932
19933   // Check that the shuffles are both shuffling the same vectors.
19934   if (!(A == C && B == D) && !(A == D && B == C))
19935     return false;
19936
19937   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19938   if (!A.getNode() && !B.getNode())
19939     return false;
19940
19941   // If A and B occur in reverse order in RHS, then "swap" them (which means
19942   // rewriting the mask).
19943   if (A != C)
19944     CommuteVectorShuffleMask(RMask, NumElts);
19945
19946   // At this point LHS and RHS are equivalent to
19947   //   LHS = VECTOR_SHUFFLE A, B, LMask
19948   //   RHS = VECTOR_SHUFFLE A, B, RMask
19949   // Check that the masks correspond to performing a horizontal operation.
19950   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19951     for (unsigned i = 0; i != NumLaneElts; ++i) {
19952       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19953
19954       // Ignore any UNDEF components.
19955       if (LIdx < 0 || RIdx < 0 ||
19956           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19957           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19958         continue;
19959
19960       // Check that successive elements are being operated on.  If not, this is
19961       // not a horizontal operation.
19962       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19963       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19964       if (!(LIdx == Index && RIdx == Index + 1) &&
19965           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19966         return false;
19967     }
19968   }
19969
19970   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19971   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19972   return true;
19973 }
19974
19975 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19976 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19977                                   const X86Subtarget *Subtarget) {
19978   EVT VT = N->getValueType(0);
19979   SDValue LHS = N->getOperand(0);
19980   SDValue RHS = N->getOperand(1);
19981
19982   // Try to synthesize horizontal adds from adds of shuffles.
19983   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19984        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19985       isHorizontalBinOp(LHS, RHS, true))
19986     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19987   return SDValue();
19988 }
19989
19990 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19991 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19992                                   const X86Subtarget *Subtarget) {
19993   EVT VT = N->getValueType(0);
19994   SDValue LHS = N->getOperand(0);
19995   SDValue RHS = N->getOperand(1);
19996
19997   // Try to synthesize horizontal subs from subs of shuffles.
19998   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19999        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20000       isHorizontalBinOp(LHS, RHS, false))
20001     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20002   return SDValue();
20003 }
20004
20005 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20006 /// X86ISD::FXOR nodes.
20007 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20008   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20009   // F[X]OR(0.0, x) -> x
20010   // F[X]OR(x, 0.0) -> x
20011   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20012     if (C->getValueAPF().isPosZero())
20013       return N->getOperand(1);
20014   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20015     if (C->getValueAPF().isPosZero())
20016       return N->getOperand(0);
20017   return SDValue();
20018 }
20019
20020 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20021 /// X86ISD::FMAX nodes.
20022 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20023   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20024
20025   // Only perform optimizations if UnsafeMath is used.
20026   if (!DAG.getTarget().Options.UnsafeFPMath)
20027     return SDValue();
20028
20029   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20030   // into FMINC and FMAXC, which are Commutative operations.
20031   unsigned NewOp = 0;
20032   switch (N->getOpcode()) {
20033     default: llvm_unreachable("unknown opcode");
20034     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20035     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20036   }
20037
20038   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20039                      N->getOperand(0), N->getOperand(1));
20040 }
20041
20042 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20043 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20044   // FAND(0.0, x) -> 0.0
20045   // FAND(x, 0.0) -> 0.0
20046   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20047     if (C->getValueAPF().isPosZero())
20048       return N->getOperand(0);
20049   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20050     if (C->getValueAPF().isPosZero())
20051       return N->getOperand(1);
20052   return SDValue();
20053 }
20054
20055 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20056 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20057   // FANDN(x, 0.0) -> 0.0
20058   // FANDN(0.0, x) -> x
20059   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20060     if (C->getValueAPF().isPosZero())
20061       return N->getOperand(1);
20062   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20063     if (C->getValueAPF().isPosZero())
20064       return N->getOperand(1);
20065   return SDValue();
20066 }
20067
20068 static SDValue PerformBTCombine(SDNode *N,
20069                                 SelectionDAG &DAG,
20070                                 TargetLowering::DAGCombinerInfo &DCI) {
20071   // BT ignores high bits in the bit index operand.
20072   SDValue Op1 = N->getOperand(1);
20073   if (Op1.hasOneUse()) {
20074     unsigned BitWidth = Op1.getValueSizeInBits();
20075     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20076     APInt KnownZero, KnownOne;
20077     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20078                                           !DCI.isBeforeLegalizeOps());
20079     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20080     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20081         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20082       DCI.CommitTargetLoweringOpt(TLO);
20083   }
20084   return SDValue();
20085 }
20086
20087 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20088   SDValue Op = N->getOperand(0);
20089   if (Op.getOpcode() == ISD::BITCAST)
20090     Op = Op.getOperand(0);
20091   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20092   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20093       VT.getVectorElementType().getSizeInBits() ==
20094       OpVT.getVectorElementType().getSizeInBits()) {
20095     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20096   }
20097   return SDValue();
20098 }
20099
20100 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20101                                                const X86Subtarget *Subtarget) {
20102   EVT VT = N->getValueType(0);
20103   if (!VT.isVector())
20104     return SDValue();
20105
20106   SDValue N0 = N->getOperand(0);
20107   SDValue N1 = N->getOperand(1);
20108   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20109   SDLoc dl(N);
20110
20111   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20112   // both SSE and AVX2 since there is no sign-extended shift right
20113   // operation on a vector with 64-bit elements.
20114   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20115   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20116   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20117       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20118     SDValue N00 = N0.getOperand(0);
20119
20120     // EXTLOAD has a better solution on AVX2,
20121     // it may be replaced with X86ISD::VSEXT node.
20122     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20123       if (!ISD::isNormalLoad(N00.getNode()))
20124         return SDValue();
20125
20126     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20127         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20128                                   N00, N1);
20129       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20130     }
20131   }
20132   return SDValue();
20133 }
20134
20135 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20136                                   TargetLowering::DAGCombinerInfo &DCI,
20137                                   const X86Subtarget *Subtarget) {
20138   if (!DCI.isBeforeLegalizeOps())
20139     return SDValue();
20140
20141   if (!Subtarget->hasFp256())
20142     return SDValue();
20143
20144   EVT VT = N->getValueType(0);
20145   if (VT.isVector() && VT.getSizeInBits() == 256) {
20146     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20147     if (R.getNode())
20148       return R;
20149   }
20150
20151   return SDValue();
20152 }
20153
20154 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20155                                  const X86Subtarget* Subtarget) {
20156   SDLoc dl(N);
20157   EVT VT = N->getValueType(0);
20158
20159   // Let legalize expand this if it isn't a legal type yet.
20160   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20161     return SDValue();
20162
20163   EVT ScalarVT = VT.getScalarType();
20164   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20165       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20166     return SDValue();
20167
20168   SDValue A = N->getOperand(0);
20169   SDValue B = N->getOperand(1);
20170   SDValue C = N->getOperand(2);
20171
20172   bool NegA = (A.getOpcode() == ISD::FNEG);
20173   bool NegB = (B.getOpcode() == ISD::FNEG);
20174   bool NegC = (C.getOpcode() == ISD::FNEG);
20175
20176   // Negative multiplication when NegA xor NegB
20177   bool NegMul = (NegA != NegB);
20178   if (NegA)
20179     A = A.getOperand(0);
20180   if (NegB)
20181     B = B.getOperand(0);
20182   if (NegC)
20183     C = C.getOperand(0);
20184
20185   unsigned Opcode;
20186   if (!NegMul)
20187     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20188   else
20189     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20190
20191   return DAG.getNode(Opcode, dl, VT, A, B, C);
20192 }
20193
20194 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20195                                   TargetLowering::DAGCombinerInfo &DCI,
20196                                   const X86Subtarget *Subtarget) {
20197   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20198   //           (and (i32 x86isd::setcc_carry), 1)
20199   // This eliminates the zext. This transformation is necessary because
20200   // ISD::SETCC is always legalized to i8.
20201   SDLoc dl(N);
20202   SDValue N0 = N->getOperand(0);
20203   EVT VT = N->getValueType(0);
20204
20205   if (N0.getOpcode() == ISD::AND &&
20206       N0.hasOneUse() &&
20207       N0.getOperand(0).hasOneUse()) {
20208     SDValue N00 = N0.getOperand(0);
20209     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20210       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20211       if (!C || C->getZExtValue() != 1)
20212         return SDValue();
20213       return DAG.getNode(ISD::AND, dl, VT,
20214                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20215                                      N00.getOperand(0), N00.getOperand(1)),
20216                          DAG.getConstant(1, VT));
20217     }
20218   }
20219
20220   if (N0.getOpcode() == ISD::TRUNCATE &&
20221       N0.hasOneUse() &&
20222       N0.getOperand(0).hasOneUse()) {
20223     SDValue N00 = N0.getOperand(0);
20224     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20225       return DAG.getNode(ISD::AND, dl, VT,
20226                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20227                                      N00.getOperand(0), N00.getOperand(1)),
20228                          DAG.getConstant(1, VT));
20229     }
20230   }
20231   if (VT.is256BitVector()) {
20232     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20233     if (R.getNode())
20234       return R;
20235   }
20236
20237   return SDValue();
20238 }
20239
20240 // Optimize x == -y --> x+y == 0
20241 //          x != -y --> x+y != 0
20242 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20243                                       const X86Subtarget* Subtarget) {
20244   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20245   SDValue LHS = N->getOperand(0);
20246   SDValue RHS = N->getOperand(1);
20247   EVT VT = N->getValueType(0);
20248   SDLoc DL(N);
20249
20250   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20251     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20252       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20253         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20254                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20255         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20256                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20257       }
20258   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20259     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20260       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20261         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20262                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20263         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20264                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20265       }
20266
20267   if (VT.getScalarType() == MVT::i1) {
20268     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20269       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20270     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20271     if (!IsSEXT0 && !IsVZero0)
20272       return SDValue();
20273     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20274       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20275     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20276
20277     if (!IsSEXT1 && !IsVZero1)
20278       return SDValue();
20279
20280     if (IsSEXT0 && IsVZero1) {
20281       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20282       if (CC == ISD::SETEQ)
20283         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20284       return LHS.getOperand(0);
20285     }
20286     if (IsSEXT1 && IsVZero0) {
20287       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20288       if (CC == ISD::SETEQ)
20289         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20290       return RHS.getOperand(0);
20291     }
20292   }
20293
20294   return SDValue();
20295 }
20296
20297 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20298                                       const X86Subtarget *Subtarget) {
20299   SDLoc dl(N);
20300   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20301   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20302          "X86insertps is only defined for v4x32");
20303
20304   SDValue Ld = N->getOperand(1);
20305   if (MayFoldLoad(Ld)) {
20306     // Extract the countS bits from the immediate so we can get the proper
20307     // address when narrowing the vector load to a specific element.
20308     // When the second source op is a memory address, interps doesn't use
20309     // countS and just gets an f32 from that address.
20310     unsigned DestIndex =
20311         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20312     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20313   } else
20314     return SDValue();
20315
20316   // Create this as a scalar to vector to match the instruction pattern.
20317   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20318   // countS bits are ignored when loading from memory on insertps, which
20319   // means we don't need to explicitly set them to 0.
20320   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20321                      LoadScalarToVector, N->getOperand(2));
20322 }
20323
20324 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20325 // as "sbb reg,reg", since it can be extended without zext and produces
20326 // an all-ones bit which is more useful than 0/1 in some cases.
20327 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20328                                MVT VT) {
20329   if (VT == MVT::i8)
20330     return DAG.getNode(ISD::AND, DL, VT,
20331                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20332                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20333                        DAG.getConstant(1, VT));
20334   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20335   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20336                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20337                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20338 }
20339
20340 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20341 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20342                                    TargetLowering::DAGCombinerInfo &DCI,
20343                                    const X86Subtarget *Subtarget) {
20344   SDLoc DL(N);
20345   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20346   SDValue EFLAGS = N->getOperand(1);
20347
20348   if (CC == X86::COND_A) {
20349     // Try to convert COND_A into COND_B in an attempt to facilitate
20350     // materializing "setb reg".
20351     //
20352     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20353     // cannot take an immediate as its first operand.
20354     //
20355     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20356         EFLAGS.getValueType().isInteger() &&
20357         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20358       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20359                                    EFLAGS.getNode()->getVTList(),
20360                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20361       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20362       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20363     }
20364   }
20365
20366   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20367   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20368   // cases.
20369   if (CC == X86::COND_B)
20370     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20371
20372   SDValue Flags;
20373
20374   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20375   if (Flags.getNode()) {
20376     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20377     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20378   }
20379
20380   return SDValue();
20381 }
20382
20383 // Optimize branch condition evaluation.
20384 //
20385 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20386                                     TargetLowering::DAGCombinerInfo &DCI,
20387                                     const X86Subtarget *Subtarget) {
20388   SDLoc DL(N);
20389   SDValue Chain = N->getOperand(0);
20390   SDValue Dest = N->getOperand(1);
20391   SDValue EFLAGS = N->getOperand(3);
20392   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20393
20394   SDValue Flags;
20395
20396   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20397   if (Flags.getNode()) {
20398     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20399     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20400                        Flags);
20401   }
20402
20403   return SDValue();
20404 }
20405
20406 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20407                                         const X86TargetLowering *XTLI) {
20408   SDValue Op0 = N->getOperand(0);
20409   EVT InVT = Op0->getValueType(0);
20410
20411   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20412   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20413     SDLoc dl(N);
20414     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20415     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20416     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20417   }
20418
20419   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20420   // a 32-bit target where SSE doesn't support i64->FP operations.
20421   if (Op0.getOpcode() == ISD::LOAD) {
20422     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20423     EVT VT = Ld->getValueType(0);
20424     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20425         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20426         !XTLI->getSubtarget()->is64Bit() &&
20427         VT == MVT::i64) {
20428       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20429                                           Ld->getChain(), Op0, DAG);
20430       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20431       return FILDChain;
20432     }
20433   }
20434   return SDValue();
20435 }
20436
20437 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20438 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20439                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20440   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20441   // the result is either zero or one (depending on the input carry bit).
20442   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20443   if (X86::isZeroNode(N->getOperand(0)) &&
20444       X86::isZeroNode(N->getOperand(1)) &&
20445       // We don't have a good way to replace an EFLAGS use, so only do this when
20446       // dead right now.
20447       SDValue(N, 1).use_empty()) {
20448     SDLoc DL(N);
20449     EVT VT = N->getValueType(0);
20450     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20451     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20452                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20453                                            DAG.getConstant(X86::COND_B,MVT::i8),
20454                                            N->getOperand(2)),
20455                                DAG.getConstant(1, VT));
20456     return DCI.CombineTo(N, Res1, CarryOut);
20457   }
20458
20459   return SDValue();
20460 }
20461
20462 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20463 //      (add Y, (setne X, 0)) -> sbb -1, Y
20464 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20465 //      (sub (setne X, 0), Y) -> adc -1, Y
20466 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20467   SDLoc DL(N);
20468
20469   // Look through ZExts.
20470   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20471   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20472     return SDValue();
20473
20474   SDValue SetCC = Ext.getOperand(0);
20475   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20476     return SDValue();
20477
20478   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20479   if (CC != X86::COND_E && CC != X86::COND_NE)
20480     return SDValue();
20481
20482   SDValue Cmp = SetCC.getOperand(1);
20483   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20484       !X86::isZeroNode(Cmp.getOperand(1)) ||
20485       !Cmp.getOperand(0).getValueType().isInteger())
20486     return SDValue();
20487
20488   SDValue CmpOp0 = Cmp.getOperand(0);
20489   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20490                                DAG.getConstant(1, CmpOp0.getValueType()));
20491
20492   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20493   if (CC == X86::COND_NE)
20494     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20495                        DL, OtherVal.getValueType(), OtherVal,
20496                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20497   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20498                      DL, OtherVal.getValueType(), OtherVal,
20499                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20500 }
20501
20502 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20503 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20504                                  const X86Subtarget *Subtarget) {
20505   EVT VT = N->getValueType(0);
20506   SDValue Op0 = N->getOperand(0);
20507   SDValue Op1 = N->getOperand(1);
20508
20509   // Try to synthesize horizontal adds from adds of shuffles.
20510   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20511        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20512       isHorizontalBinOp(Op0, Op1, true))
20513     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20514
20515   return OptimizeConditionalInDecrement(N, DAG);
20516 }
20517
20518 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20519                                  const X86Subtarget *Subtarget) {
20520   SDValue Op0 = N->getOperand(0);
20521   SDValue Op1 = N->getOperand(1);
20522
20523   // X86 can't encode an immediate LHS of a sub. See if we can push the
20524   // negation into a preceding instruction.
20525   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20526     // If the RHS of the sub is a XOR with one use and a constant, invert the
20527     // immediate. Then add one to the LHS of the sub so we can turn
20528     // X-Y -> X+~Y+1, saving one register.
20529     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20530         isa<ConstantSDNode>(Op1.getOperand(1))) {
20531       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20532       EVT VT = Op0.getValueType();
20533       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20534                                    Op1.getOperand(0),
20535                                    DAG.getConstant(~XorC, VT));
20536       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20537                          DAG.getConstant(C->getAPIntValue()+1, VT));
20538     }
20539   }
20540
20541   // Try to synthesize horizontal adds from adds of shuffles.
20542   EVT VT = N->getValueType(0);
20543   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20544        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20545       isHorizontalBinOp(Op0, Op1, true))
20546     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20547
20548   return OptimizeConditionalInDecrement(N, DAG);
20549 }
20550
20551 /// performVZEXTCombine - Performs build vector combines
20552 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20553                                         TargetLowering::DAGCombinerInfo &DCI,
20554                                         const X86Subtarget *Subtarget) {
20555   // (vzext (bitcast (vzext (x)) -> (vzext x)
20556   SDValue In = N->getOperand(0);
20557   while (In.getOpcode() == ISD::BITCAST)
20558     In = In.getOperand(0);
20559
20560   if (In.getOpcode() != X86ISD::VZEXT)
20561     return SDValue();
20562
20563   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20564                      In.getOperand(0));
20565 }
20566
20567 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20568                                              DAGCombinerInfo &DCI) const {
20569   SelectionDAG &DAG = DCI.DAG;
20570   switch (N->getOpcode()) {
20571   default: break;
20572   case ISD::EXTRACT_VECTOR_ELT:
20573     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20574   case ISD::VSELECT:
20575   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20576   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20577   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20578   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20579   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20580   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20581   case ISD::SHL:
20582   case ISD::SRA:
20583   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20584   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20585   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20586   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20587   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20588   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20589   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20590   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20591   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20592   case X86ISD::FXOR:
20593   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20594   case X86ISD::FMIN:
20595   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20596   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20597   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20598   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20599   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20600   case ISD::ANY_EXTEND:
20601   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20602   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20603   case ISD::SIGN_EXTEND_INREG:
20604     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20605   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20606   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20607   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20608   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20609   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20610   case X86ISD::SHUFP:       // Handle all target specific shuffles
20611   case X86ISD::PALIGNR:
20612   case X86ISD::UNPCKH:
20613   case X86ISD::UNPCKL:
20614   case X86ISD::MOVHLPS:
20615   case X86ISD::MOVLHPS:
20616   case X86ISD::PSHUFD:
20617   case X86ISD::PSHUFHW:
20618   case X86ISD::PSHUFLW:
20619   case X86ISD::MOVSS:
20620   case X86ISD::MOVSD:
20621   case X86ISD::VPERMILP:
20622   case X86ISD::VPERM2X128:
20623   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20624   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20625   case ISD::INTRINSIC_WO_CHAIN:
20626     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20627   case X86ISD::INSERTPS:
20628     return PerformINSERTPSCombine(N, DAG, Subtarget);
20629   }
20630
20631   return SDValue();
20632 }
20633
20634 /// isTypeDesirableForOp - Return true if the target has native support for
20635 /// the specified value type and it is 'desirable' to use the type for the
20636 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20637 /// instruction encodings are longer and some i16 instructions are slow.
20638 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20639   if (!isTypeLegal(VT))
20640     return false;
20641   if (VT != MVT::i16)
20642     return true;
20643
20644   switch (Opc) {
20645   default:
20646     return true;
20647   case ISD::LOAD:
20648   case ISD::SIGN_EXTEND:
20649   case ISD::ZERO_EXTEND:
20650   case ISD::ANY_EXTEND:
20651   case ISD::SHL:
20652   case ISD::SRL:
20653   case ISD::SUB:
20654   case ISD::ADD:
20655   case ISD::MUL:
20656   case ISD::AND:
20657   case ISD::OR:
20658   case ISD::XOR:
20659     return false;
20660   }
20661 }
20662
20663 /// IsDesirableToPromoteOp - This method query the target whether it is
20664 /// beneficial for dag combiner to promote the specified node. If true, it
20665 /// should return the desired promotion type by reference.
20666 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20667   EVT VT = Op.getValueType();
20668   if (VT != MVT::i16)
20669     return false;
20670
20671   bool Promote = false;
20672   bool Commute = false;
20673   switch (Op.getOpcode()) {
20674   default: break;
20675   case ISD::LOAD: {
20676     LoadSDNode *LD = cast<LoadSDNode>(Op);
20677     // If the non-extending load has a single use and it's not live out, then it
20678     // might be folded.
20679     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20680                                                      Op.hasOneUse()*/) {
20681       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20682              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20683         // The only case where we'd want to promote LOAD (rather then it being
20684         // promoted as an operand is when it's only use is liveout.
20685         if (UI->getOpcode() != ISD::CopyToReg)
20686           return false;
20687       }
20688     }
20689     Promote = true;
20690     break;
20691   }
20692   case ISD::SIGN_EXTEND:
20693   case ISD::ZERO_EXTEND:
20694   case ISD::ANY_EXTEND:
20695     Promote = true;
20696     break;
20697   case ISD::SHL:
20698   case ISD::SRL: {
20699     SDValue N0 = Op.getOperand(0);
20700     // Look out for (store (shl (load), x)).
20701     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20702       return false;
20703     Promote = true;
20704     break;
20705   }
20706   case ISD::ADD:
20707   case ISD::MUL:
20708   case ISD::AND:
20709   case ISD::OR:
20710   case ISD::XOR:
20711     Commute = true;
20712     // fallthrough
20713   case ISD::SUB: {
20714     SDValue N0 = Op.getOperand(0);
20715     SDValue N1 = Op.getOperand(1);
20716     if (!Commute && MayFoldLoad(N1))
20717       return false;
20718     // Avoid disabling potential load folding opportunities.
20719     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20720       return false;
20721     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20722       return false;
20723     Promote = true;
20724   }
20725   }
20726
20727   PVT = MVT::i32;
20728   return Promote;
20729 }
20730
20731 //===----------------------------------------------------------------------===//
20732 //                           X86 Inline Assembly Support
20733 //===----------------------------------------------------------------------===//
20734
20735 namespace {
20736   // Helper to match a string separated by whitespace.
20737   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20738     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20739
20740     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20741       StringRef piece(*args[i]);
20742       if (!s.startswith(piece)) // Check if the piece matches.
20743         return false;
20744
20745       s = s.substr(piece.size());
20746       StringRef::size_type pos = s.find_first_not_of(" \t");
20747       if (pos == 0) // We matched a prefix.
20748         return false;
20749
20750       s = s.substr(pos);
20751     }
20752
20753     return s.empty();
20754   }
20755   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20756 }
20757
20758 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20759
20760   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20761     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20762         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20763         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20764
20765       if (AsmPieces.size() == 3)
20766         return true;
20767       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20768         return true;
20769     }
20770   }
20771   return false;
20772 }
20773
20774 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20775   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20776
20777   std::string AsmStr = IA->getAsmString();
20778
20779   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20780   if (!Ty || Ty->getBitWidth() % 16 != 0)
20781     return false;
20782
20783   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20784   SmallVector<StringRef, 4> AsmPieces;
20785   SplitString(AsmStr, AsmPieces, ";\n");
20786
20787   switch (AsmPieces.size()) {
20788   default: return false;
20789   case 1:
20790     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20791     // we will turn this bswap into something that will be lowered to logical
20792     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20793     // lower so don't worry about this.
20794     // bswap $0
20795     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20796         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20797         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20798         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20799         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20800         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20801       // No need to check constraints, nothing other than the equivalent of
20802       // "=r,0" would be valid here.
20803       return IntrinsicLowering::LowerToByteSwap(CI);
20804     }
20805
20806     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20807     if (CI->getType()->isIntegerTy(16) &&
20808         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20809         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20810          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20811       AsmPieces.clear();
20812       const std::string &ConstraintsStr = IA->getConstraintString();
20813       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20814       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20815       if (clobbersFlagRegisters(AsmPieces))
20816         return IntrinsicLowering::LowerToByteSwap(CI);
20817     }
20818     break;
20819   case 3:
20820     if (CI->getType()->isIntegerTy(32) &&
20821         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20822         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20823         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20824         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20825       AsmPieces.clear();
20826       const std::string &ConstraintsStr = IA->getConstraintString();
20827       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20828       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20829       if (clobbersFlagRegisters(AsmPieces))
20830         return IntrinsicLowering::LowerToByteSwap(CI);
20831     }
20832
20833     if (CI->getType()->isIntegerTy(64)) {
20834       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20835       if (Constraints.size() >= 2 &&
20836           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20837           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20838         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20839         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20840             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20841             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20842           return IntrinsicLowering::LowerToByteSwap(CI);
20843       }
20844     }
20845     break;
20846   }
20847   return false;
20848 }
20849
20850 /// getConstraintType - Given a constraint letter, return the type of
20851 /// constraint it is for this target.
20852 X86TargetLowering::ConstraintType
20853 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20854   if (Constraint.size() == 1) {
20855     switch (Constraint[0]) {
20856     case 'R':
20857     case 'q':
20858     case 'Q':
20859     case 'f':
20860     case 't':
20861     case 'u':
20862     case 'y':
20863     case 'x':
20864     case 'Y':
20865     case 'l':
20866       return C_RegisterClass;
20867     case 'a':
20868     case 'b':
20869     case 'c':
20870     case 'd':
20871     case 'S':
20872     case 'D':
20873     case 'A':
20874       return C_Register;
20875     case 'I':
20876     case 'J':
20877     case 'K':
20878     case 'L':
20879     case 'M':
20880     case 'N':
20881     case 'G':
20882     case 'C':
20883     case 'e':
20884     case 'Z':
20885       return C_Other;
20886     default:
20887       break;
20888     }
20889   }
20890   return TargetLowering::getConstraintType(Constraint);
20891 }
20892
20893 /// Examine constraint type and operand type and determine a weight value.
20894 /// This object must already have been set up with the operand type
20895 /// and the current alternative constraint selected.
20896 TargetLowering::ConstraintWeight
20897   X86TargetLowering::getSingleConstraintMatchWeight(
20898     AsmOperandInfo &info, const char *constraint) const {
20899   ConstraintWeight weight = CW_Invalid;
20900   Value *CallOperandVal = info.CallOperandVal;
20901     // If we don't have a value, we can't do a match,
20902     // but allow it at the lowest weight.
20903   if (!CallOperandVal)
20904     return CW_Default;
20905   Type *type = CallOperandVal->getType();
20906   // Look at the constraint type.
20907   switch (*constraint) {
20908   default:
20909     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20910   case 'R':
20911   case 'q':
20912   case 'Q':
20913   case 'a':
20914   case 'b':
20915   case 'c':
20916   case 'd':
20917   case 'S':
20918   case 'D':
20919   case 'A':
20920     if (CallOperandVal->getType()->isIntegerTy())
20921       weight = CW_SpecificReg;
20922     break;
20923   case 'f':
20924   case 't':
20925   case 'u':
20926     if (type->isFloatingPointTy())
20927       weight = CW_SpecificReg;
20928     break;
20929   case 'y':
20930     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20931       weight = CW_SpecificReg;
20932     break;
20933   case 'x':
20934   case 'Y':
20935     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20936         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20937       weight = CW_Register;
20938     break;
20939   case 'I':
20940     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20941       if (C->getZExtValue() <= 31)
20942         weight = CW_Constant;
20943     }
20944     break;
20945   case 'J':
20946     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20947       if (C->getZExtValue() <= 63)
20948         weight = CW_Constant;
20949     }
20950     break;
20951   case 'K':
20952     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20953       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20954         weight = CW_Constant;
20955     }
20956     break;
20957   case 'L':
20958     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20959       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20960         weight = CW_Constant;
20961     }
20962     break;
20963   case 'M':
20964     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20965       if (C->getZExtValue() <= 3)
20966         weight = CW_Constant;
20967     }
20968     break;
20969   case 'N':
20970     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20971       if (C->getZExtValue() <= 0xff)
20972         weight = CW_Constant;
20973     }
20974     break;
20975   case 'G':
20976   case 'C':
20977     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20978       weight = CW_Constant;
20979     }
20980     break;
20981   case 'e':
20982     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20983       if ((C->getSExtValue() >= -0x80000000LL) &&
20984           (C->getSExtValue() <= 0x7fffffffLL))
20985         weight = CW_Constant;
20986     }
20987     break;
20988   case 'Z':
20989     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20990       if (C->getZExtValue() <= 0xffffffff)
20991         weight = CW_Constant;
20992     }
20993     break;
20994   }
20995   return weight;
20996 }
20997
20998 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20999 /// with another that has more specific requirements based on the type of the
21000 /// corresponding operand.
21001 const char *X86TargetLowering::
21002 LowerXConstraint(EVT ConstraintVT) const {
21003   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21004   // 'f' like normal targets.
21005   if (ConstraintVT.isFloatingPoint()) {
21006     if (Subtarget->hasSSE2())
21007       return "Y";
21008     if (Subtarget->hasSSE1())
21009       return "x";
21010   }
21011
21012   return TargetLowering::LowerXConstraint(ConstraintVT);
21013 }
21014
21015 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21016 /// vector.  If it is invalid, don't add anything to Ops.
21017 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21018                                                      std::string &Constraint,
21019                                                      std::vector<SDValue>&Ops,
21020                                                      SelectionDAG &DAG) const {
21021   SDValue Result;
21022
21023   // Only support length 1 constraints for now.
21024   if (Constraint.length() > 1) return;
21025
21026   char ConstraintLetter = Constraint[0];
21027   switch (ConstraintLetter) {
21028   default: break;
21029   case 'I':
21030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21031       if (C->getZExtValue() <= 31) {
21032         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21033         break;
21034       }
21035     }
21036     return;
21037   case 'J':
21038     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21039       if (C->getZExtValue() <= 63) {
21040         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21041         break;
21042       }
21043     }
21044     return;
21045   case 'K':
21046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21047       if (isInt<8>(C->getSExtValue())) {
21048         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21049         break;
21050       }
21051     }
21052     return;
21053   case 'N':
21054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21055       if (C->getZExtValue() <= 255) {
21056         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21057         break;
21058       }
21059     }
21060     return;
21061   case 'e': {
21062     // 32-bit signed value
21063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21064       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21065                                            C->getSExtValue())) {
21066         // Widen to 64 bits here to get it sign extended.
21067         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21068         break;
21069       }
21070     // FIXME gcc accepts some relocatable values here too, but only in certain
21071     // memory models; it's complicated.
21072     }
21073     return;
21074   }
21075   case 'Z': {
21076     // 32-bit unsigned value
21077     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21078       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21079                                            C->getZExtValue())) {
21080         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21081         break;
21082       }
21083     }
21084     // FIXME gcc accepts some relocatable values here too, but only in certain
21085     // memory models; it's complicated.
21086     return;
21087   }
21088   case 'i': {
21089     // Literal immediates are always ok.
21090     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21091       // Widen to 64 bits here to get it sign extended.
21092       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21093       break;
21094     }
21095
21096     // In any sort of PIC mode addresses need to be computed at runtime by
21097     // adding in a register or some sort of table lookup.  These can't
21098     // be used as immediates.
21099     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21100       return;
21101
21102     // If we are in non-pic codegen mode, we allow the address of a global (with
21103     // an optional displacement) to be used with 'i'.
21104     GlobalAddressSDNode *GA = nullptr;
21105     int64_t Offset = 0;
21106
21107     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21108     while (1) {
21109       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21110         Offset += GA->getOffset();
21111         break;
21112       } else if (Op.getOpcode() == ISD::ADD) {
21113         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21114           Offset += C->getZExtValue();
21115           Op = Op.getOperand(0);
21116           continue;
21117         }
21118       } else if (Op.getOpcode() == ISD::SUB) {
21119         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21120           Offset += -C->getZExtValue();
21121           Op = Op.getOperand(0);
21122           continue;
21123         }
21124       }
21125
21126       // Otherwise, this isn't something we can handle, reject it.
21127       return;
21128     }
21129
21130     const GlobalValue *GV = GA->getGlobal();
21131     // If we require an extra load to get this address, as in PIC mode, we
21132     // can't accept it.
21133     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21134                                                         getTargetMachine())))
21135       return;
21136
21137     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21138                                         GA->getValueType(0), Offset);
21139     break;
21140   }
21141   }
21142
21143   if (Result.getNode()) {
21144     Ops.push_back(Result);
21145     return;
21146   }
21147   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21148 }
21149
21150 std::pair<unsigned, const TargetRegisterClass*>
21151 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21152                                                 MVT VT) const {
21153   // First, see if this is a constraint that directly corresponds to an LLVM
21154   // register class.
21155   if (Constraint.size() == 1) {
21156     // GCC Constraint Letters
21157     switch (Constraint[0]) {
21158     default: break;
21159       // TODO: Slight differences here in allocation order and leaving
21160       // RIP in the class. Do they matter any more here than they do
21161       // in the normal allocation?
21162     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21163       if (Subtarget->is64Bit()) {
21164         if (VT == MVT::i32 || VT == MVT::f32)
21165           return std::make_pair(0U, &X86::GR32RegClass);
21166         if (VT == MVT::i16)
21167           return std::make_pair(0U, &X86::GR16RegClass);
21168         if (VT == MVT::i8 || VT == MVT::i1)
21169           return std::make_pair(0U, &X86::GR8RegClass);
21170         if (VT == MVT::i64 || VT == MVT::f64)
21171           return std::make_pair(0U, &X86::GR64RegClass);
21172         break;
21173       }
21174       // 32-bit fallthrough
21175     case 'Q':   // Q_REGS
21176       if (VT == MVT::i32 || VT == MVT::f32)
21177         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21178       if (VT == MVT::i16)
21179         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21180       if (VT == MVT::i8 || VT == MVT::i1)
21181         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21182       if (VT == MVT::i64)
21183         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21184       break;
21185     case 'r':   // GENERAL_REGS
21186     case 'l':   // INDEX_REGS
21187       if (VT == MVT::i8 || VT == MVT::i1)
21188         return std::make_pair(0U, &X86::GR8RegClass);
21189       if (VT == MVT::i16)
21190         return std::make_pair(0U, &X86::GR16RegClass);
21191       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21192         return std::make_pair(0U, &X86::GR32RegClass);
21193       return std::make_pair(0U, &X86::GR64RegClass);
21194     case 'R':   // LEGACY_REGS
21195       if (VT == MVT::i8 || VT == MVT::i1)
21196         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21197       if (VT == MVT::i16)
21198         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21199       if (VT == MVT::i32 || !Subtarget->is64Bit())
21200         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21201       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21202     case 'f':  // FP Stack registers.
21203       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21204       // value to the correct fpstack register class.
21205       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21206         return std::make_pair(0U, &X86::RFP32RegClass);
21207       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21208         return std::make_pair(0U, &X86::RFP64RegClass);
21209       return std::make_pair(0U, &X86::RFP80RegClass);
21210     case 'y':   // MMX_REGS if MMX allowed.
21211       if (!Subtarget->hasMMX()) break;
21212       return std::make_pair(0U, &X86::VR64RegClass);
21213     case 'Y':   // SSE_REGS if SSE2 allowed
21214       if (!Subtarget->hasSSE2()) break;
21215       // FALL THROUGH.
21216     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21217       if (!Subtarget->hasSSE1()) break;
21218
21219       switch (VT.SimpleTy) {
21220       default: break;
21221       // Scalar SSE types.
21222       case MVT::f32:
21223       case MVT::i32:
21224         return std::make_pair(0U, &X86::FR32RegClass);
21225       case MVT::f64:
21226       case MVT::i64:
21227         return std::make_pair(0U, &X86::FR64RegClass);
21228       // Vector types.
21229       case MVT::v16i8:
21230       case MVT::v8i16:
21231       case MVT::v4i32:
21232       case MVT::v2i64:
21233       case MVT::v4f32:
21234       case MVT::v2f64:
21235         return std::make_pair(0U, &X86::VR128RegClass);
21236       // AVX types.
21237       case MVT::v32i8:
21238       case MVT::v16i16:
21239       case MVT::v8i32:
21240       case MVT::v4i64:
21241       case MVT::v8f32:
21242       case MVT::v4f64:
21243         return std::make_pair(0U, &X86::VR256RegClass);
21244       case MVT::v8f64:
21245       case MVT::v16f32:
21246       case MVT::v16i32:
21247       case MVT::v8i64:
21248         return std::make_pair(0U, &X86::VR512RegClass);
21249       }
21250       break;
21251     }
21252   }
21253
21254   // Use the default implementation in TargetLowering to convert the register
21255   // constraint into a member of a register class.
21256   std::pair<unsigned, const TargetRegisterClass*> Res;
21257   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21258
21259   // Not found as a standard register?
21260   if (!Res.second) {
21261     // Map st(0) -> st(7) -> ST0
21262     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21263         tolower(Constraint[1]) == 's' &&
21264         tolower(Constraint[2]) == 't' &&
21265         Constraint[3] == '(' &&
21266         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21267         Constraint[5] == ')' &&
21268         Constraint[6] == '}') {
21269
21270       Res.first = X86::ST0+Constraint[4]-'0';
21271       Res.second = &X86::RFP80RegClass;
21272       return Res;
21273     }
21274
21275     // GCC allows "st(0)" to be called just plain "st".
21276     if (StringRef("{st}").equals_lower(Constraint)) {
21277       Res.first = X86::ST0;
21278       Res.second = &X86::RFP80RegClass;
21279       return Res;
21280     }
21281
21282     // flags -> EFLAGS
21283     if (StringRef("{flags}").equals_lower(Constraint)) {
21284       Res.first = X86::EFLAGS;
21285       Res.second = &X86::CCRRegClass;
21286       return Res;
21287     }
21288
21289     // 'A' means EAX + EDX.
21290     if (Constraint == "A") {
21291       Res.first = X86::EAX;
21292       Res.second = &X86::GR32_ADRegClass;
21293       return Res;
21294     }
21295     return Res;
21296   }
21297
21298   // Otherwise, check to see if this is a register class of the wrong value
21299   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21300   // turn into {ax},{dx}.
21301   if (Res.second->hasType(VT))
21302     return Res;   // Correct type already, nothing to do.
21303
21304   // All of the single-register GCC register classes map their values onto
21305   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21306   // really want an 8-bit or 32-bit register, map to the appropriate register
21307   // class and return the appropriate register.
21308   if (Res.second == &X86::GR16RegClass) {
21309     if (VT == MVT::i8 || VT == MVT::i1) {
21310       unsigned DestReg = 0;
21311       switch (Res.first) {
21312       default: break;
21313       case X86::AX: DestReg = X86::AL; break;
21314       case X86::DX: DestReg = X86::DL; break;
21315       case X86::CX: DestReg = X86::CL; break;
21316       case X86::BX: DestReg = X86::BL; break;
21317       }
21318       if (DestReg) {
21319         Res.first = DestReg;
21320         Res.second = &X86::GR8RegClass;
21321       }
21322     } else if (VT == MVT::i32 || VT == MVT::f32) {
21323       unsigned DestReg = 0;
21324       switch (Res.first) {
21325       default: break;
21326       case X86::AX: DestReg = X86::EAX; break;
21327       case X86::DX: DestReg = X86::EDX; break;
21328       case X86::CX: DestReg = X86::ECX; break;
21329       case X86::BX: DestReg = X86::EBX; break;
21330       case X86::SI: DestReg = X86::ESI; break;
21331       case X86::DI: DestReg = X86::EDI; break;
21332       case X86::BP: DestReg = X86::EBP; break;
21333       case X86::SP: DestReg = X86::ESP; break;
21334       }
21335       if (DestReg) {
21336         Res.first = DestReg;
21337         Res.second = &X86::GR32RegClass;
21338       }
21339     } else if (VT == MVT::i64 || VT == MVT::f64) {
21340       unsigned DestReg = 0;
21341       switch (Res.first) {
21342       default: break;
21343       case X86::AX: DestReg = X86::RAX; break;
21344       case X86::DX: DestReg = X86::RDX; break;
21345       case X86::CX: DestReg = X86::RCX; break;
21346       case X86::BX: DestReg = X86::RBX; break;
21347       case X86::SI: DestReg = X86::RSI; break;
21348       case X86::DI: DestReg = X86::RDI; break;
21349       case X86::BP: DestReg = X86::RBP; break;
21350       case X86::SP: DestReg = X86::RSP; break;
21351       }
21352       if (DestReg) {
21353         Res.first = DestReg;
21354         Res.second = &X86::GR64RegClass;
21355       }
21356     }
21357   } else if (Res.second == &X86::FR32RegClass ||
21358              Res.second == &X86::FR64RegClass ||
21359              Res.second == &X86::VR128RegClass ||
21360              Res.second == &X86::VR256RegClass ||
21361              Res.second == &X86::FR32XRegClass ||
21362              Res.second == &X86::FR64XRegClass ||
21363              Res.second == &X86::VR128XRegClass ||
21364              Res.second == &X86::VR256XRegClass ||
21365              Res.second == &X86::VR512RegClass) {
21366     // Handle references to XMM physical registers that got mapped into the
21367     // wrong class.  This can happen with constraints like {xmm0} where the
21368     // target independent register mapper will just pick the first match it can
21369     // find, ignoring the required type.
21370
21371     if (VT == MVT::f32 || VT == MVT::i32)
21372       Res.second = &X86::FR32RegClass;
21373     else if (VT == MVT::f64 || VT == MVT::i64)
21374       Res.second = &X86::FR64RegClass;
21375     else if (X86::VR128RegClass.hasType(VT))
21376       Res.second = &X86::VR128RegClass;
21377     else if (X86::VR256RegClass.hasType(VT))
21378       Res.second = &X86::VR256RegClass;
21379     else if (X86::VR512RegClass.hasType(VT))
21380       Res.second = &X86::VR512RegClass;
21381   }
21382
21383   return Res;
21384 }
21385
21386 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21387                                             Type *Ty) const {
21388   // Scaling factors are not free at all.
21389   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21390   // will take 2 allocations in the out of order engine instead of 1
21391   // for plain addressing mode, i.e. inst (reg1).
21392   // E.g.,
21393   // vaddps (%rsi,%drx), %ymm0, %ymm1
21394   // Requires two allocations (one for the load, one for the computation)
21395   // whereas:
21396   // vaddps (%rsi), %ymm0, %ymm1
21397   // Requires just 1 allocation, i.e., freeing allocations for other operations
21398   // and having less micro operations to execute.
21399   //
21400   // For some X86 architectures, this is even worse because for instance for
21401   // stores, the complex addressing mode forces the instruction to use the
21402   // "load" ports instead of the dedicated "store" port.
21403   // E.g., on Haswell:
21404   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21405   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21406   if (isLegalAddressingMode(AM, Ty))
21407     // Scale represents reg2 * scale, thus account for 1
21408     // as soon as we use a second register.
21409     return AM.Scale != 0;
21410   return -1;
21411 }