AVX512: Implemented encoding and intrinsics for vpalignr
[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 "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
168     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
169   } else if (!Subtarget->useSoftFloat()) {
170     // We have an algorithm for SSE2->double, and we turn this into a
171     // 64-bit FILD followed by conditional FADD for other targets.
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173     // We have an algorithm for SSE2, and we turn this into a 64-bit
174     // FILD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
176   }
177
178   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
179   // this operation.
180   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
181   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
182
183   if (!Subtarget->useSoftFloat()) {
184     // SSE has no i16 to fp conversion, only i32
185     if (X86ScalarSSEf32) {
186       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187       // f32 and f64 cases are Legal, f80 case is not
188       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
189     } else {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     }
193   } else {
194     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
195     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
196   }
197
198   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
199   // are Legal, f80 is custom lowered.
200   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
201   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (X86ScalarSSEf32) {
209     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
210     // f32 and f64 cases are Legal, f80 case is not
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
212   } else {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   }
216
217   // Handle FP_TO_UINT by promoting the destination to a larger signed
218   // conversion.
219   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
220   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
221   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
222
223   if (Subtarget->is64Bit()) {
224     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
228     } else {
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
231     }
232   } else if (!Subtarget->useSoftFloat()) {
233     // Since AVX is a superset of SSE3, only check for SSE here.
234     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235       // Expand FP_TO_UINT into a select.
236       // FIXME: We would like to use a Custom expander here eventually to do
237       // the optimal thing for SSE vs. the default expansion in the legalizer.
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
239     else
240       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244
245     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
246   }
247
248   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249   if (!X86ScalarSSEf64) {
250     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
251     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
252     if (Subtarget->is64Bit()) {
253       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
254       // Without SSE, i64->f64 goes through memory.
255       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
256     }
257   }
258
259   // Scalar integer divide and remainder are lowered to use operations that
260   // produce two results, to match the available instructions. This exposes
261   // the two-result form to trivial CSE, which is able to combine x/y and x%y
262   // into a single instruction.
263   //
264   // Scalar integer multiply-high is also lowered to use two-result
265   // operations, to match the available instructions. However, plain multiply
266   // (low) operations are left as Legal, as there are single-result
267   // instructions for this in x86. Using the two-result multiply instructions
268   // when both high and low results are needed must be arranged by dagcombine.
269   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
270     MVT VT = IntVTs[i];
271     setOperationAction(ISD::MULHS, VT, Expand);
272     setOperationAction(ISD::MULHU, VT, Expand);
273     setOperationAction(ISD::SDIV, VT, Expand);
274     setOperationAction(ISD::UDIV, VT, Expand);
275     setOperationAction(ISD::SREM, VT, Expand);
276     setOperationAction(ISD::UREM, VT, Expand);
277
278     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279     setOperationAction(ISD::ADDC, VT, Custom);
280     setOperationAction(ISD::ADDE, VT, Custom);
281     setOperationAction(ISD::SUBC, VT, Custom);
282     setOperationAction(ISD::SUBE, VT, Custom);
283   }
284
285   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
286   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
287   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
288   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
289   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
291   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
294   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
295   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
301   if (Subtarget->is64Bit())
302     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
304   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
306   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
307   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
308   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
309   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
310   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
311
312   // Promote the i8 variants and force them on up to i32 which has a shorter
313   // encoding.
314   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
315   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
316   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
317   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
318   if (Subtarget->hasBMI()) {
319     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
320     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
321     if (Subtarget->is64Bit())
322       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
323   } else {
324     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
325     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
326     if (Subtarget->is64Bit())
327       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
328   }
329
330   if (Subtarget->hasLZCNT()) {
331     // When promoting the i8 variants, force them to i32 for a shorter
332     // encoding.
333     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
334     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
335     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
336     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
337     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
338     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
339     if (Subtarget->is64Bit())
340       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
341   } else {
342     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
343     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
344     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
348     if (Subtarget->is64Bit()) {
349       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
351     }
352   }
353
354   // Special handling for half-precision floating point conversions.
355   // If we don't have F16C support, then lower half float conversions
356   // into library calls.
357   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
358     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
359     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
360   }
361
362   // There's never any support for operations beyond MVT::f32.
363   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
364   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
365   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
366   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
367
368   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
369   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
370   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
371   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
372   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
374
375   if (Subtarget->hasPOPCNT()) {
376     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
377   } else {
378     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
379     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
380     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
381     if (Subtarget->is64Bit())
382       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
383   }
384
385   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
386
387   if (!Subtarget->hasMOVBE())
388     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
389
390   // These should be promoted to a larger select which is supported.
391   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
392   // X86 wants to expand cmov itself.
393   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
394   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
395   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
396   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
397   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
398   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
399   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
400   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
401   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
402   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
403   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
404   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
405   if (Subtarget->is64Bit()) {
406     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
407     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
408   }
409   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
410   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
411   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
412   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
413   // support continuation, user-level threading, and etc.. As a result, no
414   // other SjLj exception interfaces are implemented and please don't build
415   // your own exception handling based on them.
416   // LLVM/Clang supports zero-cost DWARF exception handling.
417   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
418   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
419
420   // Darwin ABI issue.
421   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
422   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
423   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
424   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
425   if (Subtarget->is64Bit())
426     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
427   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
428   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
429   if (Subtarget->is64Bit()) {
430     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
431     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
432     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
433     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
434     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
435   }
436   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
437   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
438   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
439   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
442     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
443     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
444   }
445
446   if (Subtarget->hasSSE1())
447     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
448
449   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
450
451   // Expand certain atomics
452   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
453     MVT VT = IntVTs[i];
454     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
455     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
456     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
457   }
458
459   if (Subtarget->hasCmpxchg16b()) {
460     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
461   }
462
463   // FIXME - use subtarget debug flags
464   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
465       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
466     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
467   }
468
469   if (Subtarget->isTarget64BitLP64()) {
470     setExceptionPointerRegister(X86::RAX);
471     setExceptionSelectorRegister(X86::RDX);
472   } else {
473     setExceptionPointerRegister(X86::EAX);
474     setExceptionSelectorRegister(X86::EDX);
475   }
476   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
477   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
478
479   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
480   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
481
482   setOperationAction(ISD::TRAP, MVT::Other, Legal);
483   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
484
485   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
486   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
487   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
490     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
491   } else {
492     // TargetInfo::CharPtrBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
495   }
496
497   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
498   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
499
500   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
501
502   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
503   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
504   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
505
506   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
507     // f32 and f64 use SSE.
508     // Set up the FP register classes.
509     addRegisterClass(MVT::f32, &X86::FR32RegClass);
510     addRegisterClass(MVT::f64, &X86::FR64RegClass);
511
512     // Use ANDPD to simulate FABS.
513     setOperationAction(ISD::FABS , MVT::f64, Custom);
514     setOperationAction(ISD::FABS , MVT::f32, Custom);
515
516     // Use XORP to simulate FNEG.
517     setOperationAction(ISD::FNEG , MVT::f64, Custom);
518     setOperationAction(ISD::FNEG , MVT::f32, Custom);
519
520     // Use ANDPD and ORPD to simulate FCOPYSIGN.
521     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
522     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
523
524     // Lower this to FGETSIGNx86 plus an AND.
525     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
526     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
527
528     // We don't support sin/cos/fmod
529     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
530     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
531     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
532     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
533     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
534     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
535
536     // Expand FP immediates into loads from the stack, except for the special
537     // cases we handle.
538     addLegalFPImmediate(APFloat(+0.0)); // xorpd
539     addLegalFPImmediate(APFloat(+0.0f)); // xorps
540   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
541     // Use SSE for f32, x87 for f64.
542     // Set up the FP register classes.
543     addRegisterClass(MVT::f32, &X86::FR32RegClass);
544     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
545
546     // Use ANDPS to simulate FABS.
547     setOperationAction(ISD::FABS , MVT::f32, Custom);
548
549     // Use XORP to simulate FNEG.
550     setOperationAction(ISD::FNEG , MVT::f32, Custom);
551
552     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
553
554     // Use ANDPS and ORPS to simulate FCOPYSIGN.
555     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
556     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
557
558     // We don't support sin/cos/fmod
559     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
560     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
561     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
562
563     // Special cases we handle for FP constants.
564     addLegalFPImmediate(APFloat(+0.0f)); // xorps
565     addLegalFPImmediate(APFloat(+0.0)); // FLD0
566     addLegalFPImmediate(APFloat(+1.0)); // FLD1
567     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
568     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
569
570     if (!TM.Options.UnsafeFPMath) {
571       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
572       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
573       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
574     }
575   } else if (!Subtarget->useSoftFloat()) {
576     // f32 and f64 in x87.
577     // Set up the FP register classes.
578     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
579     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
580
581     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
582     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
583     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
584     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
585
586     if (!TM.Options.UnsafeFPMath) {
587       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
588       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
589       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
590       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
591       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
592       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
593     }
594     addLegalFPImmediate(APFloat(+0.0)); // FLD0
595     addLegalFPImmediate(APFloat(+1.0)); // FLD1
596     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
598     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
602   }
603
604   // We don't support FMA.
605   setOperationAction(ISD::FMA, MVT::f64, Expand);
606   setOperationAction(ISD::FMA, MVT::f32, Expand);
607
608   // Long double always uses X87.
609   if (!Subtarget->useSoftFloat()) {
610     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
611     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
612     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
613     {
614       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
615       addLegalFPImmediate(TmpFlt);  // FLD0
616       TmpFlt.changeSign();
617       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
618
619       bool ignored;
620       APFloat TmpFlt2(+1.0);
621       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
622                       &ignored);
623       addLegalFPImmediate(TmpFlt2);  // FLD1
624       TmpFlt2.changeSign();
625       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
626     }
627
628     if (!TM.Options.UnsafeFPMath) {
629       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
630       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
631       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
632     }
633
634     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
635     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
636     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
637     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
638     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
639     setOperationAction(ISD::FMA, MVT::f80, Expand);
640   }
641
642   // Always use a library call for pow.
643   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
644   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
645   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
646
647   setOperationAction(ISD::FLOG, MVT::f80, Expand);
648   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
649   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
650   setOperationAction(ISD::FEXP, MVT::f80, Expand);
651   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
652   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
653   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
654
655   // First set operation action for all vector types to either promote
656   // (for widening) or expand (for scalarization). Then we will selectively
657   // turn on ones that can be effectively codegen'd.
658   for (MVT VT : MVT::vector_valuetypes()) {
659     setOperationAction(ISD::ADD , VT, Expand);
660     setOperationAction(ISD::SUB , VT, Expand);
661     setOperationAction(ISD::FADD, VT, Expand);
662     setOperationAction(ISD::FNEG, VT, Expand);
663     setOperationAction(ISD::FSUB, VT, Expand);
664     setOperationAction(ISD::MUL , VT, Expand);
665     setOperationAction(ISD::FMUL, VT, Expand);
666     setOperationAction(ISD::SDIV, VT, Expand);
667     setOperationAction(ISD::UDIV, VT, Expand);
668     setOperationAction(ISD::FDIV, VT, Expand);
669     setOperationAction(ISD::SREM, VT, Expand);
670     setOperationAction(ISD::UREM, VT, Expand);
671     setOperationAction(ISD::LOAD, VT, Expand);
672     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
673     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
674     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
675     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
676     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
677     setOperationAction(ISD::FABS, VT, Expand);
678     setOperationAction(ISD::FSIN, VT, Expand);
679     setOperationAction(ISD::FSINCOS, VT, Expand);
680     setOperationAction(ISD::FCOS, VT, Expand);
681     setOperationAction(ISD::FSINCOS, VT, Expand);
682     setOperationAction(ISD::FREM, VT, Expand);
683     setOperationAction(ISD::FMA,  VT, Expand);
684     setOperationAction(ISD::FPOWI, VT, Expand);
685     setOperationAction(ISD::FSQRT, VT, Expand);
686     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
687     setOperationAction(ISD::FFLOOR, VT, Expand);
688     setOperationAction(ISD::FCEIL, VT, Expand);
689     setOperationAction(ISD::FTRUNC, VT, Expand);
690     setOperationAction(ISD::FRINT, VT, Expand);
691     setOperationAction(ISD::FNEARBYINT, VT, Expand);
692     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
693     setOperationAction(ISD::MULHS, VT, Expand);
694     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
695     setOperationAction(ISD::MULHU, VT, Expand);
696     setOperationAction(ISD::SDIVREM, VT, Expand);
697     setOperationAction(ISD::UDIVREM, VT, Expand);
698     setOperationAction(ISD::FPOW, VT, Expand);
699     setOperationAction(ISD::CTPOP, VT, Expand);
700     setOperationAction(ISD::CTTZ, VT, Expand);
701     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
702     setOperationAction(ISD::CTLZ, VT, Expand);
703     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
704     setOperationAction(ISD::SHL, VT, Expand);
705     setOperationAction(ISD::SRA, VT, Expand);
706     setOperationAction(ISD::SRL, VT, Expand);
707     setOperationAction(ISD::ROTL, VT, Expand);
708     setOperationAction(ISD::ROTR, VT, Expand);
709     setOperationAction(ISD::BSWAP, VT, Expand);
710     setOperationAction(ISD::SETCC, VT, Expand);
711     setOperationAction(ISD::FLOG, VT, Expand);
712     setOperationAction(ISD::FLOG2, VT, Expand);
713     setOperationAction(ISD::FLOG10, VT, Expand);
714     setOperationAction(ISD::FEXP, VT, Expand);
715     setOperationAction(ISD::FEXP2, VT, Expand);
716     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
717     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
718     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
719     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
720     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
721     setOperationAction(ISD::TRUNCATE, VT, Expand);
722     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
723     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
724     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
725     setOperationAction(ISD::VSELECT, VT, Expand);
726     setOperationAction(ISD::SELECT_CC, VT, Expand);
727     for (MVT InnerVT : MVT::vector_valuetypes()) {
728       setTruncStoreAction(InnerVT, VT, Expand);
729
730       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
731       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
732
733       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
734       // types, we have to deal with them whether we ask for Expansion or not.
735       // Setting Expand causes its own optimisation problems though, so leave
736       // them legal.
737       if (VT.getVectorElementType() == MVT::i1)
738         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
739
740       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
741       // split/scalarized right now.
742       if (VT.getVectorElementType() == MVT::f16)
743         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
744     }
745   }
746
747   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
748   // with -msoft-float, disable use of MMX as well.
749   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
750     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
751     // No operations on x86mmx supported, everything uses intrinsics.
752   }
753
754   // MMX-sized vectors (other than x86mmx) are expected to be expanded
755   // into smaller operations.
756   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
757     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
758     setOperationAction(ISD::AND,                MMXTy,      Expand);
759     setOperationAction(ISD::OR,                 MMXTy,      Expand);
760     setOperationAction(ISD::XOR,                MMXTy,      Expand);
761     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
762     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
763     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
764   }
765   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
766
767   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
768     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
769
770     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
771     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
772     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
773     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
774     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
775     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
776     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
777     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
780     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
782     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
783     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
784   }
785
786   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
787     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
788
789     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
790     // registers cannot be used even for integer operations.
791     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
792     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
793     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
794     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
795
796     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
797     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
798     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
799     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
800     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
801     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
802     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
803     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
804     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
805     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
806     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
807     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
808     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
809     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
810     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
812     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
813     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
814     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
815     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
816     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
817     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
818     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
819
820     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
821     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
822     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
823     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
824
825     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
828     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
829
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
831     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
835
836     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
837     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
838     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
839     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
840
841     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
843       MVT VT = (MVT::SimpleValueType)i;
844       // Do not attempt to custom lower non-power-of-2 vectors
845       if (!isPowerOf2_32(VT.getVectorNumElements()))
846         continue;
847       // Do not attempt to custom lower non-128-bit vectors
848       if (!VT.is128BitVector())
849         continue;
850       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
851       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
852       setOperationAction(ISD::VSELECT,            VT, Custom);
853       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
854     }
855
856     // We support custom legalizing of sext and anyext loads for specific
857     // memory vector types which we can load as a scalar (or sequence of
858     // scalars) and extend in-register to a legal 128-bit vector type. For sext
859     // loads these must work with a single scalar load.
860     for (MVT VT : MVT::integer_vector_valuetypes()) {
861       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
862       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
863       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
864       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
865       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
866       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
870     }
871
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
876     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
877     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
878     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
879     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
880
881     if (Subtarget->is64Bit()) {
882       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
884     }
885
886     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
887     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
888       MVT VT = (MVT::SimpleValueType)i;
889
890       // Do not attempt to promote non-128-bit vectors
891       if (!VT.is128BitVector())
892         continue;
893
894       setOperationAction(ISD::AND,    VT, Promote);
895       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
896       setOperationAction(ISD::OR,     VT, Promote);
897       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
898       setOperationAction(ISD::XOR,    VT, Promote);
899       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
900       setOperationAction(ISD::LOAD,   VT, Promote);
901       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
902       setOperationAction(ISD::SELECT, VT, Promote);
903       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
904     }
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914
915     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
916
917     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
919     // As there is no 64-bit GPR available, we need build a special custom
920     // sequence to convert from v2i32 to v2f32.
921     if (!Subtarget->is64Bit())
922       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
923
924     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
925     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
926
927     for (MVT VT : MVT::fp_vector_valuetypes())
928       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
929
930     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
931     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
933   }
934
935   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
936     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
937       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
938       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
939       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
940       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
941       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
942     }
943
944     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
945     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
946     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
947     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
948     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
952
953     // FIXME: Do we need to handle scalar-to-vector here?
954     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
955
956     // We directly match byte blends in the backend as they match the VSELECT
957     // condition form.
958     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
959
960     // SSE41 brings specific instructions for doing vector sign extend even in
961     // cases where we don't have SRA.
962     for (MVT VT : MVT::integer_vector_valuetypes()) {
963       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
966     }
967
968     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
975
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
982
983     // i8 and i16 vectors are custom because the source register and source
984     // source memory operand types are not the same width.  f32 vectors are
985     // custom since the immediate controlling the insert encodes additional
986     // information.
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
991
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
996
997     // FIXME: these should be Legal, but that's only for the case where
998     // the index is constant.  For now custom expand to deal with that.
999     if (Subtarget->is64Bit()) {
1000       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002     }
1003   }
1004
1005   if (Subtarget->hasSSE2()) {
1006     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1007     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1009
1010     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1015
1016     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1018
1019     // In the customized shift lowering, the legal cases in AVX2 will be
1020     // recognized.
1021     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1025     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1026
1027     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070     // even though v8i16 is a legal type.
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074
1075     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1077     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1080     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1081
1082     for (MVT VT : MVT::fp_vector_valuetypes())
1083       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084
1085     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1089     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1090
1091     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1092     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1093
1094     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1096     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1097     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1098
1099     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1100     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1101     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1102
1103     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1104     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1105     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1106     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1107     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1108     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1109     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1110     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1112     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1113     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1114     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1115
1116     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1117     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1118     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1119     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1120
1121     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1122       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1123       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1124       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1125       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1126       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1128     }
1129
1130     if (Subtarget->hasInt256()) {
1131       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1132       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1133       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1134       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1135
1136       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1137       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1138       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1139       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1140
1141       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1142       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1143       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1144       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1145
1146       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1147       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1148       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1149       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1150
1151       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1152       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1153       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1154       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1155       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1156       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1157       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1158       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1159       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1160       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1161       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1162       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1163
1164       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1165       // when we have a 256bit-wide blend with immediate.
1166       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1167
1168       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1169       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1170       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1171       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1172       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1175
1176       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1177       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1178       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1179       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1182     } else {
1183       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1184       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1185       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1186       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1187
1188       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1189       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1190       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1191       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1192
1193       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1199       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1200       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1201       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1202       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1203       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1204       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1205       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1206       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1207       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1208       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1209       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1210     }
1211
1212     // In the customized shift lowering, the legal cases in AVX2 will be
1213     // recognized.
1214     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1215     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1216
1217     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1218     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1219
1220     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1221     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1222
1223     // Custom lower several nodes for 256-bit types.
1224     for (MVT VT : MVT::vector_valuetypes()) {
1225       if (VT.getScalarSizeInBits() >= 32) {
1226         setOperationAction(ISD::MLOAD,  VT, Legal);
1227         setOperationAction(ISD::MSTORE, VT, Legal);
1228       }
1229       // Extract subvector is special because the value type
1230       // (result) is 128-bit but the source is 256-bit wide.
1231       if (VT.is128BitVector()) {
1232         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1233       }
1234       // Do not attempt to custom lower other non-256-bit vectors
1235       if (!VT.is256BitVector())
1236         continue;
1237
1238       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1239       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1240       setOperationAction(ISD::VSELECT,            VT, Custom);
1241       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1242       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1243       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1244       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1245       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1246     }
1247
1248     if (Subtarget->hasInt256())
1249       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1250
1251
1252     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254       MVT VT = (MVT::SimpleValueType)i;
1255
1256       // Do not attempt to promote non-256-bit vectors
1257       if (!VT.is256BitVector())
1258         continue;
1259
1260       setOperationAction(ISD::AND,    VT, Promote);
1261       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1262       setOperationAction(ISD::OR,     VT, Promote);
1263       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1264       setOperationAction(ISD::XOR,    VT, Promote);
1265       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1266       setOperationAction(ISD::LOAD,   VT, Promote);
1267       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1268       setOperationAction(ISD::SELECT, VT, Promote);
1269       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1270     }
1271   }
1272
1273   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1274     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1275     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1276     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1277     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1278
1279     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1280     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1281     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1282
1283     for (MVT VT : MVT::fp_vector_valuetypes())
1284       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1285
1286     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1287     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1288     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1289     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1290     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1291     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1292     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1293     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1294     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1295     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1298
1299     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1300     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1301     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1302     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1303     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1304     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1305     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1306     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1307     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1309     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1312
1313     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1314     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1315     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1316     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1318     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1319
1320     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1323     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1325     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1326     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1327     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1328
1329     // FIXME:  [US]INT_TO_FP are not legal for f80.
1330     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1331     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1332     if (Subtarget->is64Bit()) {
1333       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1334       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1335     }
1336     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1339     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1343     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1348     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1349     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1350     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1351     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1352
1353     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1354     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1355     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1356     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1357     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1358     if (Subtarget->hasVLX()){
1359       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1360       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1361       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1362       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1363       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1364
1365       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1366       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1367       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1368       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1369       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1370     }
1371     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1373     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1374     if (Subtarget->hasDQI()) {
1375       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1376       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1377
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1380       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1381       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1382       if (Subtarget->hasVLX()) {
1383         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1385         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1386         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1387         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1388         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1389         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1390         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1391       }
1392     }
1393     if (Subtarget->hasVLX()) {
1394       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1395       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1396       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1397       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1398       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1399       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1400       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1401       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1402     }
1403     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1406     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1407     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1408     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1409     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1410     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1413     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1414     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1415     if (Subtarget->hasDQI()) {
1416       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1417       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1418     }
1419     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1420     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1421     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1422     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1423     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1424     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1425     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1426     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1427     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1428     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1429
1430     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1431     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1433     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1434     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1435
1436     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1437     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1438
1439     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1440
1441     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1442     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1443     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1444     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1445     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1446     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1447     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1448     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1449     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1450     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1451     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1452
1453     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1455     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1456     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1457     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1458     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1459     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1460     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1461
1462     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1469
1470     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1477     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1478
1479     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1482     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1483     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1484     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1485
1486     if (Subtarget->hasCDI()) {
1487       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1488       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1489     }
1490     if (Subtarget->hasDQI()) {
1491       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1492       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1493       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1494     }
1495     // Custom lower several nodes.
1496     for (MVT VT : MVT::vector_valuetypes()) {
1497       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1498       if (EltSize == 1) {
1499         setOperationAction(ISD::AND, VT, Legal);
1500         setOperationAction(ISD::OR,  VT, Legal);
1501         setOperationAction(ISD::XOR,  VT, Legal);
1502       }
1503       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1504         setOperationAction(ISD::MGATHER,  VT, Custom);
1505         setOperationAction(ISD::MSCATTER, VT, Custom);
1506       }
1507       // Extract subvector is special because the value type
1508       // (result) is 256/128-bit but the source is 512-bit wide.
1509       if (VT.is128BitVector() || VT.is256BitVector()) {
1510         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511       }
1512       if (VT.getVectorElementType() == MVT::i1)
1513         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1514
1515       // Do not attempt to custom lower other non-512-bit vectors
1516       if (!VT.is512BitVector())
1517         continue;
1518
1519       if (EltSize >= 32) {
1520         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1521         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1522         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1523         setOperationAction(ISD::VSELECT,             VT, Legal);
1524         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1525         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1526         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1527         setOperationAction(ISD::MLOAD,               VT, Legal);
1528         setOperationAction(ISD::MSTORE,              VT, Legal);
1529       }
1530     }
1531     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1532       MVT VT = (MVT::SimpleValueType)i;
1533
1534       // Do not attempt to promote non-512-bit vectors.
1535       if (!VT.is512BitVector())
1536         continue;
1537
1538       setOperationAction(ISD::SELECT, VT, Promote);
1539       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1540     }
1541   }// has  AVX-512
1542
1543   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1544     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1545     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1546
1547     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1548     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1549
1550     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1551     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1552     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1553     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1554     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1555     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1556     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1557     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1558     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1559     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1560     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1561     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1562     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1563     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1564     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1565     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1566     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1567     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1568     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1569     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1570     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1571     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1572     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1573     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1574     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1575     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1576     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1577     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1578     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1579     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1580
1581     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1583     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1584     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1585     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1586     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1587     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1588     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1589
1590     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1591     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1592     if (Subtarget->hasVLX())
1593       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1594
1595     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1596       const MVT VT = (MVT::SimpleValueType)i;
1597
1598       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1599
1600       // Do not attempt to promote non-512-bit vectors.
1601       if (!VT.is512BitVector())
1602         continue;
1603
1604       if (EltSize < 32) {
1605         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1606         setOperationAction(ISD::VSELECT,             VT, Legal);
1607       }
1608     }
1609   }
1610
1611   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1612     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1613     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1614
1615     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1616     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1617     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1618     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1619     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1620     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1621     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1622     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1623     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1624     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1625
1626     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1627     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1628     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1629     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1630     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1631     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1632     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1633     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1634
1635     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1637     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1638     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1639     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1640     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1641     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1642     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1643   }
1644
1645   // We want to custom lower some of our intrinsics.
1646   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1647   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1648   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1649   if (!Subtarget->is64Bit())
1650     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1651
1652   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1653   // handle type legalization for these operations here.
1654   //
1655   // FIXME: We really should do custom legalization for addition and
1656   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1657   // than generic legalization for 64-bit multiplication-with-overflow, though.
1658   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1659     // Add/Sub/Mul with overflow operations are custom lowered.
1660     MVT VT = IntVTs[i];
1661     setOperationAction(ISD::SADDO, VT, Custom);
1662     setOperationAction(ISD::UADDO, VT, Custom);
1663     setOperationAction(ISD::SSUBO, VT, Custom);
1664     setOperationAction(ISD::USUBO, VT, Custom);
1665     setOperationAction(ISD::SMULO, VT, Custom);
1666     setOperationAction(ISD::UMULO, VT, Custom);
1667   }
1668
1669
1670   if (!Subtarget->is64Bit()) {
1671     // These libcalls are not available in 32-bit.
1672     setLibcallName(RTLIB::SHL_I128, nullptr);
1673     setLibcallName(RTLIB::SRL_I128, nullptr);
1674     setLibcallName(RTLIB::SRA_I128, nullptr);
1675   }
1676
1677   // Combine sin / cos into one node or libcall if possible.
1678   if (Subtarget->hasSinCos()) {
1679     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1680     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1681     if (Subtarget->isTargetDarwin()) {
1682       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1683       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1684       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1685       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1686     }
1687   }
1688
1689   if (Subtarget->isTargetWin64()) {
1690     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1691     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1692     setOperationAction(ISD::SREM, MVT::i128, Custom);
1693     setOperationAction(ISD::UREM, MVT::i128, Custom);
1694     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1695     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1696   }
1697
1698   // We have target-specific dag combine patterns for the following nodes:
1699   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1700   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1701   setTargetDAGCombine(ISD::BITCAST);
1702   setTargetDAGCombine(ISD::VSELECT);
1703   setTargetDAGCombine(ISD::SELECT);
1704   setTargetDAGCombine(ISD::SHL);
1705   setTargetDAGCombine(ISD::SRA);
1706   setTargetDAGCombine(ISD::SRL);
1707   setTargetDAGCombine(ISD::OR);
1708   setTargetDAGCombine(ISD::AND);
1709   setTargetDAGCombine(ISD::ADD);
1710   setTargetDAGCombine(ISD::FADD);
1711   setTargetDAGCombine(ISD::FSUB);
1712   setTargetDAGCombine(ISD::FMA);
1713   setTargetDAGCombine(ISD::SUB);
1714   setTargetDAGCombine(ISD::LOAD);
1715   setTargetDAGCombine(ISD::MLOAD);
1716   setTargetDAGCombine(ISD::STORE);
1717   setTargetDAGCombine(ISD::MSTORE);
1718   setTargetDAGCombine(ISD::ZERO_EXTEND);
1719   setTargetDAGCombine(ISD::ANY_EXTEND);
1720   setTargetDAGCombine(ISD::SIGN_EXTEND);
1721   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1722   setTargetDAGCombine(ISD::SINT_TO_FP);
1723   setTargetDAGCombine(ISD::UINT_TO_FP);
1724   setTargetDAGCombine(ISD::SETCC);
1725   setTargetDAGCombine(ISD::BUILD_VECTOR);
1726   setTargetDAGCombine(ISD::MUL);
1727   setTargetDAGCombine(ISD::XOR);
1728
1729   computeRegisterProperties(Subtarget->getRegisterInfo());
1730
1731   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1732   MaxStoresPerMemsetOptSize = 8;
1733   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1734   MaxStoresPerMemcpyOptSize = 4;
1735   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1736   MaxStoresPerMemmoveOptSize = 4;
1737   setPrefLoopAlignment(4); // 2^4 bytes.
1738
1739   // Predictable cmov don't hurt on atom because it's in-order.
1740   PredictableSelectIsExpensive = !Subtarget->isAtom();
1741   EnableExtLdPromotion = true;
1742   setPrefFunctionAlignment(4); // 2^4 bytes.
1743
1744   verifyIntrinsicTables();
1745 }
1746
1747 // This has so far only been implemented for 64-bit MachO.
1748 bool X86TargetLowering::useLoadStackGuardNode() const {
1749   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1750 }
1751
1752 TargetLoweringBase::LegalizeTypeAction
1753 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1754   if (ExperimentalVectorWideningLegalization &&
1755       VT.getVectorNumElements() != 1 &&
1756       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1757     return TypeWidenVector;
1758
1759   return TargetLoweringBase::getPreferredVectorAction(VT);
1760 }
1761
1762 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1763                                           EVT VT) const {
1764   if (!VT.isVector())
1765     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1766
1767   const unsigned NumElts = VT.getVectorNumElements();
1768   const EVT EltVT = VT.getVectorElementType();
1769   if (VT.is512BitVector()) {
1770     if (Subtarget->hasAVX512())
1771       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1772           EltVT == MVT::f32 || EltVT == MVT::f64)
1773         switch(NumElts) {
1774         case  8: return MVT::v8i1;
1775         case 16: return MVT::v16i1;
1776       }
1777     if (Subtarget->hasBWI())
1778       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1779         switch(NumElts) {
1780         case 32: return MVT::v32i1;
1781         case 64: return MVT::v64i1;
1782       }
1783   }
1784
1785   if (VT.is256BitVector() || VT.is128BitVector()) {
1786     if (Subtarget->hasVLX())
1787       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1788           EltVT == MVT::f32 || EltVT == MVT::f64)
1789         switch(NumElts) {
1790         case 2: return MVT::v2i1;
1791         case 4: return MVT::v4i1;
1792         case 8: return MVT::v8i1;
1793       }
1794     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1795       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1796         switch(NumElts) {
1797         case  8: return MVT::v8i1;
1798         case 16: return MVT::v16i1;
1799         case 32: return MVT::v32i1;
1800       }
1801   }
1802
1803   return VT.changeVectorElementTypeToInteger();
1804 }
1805
1806 /// Helper for getByValTypeAlignment to determine
1807 /// the desired ByVal argument alignment.
1808 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1809   if (MaxAlign == 16)
1810     return;
1811   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1812     if (VTy->getBitWidth() == 128)
1813       MaxAlign = 16;
1814   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1815     unsigned EltAlign = 0;
1816     getMaxByValAlign(ATy->getElementType(), EltAlign);
1817     if (EltAlign > MaxAlign)
1818       MaxAlign = EltAlign;
1819   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1820     for (auto *EltTy : STy->elements()) {
1821       unsigned EltAlign = 0;
1822       getMaxByValAlign(EltTy, EltAlign);
1823       if (EltAlign > MaxAlign)
1824         MaxAlign = EltAlign;
1825       if (MaxAlign == 16)
1826         break;
1827     }
1828   }
1829 }
1830
1831 /// Return the desired alignment for ByVal aggregate
1832 /// function arguments in the caller parameter area. For X86, aggregates
1833 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1834 /// are at 4-byte boundaries.
1835 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1836                                                   const DataLayout &DL) const {
1837   if (Subtarget->is64Bit()) {
1838     // Max of 8 and alignment of type.
1839     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1840     if (TyAlign > 8)
1841       return TyAlign;
1842     return 8;
1843   }
1844
1845   unsigned Align = 4;
1846   if (Subtarget->hasSSE1())
1847     getMaxByValAlign(Ty, Align);
1848   return Align;
1849 }
1850
1851 /// Returns the target specific optimal type for load
1852 /// and store operations as a result of memset, memcpy, and memmove
1853 /// lowering. If DstAlign is zero that means it's safe to destination
1854 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1855 /// means there isn't a need to check it against alignment requirement,
1856 /// probably because the source does not need to be loaded. If 'IsMemset' is
1857 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1858 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1859 /// source is constant so it does not need to be loaded.
1860 /// It returns EVT::Other if the type should be determined using generic
1861 /// target-independent logic.
1862 EVT
1863 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1864                                        unsigned DstAlign, unsigned SrcAlign,
1865                                        bool IsMemset, bool ZeroMemset,
1866                                        bool MemcpyStrSrc,
1867                                        MachineFunction &MF) const {
1868   const Function *F = MF.getFunction();
1869   if ((!IsMemset || ZeroMemset) &&
1870       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1871     if (Size >= 16 &&
1872         (!Subtarget->isUnalignedMemUnder32Slow() ||
1873          ((DstAlign == 0 || DstAlign >= 16) &&
1874           (SrcAlign == 0 || SrcAlign >= 16)))) {
1875       if (Size >= 32) {
1876         // FIXME: Check if unaligned 32-byte accesses are slow.
1877         if (Subtarget->hasInt256())
1878           return MVT::v8i32;
1879         if (Subtarget->hasFp256())
1880           return MVT::v8f32;
1881       }
1882       if (Subtarget->hasSSE2())
1883         return MVT::v4i32;
1884       if (Subtarget->hasSSE1())
1885         return MVT::v4f32;
1886     } else if (!MemcpyStrSrc && Size >= 8 &&
1887                !Subtarget->is64Bit() &&
1888                Subtarget->hasSSE2()) {
1889       // Do not use f64 to lower memcpy if source is string constant. It's
1890       // better to use i32 to avoid the loads.
1891       return MVT::f64;
1892     }
1893   }
1894   // This is a compromise. If we reach here, unaligned accesses may be slow on
1895   // this target. However, creating smaller, aligned accesses could be even
1896   // slower and would certainly be a lot more code.
1897   if (Subtarget->is64Bit() && Size >= 8)
1898     return MVT::i64;
1899   return MVT::i32;
1900 }
1901
1902 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1903   if (VT == MVT::f32)
1904     return X86ScalarSSEf32;
1905   else if (VT == MVT::f64)
1906     return X86ScalarSSEf64;
1907   return true;
1908 }
1909
1910 bool
1911 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1912                                                   unsigned,
1913                                                   unsigned,
1914                                                   bool *Fast) const {
1915   if (Fast) {
1916     if (VT.getSizeInBits() == 256)
1917       *Fast = !Subtarget->isUnalignedMem32Slow();
1918     else
1919       *Fast = !Subtarget->isUnalignedMemUnder32Slow();
1920   }
1921   return true;
1922 }
1923
1924 /// Return the entry encoding for a jump table in the
1925 /// current function.  The returned value is a member of the
1926 /// MachineJumpTableInfo::JTEntryKind enum.
1927 unsigned X86TargetLowering::getJumpTableEncoding() const {
1928   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1929   // symbol.
1930   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1931       Subtarget->isPICStyleGOT())
1932     return MachineJumpTableInfo::EK_Custom32;
1933
1934   // Otherwise, use the normal jump table encoding heuristics.
1935   return TargetLowering::getJumpTableEncoding();
1936 }
1937
1938 bool X86TargetLowering::useSoftFloat() const {
1939   return Subtarget->useSoftFloat();
1940 }
1941
1942 const MCExpr *
1943 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1944                                              const MachineBasicBlock *MBB,
1945                                              unsigned uid,MCContext &Ctx) const{
1946   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1947          Subtarget->isPICStyleGOT());
1948   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1949   // entries.
1950   return MCSymbolRefExpr::create(MBB->getSymbol(),
1951                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1952 }
1953
1954 /// Returns relocation base for the given PIC jumptable.
1955 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1956                                                     SelectionDAG &DAG) const {
1957   if (!Subtarget->is64Bit())
1958     // This doesn't have SDLoc associated with it, but is not really the
1959     // same as a Register.
1960     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1961                        getPointerTy(DAG.getDataLayout()));
1962   return Table;
1963 }
1964
1965 /// This returns the relocation base for the given PIC jumptable,
1966 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1967 const MCExpr *X86TargetLowering::
1968 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1969                              MCContext &Ctx) const {
1970   // X86-64 uses RIP relative addressing based on the jump table label.
1971   if (Subtarget->isPICStyleRIPRel())
1972     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1973
1974   // Otherwise, the reference is relative to the PIC base.
1975   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1976 }
1977
1978 std::pair<const TargetRegisterClass *, uint8_t>
1979 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1980                                            MVT VT) const {
1981   const TargetRegisterClass *RRC = nullptr;
1982   uint8_t Cost = 1;
1983   switch (VT.SimpleTy) {
1984   default:
1985     return TargetLowering::findRepresentativeClass(TRI, VT);
1986   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1987     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1988     break;
1989   case MVT::x86mmx:
1990     RRC = &X86::VR64RegClass;
1991     break;
1992   case MVT::f32: case MVT::f64:
1993   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1994   case MVT::v4f32: case MVT::v2f64:
1995   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1996   case MVT::v4f64:
1997     RRC = &X86::VR128RegClass;
1998     break;
1999   }
2000   return std::make_pair(RRC, Cost);
2001 }
2002
2003 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2004                                                unsigned &Offset) const {
2005   if (!Subtarget->isTargetLinux())
2006     return false;
2007
2008   if (Subtarget->is64Bit()) {
2009     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2010     Offset = 0x28;
2011     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2012       AddressSpace = 256;
2013     else
2014       AddressSpace = 257;
2015   } else {
2016     // %gs:0x14 on i386
2017     Offset = 0x14;
2018     AddressSpace = 256;
2019   }
2020   return true;
2021 }
2022
2023 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2024                                             unsigned DestAS) const {
2025   assert(SrcAS != DestAS && "Expected different address spaces!");
2026
2027   return SrcAS < 256 && DestAS < 256;
2028 }
2029
2030 //===----------------------------------------------------------------------===//
2031 //               Return Value Calling Convention Implementation
2032 //===----------------------------------------------------------------------===//
2033
2034 #include "X86GenCallingConv.inc"
2035
2036 bool
2037 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2038                                   MachineFunction &MF, bool isVarArg,
2039                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2040                         LLVMContext &Context) const {
2041   SmallVector<CCValAssign, 16> RVLocs;
2042   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2043   return CCInfo.CheckReturn(Outs, RetCC_X86);
2044 }
2045
2046 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2047   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2048   return ScratchRegs;
2049 }
2050
2051 SDValue
2052 X86TargetLowering::LowerReturn(SDValue Chain,
2053                                CallingConv::ID CallConv, bool isVarArg,
2054                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2055                                const SmallVectorImpl<SDValue> &OutVals,
2056                                SDLoc dl, SelectionDAG &DAG) const {
2057   MachineFunction &MF = DAG.getMachineFunction();
2058   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2059
2060   SmallVector<CCValAssign, 16> RVLocs;
2061   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2062   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2063
2064   SDValue Flag;
2065   SmallVector<SDValue, 6> RetOps;
2066   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2067   // Operand #1 = Bytes To Pop
2068   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2069                    MVT::i16));
2070
2071   // Copy the result values into the output registers.
2072   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2073     CCValAssign &VA = RVLocs[i];
2074     assert(VA.isRegLoc() && "Can only return in registers!");
2075     SDValue ValToCopy = OutVals[i];
2076     EVT ValVT = ValToCopy.getValueType();
2077
2078     // Promote values to the appropriate types.
2079     if (VA.getLocInfo() == CCValAssign::SExt)
2080       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2081     else if (VA.getLocInfo() == CCValAssign::ZExt)
2082       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2083     else if (VA.getLocInfo() == CCValAssign::AExt) {
2084       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2085         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2086       else
2087         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2088     }
2089     else if (VA.getLocInfo() == CCValAssign::BCvt)
2090       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2091
2092     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2093            "Unexpected FP-extend for return value.");
2094
2095     // If this is x86-64, and we disabled SSE, we can't return FP values,
2096     // or SSE or MMX vectors.
2097     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2098          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2099           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2100       report_fatal_error("SSE register return with SSE disabled");
2101     }
2102     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2103     // llvm-gcc has never done it right and no one has noticed, so this
2104     // should be OK for now.
2105     if (ValVT == MVT::f64 &&
2106         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2107       report_fatal_error("SSE2 register return with SSE2 disabled");
2108
2109     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2110     // the RET instruction and handled by the FP Stackifier.
2111     if (VA.getLocReg() == X86::FP0 ||
2112         VA.getLocReg() == X86::FP1) {
2113       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2114       // change the value to the FP stack register class.
2115       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2116         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2117       RetOps.push_back(ValToCopy);
2118       // Don't emit a copytoreg.
2119       continue;
2120     }
2121
2122     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2123     // which is returned in RAX / RDX.
2124     if (Subtarget->is64Bit()) {
2125       if (ValVT == MVT::x86mmx) {
2126         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2127           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2128           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2129                                   ValToCopy);
2130           // If we don't have SSE2 available, convert to v4f32 so the generated
2131           // register is legal.
2132           if (!Subtarget->hasSSE2())
2133             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2134         }
2135       }
2136     }
2137
2138     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2139     Flag = Chain.getValue(1);
2140     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2141   }
2142
2143   // All x86 ABIs require that for returning structs by value we copy
2144   // the sret argument into %rax/%eax (depending on ABI) for the return.
2145   // We saved the argument into a virtual register in the entry block,
2146   // so now we copy the value out and into %rax/%eax.
2147   //
2148   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2149   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2150   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2151   // either case FuncInfo->setSRetReturnReg() will have been called.
2152   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2153     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2154                                      getPointerTy(MF.getDataLayout()));
2155
2156     unsigned RetValReg
2157         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2158           X86::RAX : X86::EAX;
2159     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2160     Flag = Chain.getValue(1);
2161
2162     // RAX/EAX now acts like a return value.
2163     RetOps.push_back(
2164         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2165   }
2166
2167   RetOps[0] = Chain;  // Update chain.
2168
2169   // Add the flag if we have it.
2170   if (Flag.getNode())
2171     RetOps.push_back(Flag);
2172
2173   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2174 }
2175
2176 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2177   if (N->getNumValues() != 1)
2178     return false;
2179   if (!N->hasNUsesOfValue(1, 0))
2180     return false;
2181
2182   SDValue TCChain = Chain;
2183   SDNode *Copy = *N->use_begin();
2184   if (Copy->getOpcode() == ISD::CopyToReg) {
2185     // If the copy has a glue operand, we conservatively assume it isn't safe to
2186     // perform a tail call.
2187     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2188       return false;
2189     TCChain = Copy->getOperand(0);
2190   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2191     return false;
2192
2193   bool HasRet = false;
2194   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2195        UI != UE; ++UI) {
2196     if (UI->getOpcode() != X86ISD::RET_FLAG)
2197       return false;
2198     // If we are returning more than one value, we can definitely
2199     // not make a tail call see PR19530
2200     if (UI->getNumOperands() > 4)
2201       return false;
2202     if (UI->getNumOperands() == 4 &&
2203         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2204       return false;
2205     HasRet = true;
2206   }
2207
2208   if (!HasRet)
2209     return false;
2210
2211   Chain = TCChain;
2212   return true;
2213 }
2214
2215 EVT
2216 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2217                                             ISD::NodeType ExtendKind) const {
2218   MVT ReturnMVT;
2219   // TODO: Is this also valid on 32-bit?
2220   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2221     ReturnMVT = MVT::i8;
2222   else
2223     ReturnMVT = MVT::i32;
2224
2225   EVT MinVT = getRegisterType(Context, ReturnMVT);
2226   return VT.bitsLT(MinVT) ? MinVT : VT;
2227 }
2228
2229 /// Lower the result values of a call into the
2230 /// appropriate copies out of appropriate physical registers.
2231 ///
2232 SDValue
2233 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2234                                    CallingConv::ID CallConv, bool isVarArg,
2235                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2236                                    SDLoc dl, SelectionDAG &DAG,
2237                                    SmallVectorImpl<SDValue> &InVals) const {
2238
2239   // Assign locations to each value returned by this call.
2240   SmallVector<CCValAssign, 16> RVLocs;
2241   bool Is64Bit = Subtarget->is64Bit();
2242   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2243                  *DAG.getContext());
2244   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2245
2246   // Copy all of the result registers out of their specified physreg.
2247   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2248     CCValAssign &VA = RVLocs[i];
2249     EVT CopyVT = VA.getLocVT();
2250
2251     // If this is x86-64, and we disabled SSE, we can't return FP values
2252     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2253         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2254       report_fatal_error("SSE register return with SSE disabled");
2255     }
2256
2257     // If we prefer to use the value in xmm registers, copy it out as f80 and
2258     // use a truncate to move it from fp stack reg to xmm reg.
2259     bool RoundAfterCopy = false;
2260     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2261         isScalarFPTypeInSSEReg(VA.getValVT())) {
2262       CopyVT = MVT::f80;
2263       RoundAfterCopy = (CopyVT != VA.getLocVT());
2264     }
2265
2266     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2267                                CopyVT, InFlag).getValue(1);
2268     SDValue Val = Chain.getValue(0);
2269
2270     if (RoundAfterCopy)
2271       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2272                         // This truncation won't change the value.
2273                         DAG.getIntPtrConstant(1, dl));
2274
2275     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2276       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2277
2278     InFlag = Chain.getValue(2);
2279     InVals.push_back(Val);
2280   }
2281
2282   return Chain;
2283 }
2284
2285 //===----------------------------------------------------------------------===//
2286 //                C & StdCall & Fast Calling Convention implementation
2287 //===----------------------------------------------------------------------===//
2288 //  StdCall calling convention seems to be standard for many Windows' API
2289 //  routines and around. It differs from C calling convention just a little:
2290 //  callee should clean up the stack, not caller. Symbols should be also
2291 //  decorated in some fancy way :) It doesn't support any vector arguments.
2292 //  For info on fast calling convention see Fast Calling Convention (tail call)
2293 //  implementation LowerX86_32FastCCCallTo.
2294
2295 /// CallIsStructReturn - Determines whether a call uses struct return
2296 /// semantics.
2297 enum StructReturnType {
2298   NotStructReturn,
2299   RegStructReturn,
2300   StackStructReturn
2301 };
2302 static StructReturnType
2303 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2304   if (Outs.empty())
2305     return NotStructReturn;
2306
2307   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2308   if (!Flags.isSRet())
2309     return NotStructReturn;
2310   if (Flags.isInReg())
2311     return RegStructReturn;
2312   return StackStructReturn;
2313 }
2314
2315 /// Determines whether a function uses struct return semantics.
2316 static StructReturnType
2317 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2318   if (Ins.empty())
2319     return NotStructReturn;
2320
2321   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2322   if (!Flags.isSRet())
2323     return NotStructReturn;
2324   if (Flags.isInReg())
2325     return RegStructReturn;
2326   return StackStructReturn;
2327 }
2328
2329 /// Make a copy of an aggregate at address specified by "Src" to address
2330 /// "Dst" with size and alignment information specified by the specific
2331 /// parameter attribute. The copy will be passed as a byval function parameter.
2332 static SDValue
2333 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2334                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2335                           SDLoc dl) {
2336   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2337
2338   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2339                        /*isVolatile*/false, /*AlwaysInline=*/true,
2340                        /*isTailCall*/false,
2341                        MachinePointerInfo(), MachinePointerInfo());
2342 }
2343
2344 /// Return true if the calling convention is one that
2345 /// supports tail call optimization.
2346 static bool IsTailCallConvention(CallingConv::ID CC) {
2347   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2348           CC == CallingConv::HiPE);
2349 }
2350
2351 /// \brief Return true if the calling convention is a C calling convention.
2352 static bool IsCCallConvention(CallingConv::ID CC) {
2353   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2354           CC == CallingConv::X86_64_SysV);
2355 }
2356
2357 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2358   auto Attr =
2359       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2360   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2361     return false;
2362
2363   CallSite CS(CI);
2364   CallingConv::ID CalleeCC = CS.getCallingConv();
2365   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2366     return false;
2367
2368   return true;
2369 }
2370
2371 /// Return true if the function is being made into
2372 /// a tailcall target by changing its ABI.
2373 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2374                                    bool GuaranteedTailCallOpt) {
2375   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2376 }
2377
2378 SDValue
2379 X86TargetLowering::LowerMemArgument(SDValue Chain,
2380                                     CallingConv::ID CallConv,
2381                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2382                                     SDLoc dl, SelectionDAG &DAG,
2383                                     const CCValAssign &VA,
2384                                     MachineFrameInfo *MFI,
2385                                     unsigned i) const {
2386   // Create the nodes corresponding to a load from this parameter slot.
2387   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2388   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2389       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2390   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2391   EVT ValVT;
2392
2393   // If value is passed by pointer we have address passed instead of the value
2394   // itself.
2395   bool ExtendedInMem = VA.isExtInLoc() &&
2396     VA.getValVT().getScalarType() == MVT::i1;
2397
2398   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2399     ValVT = VA.getLocVT();
2400   else
2401     ValVT = VA.getValVT();
2402
2403   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2404   // changed with more analysis.
2405   // In case of tail call optimization mark all arguments mutable. Since they
2406   // could be overwritten by lowering of arguments in case of a tail call.
2407   if (Flags.isByVal()) {
2408     unsigned Bytes = Flags.getByValSize();
2409     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2410     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2411     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2412   } else {
2413     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2414                                     VA.getLocMemOffset(), isImmutable);
2415     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2416     SDValue Val = DAG.getLoad(
2417         ValVT, dl, Chain, FIN,
2418         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2419         false, false, 0);
2420     return ExtendedInMem ?
2421       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2422   }
2423 }
2424
2425 // FIXME: Get this from tablegen.
2426 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2427                                                 const X86Subtarget *Subtarget) {
2428   assert(Subtarget->is64Bit());
2429
2430   if (Subtarget->isCallingConvWin64(CallConv)) {
2431     static const MCPhysReg GPR64ArgRegsWin64[] = {
2432       X86::RCX, X86::RDX, X86::R8,  X86::R9
2433     };
2434     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2435   }
2436
2437   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2438     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2439   };
2440   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2441 }
2442
2443 // FIXME: Get this from tablegen.
2444 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2445                                                 CallingConv::ID CallConv,
2446                                                 const X86Subtarget *Subtarget) {
2447   assert(Subtarget->is64Bit());
2448   if (Subtarget->isCallingConvWin64(CallConv)) {
2449     // The XMM registers which might contain var arg parameters are shadowed
2450     // in their paired GPR.  So we only need to save the GPR to their home
2451     // slots.
2452     // TODO: __vectorcall will change this.
2453     return None;
2454   }
2455
2456   const Function *Fn = MF.getFunction();
2457   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2458   bool isSoftFloat = Subtarget->useSoftFloat();
2459   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2460          "SSE register cannot be used when SSE is disabled!");
2461   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2462     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2463     // registers.
2464     return None;
2465
2466   static const MCPhysReg XMMArgRegs64Bit[] = {
2467     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2468     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2469   };
2470   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2471 }
2472
2473 SDValue
2474 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2475                                         CallingConv::ID CallConv,
2476                                         bool isVarArg,
2477                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2478                                         SDLoc dl,
2479                                         SelectionDAG &DAG,
2480                                         SmallVectorImpl<SDValue> &InVals)
2481                                           const {
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2484   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2485
2486   const Function* Fn = MF.getFunction();
2487   if (Fn->hasExternalLinkage() &&
2488       Subtarget->isTargetCygMing() &&
2489       Fn->getName() == "main")
2490     FuncInfo->setForceFramePointer(true);
2491
2492   MachineFrameInfo *MFI = MF.getFrameInfo();
2493   bool Is64Bit = Subtarget->is64Bit();
2494   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2495
2496   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2497          "Var args not supported with calling convention fastcc, ghc or hipe");
2498
2499   // Assign locations to all of the incoming arguments.
2500   SmallVector<CCValAssign, 16> ArgLocs;
2501   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2502
2503   // Allocate shadow area for Win64
2504   if (IsWin64)
2505     CCInfo.AllocateStack(32, 8);
2506
2507   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2508
2509   unsigned LastVal = ~0U;
2510   SDValue ArgValue;
2511   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2512     CCValAssign &VA = ArgLocs[i];
2513     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2514     // places.
2515     assert(VA.getValNo() != LastVal &&
2516            "Don't support value assigned to multiple locs yet");
2517     (void)LastVal;
2518     LastVal = VA.getValNo();
2519
2520     if (VA.isRegLoc()) {
2521       EVT RegVT = VA.getLocVT();
2522       const TargetRegisterClass *RC;
2523       if (RegVT == MVT::i32)
2524         RC = &X86::GR32RegClass;
2525       else if (Is64Bit && RegVT == MVT::i64)
2526         RC = &X86::GR64RegClass;
2527       else if (RegVT == MVT::f32)
2528         RC = &X86::FR32RegClass;
2529       else if (RegVT == MVT::f64)
2530         RC = &X86::FR64RegClass;
2531       else if (RegVT.is512BitVector())
2532         RC = &X86::VR512RegClass;
2533       else if (RegVT.is256BitVector())
2534         RC = &X86::VR256RegClass;
2535       else if (RegVT.is128BitVector())
2536         RC = &X86::VR128RegClass;
2537       else if (RegVT == MVT::x86mmx)
2538         RC = &X86::VR64RegClass;
2539       else if (RegVT == MVT::i1)
2540         RC = &X86::VK1RegClass;
2541       else if (RegVT == MVT::v8i1)
2542         RC = &X86::VK8RegClass;
2543       else if (RegVT == MVT::v16i1)
2544         RC = &X86::VK16RegClass;
2545       else if (RegVT == MVT::v32i1)
2546         RC = &X86::VK32RegClass;
2547       else if (RegVT == MVT::v64i1)
2548         RC = &X86::VK64RegClass;
2549       else
2550         llvm_unreachable("Unknown argument type!");
2551
2552       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2553       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2554
2555       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2556       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2557       // right size.
2558       if (VA.getLocInfo() == CCValAssign::SExt)
2559         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2560                                DAG.getValueType(VA.getValVT()));
2561       else if (VA.getLocInfo() == CCValAssign::ZExt)
2562         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2563                                DAG.getValueType(VA.getValVT()));
2564       else if (VA.getLocInfo() == CCValAssign::BCvt)
2565         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2566
2567       if (VA.isExtInLoc()) {
2568         // Handle MMX values passed in XMM regs.
2569         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2570           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2571         else
2572           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2573       }
2574     } else {
2575       assert(VA.isMemLoc());
2576       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2577     }
2578
2579     // If value is passed via pointer - do a load.
2580     if (VA.getLocInfo() == CCValAssign::Indirect)
2581       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2582                              MachinePointerInfo(), false, false, false, 0);
2583
2584     InVals.push_back(ArgValue);
2585   }
2586
2587   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2588     // All x86 ABIs require that for returning structs by value we copy the
2589     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2590     // the argument into a virtual register so that we can access it from the
2591     // return points.
2592     if (Ins[i].Flags.isSRet()) {
2593       unsigned Reg = FuncInfo->getSRetReturnReg();
2594       if (!Reg) {
2595         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2596         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2597         FuncInfo->setSRetReturnReg(Reg);
2598       }
2599       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2600       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2601       break;
2602     }
2603   }
2604
2605   unsigned StackSize = CCInfo.getNextStackOffset();
2606   // Align stack specially for tail calls.
2607   if (FuncIsMadeTailCallSafe(CallConv,
2608                              MF.getTarget().Options.GuaranteedTailCallOpt))
2609     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2610
2611   // If the function takes variable number of arguments, make a frame index for
2612   // the start of the first vararg value... for expansion of llvm.va_start. We
2613   // can skip this if there are no va_start calls.
2614   if (MFI->hasVAStart() &&
2615       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2616                    CallConv != CallingConv::X86_ThisCall))) {
2617     FuncInfo->setVarArgsFrameIndex(
2618         MFI->CreateFixedObject(1, StackSize, true));
2619   }
2620
2621   MachineModuleInfo &MMI = MF.getMMI();
2622   const Function *WinEHParent = nullptr;
2623   if (MMI.hasWinEHFuncInfo(Fn))
2624     WinEHParent = MMI.getWinEHParent(Fn);
2625   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2626   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2627
2628   // Figure out if XMM registers are in use.
2629   assert(!(Subtarget->useSoftFloat() &&
2630            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2631          "SSE register cannot be used when SSE is disabled!");
2632
2633   // 64-bit calling conventions support varargs and register parameters, so we
2634   // have to do extra work to spill them in the prologue.
2635   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2636     // Find the first unallocated argument registers.
2637     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2638     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2639     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2640     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2641     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2642            "SSE register cannot be used when SSE is disabled!");
2643
2644     // Gather all the live in physical registers.
2645     SmallVector<SDValue, 6> LiveGPRs;
2646     SmallVector<SDValue, 8> LiveXMMRegs;
2647     SDValue ALVal;
2648     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2649       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2650       LiveGPRs.push_back(
2651           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2652     }
2653     if (!ArgXMMs.empty()) {
2654       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2655       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2656       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2657         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2658         LiveXMMRegs.push_back(
2659             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2660       }
2661     }
2662
2663     if (IsWin64) {
2664       // Get to the caller-allocated home save location.  Add 8 to account
2665       // for the return address.
2666       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2667       FuncInfo->setRegSaveFrameIndex(
2668           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2669       // Fixup to set vararg frame on shadow area (4 x i64).
2670       if (NumIntRegs < 4)
2671         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2672     } else {
2673       // For X86-64, if there are vararg parameters that are passed via
2674       // registers, then we must store them to their spots on the stack so
2675       // they may be loaded by deferencing the result of va_next.
2676       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2677       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2678       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2679           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2680     }
2681
2682     // Store the integer parameter registers.
2683     SmallVector<SDValue, 8> MemOps;
2684     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2685                                       getPointerTy(DAG.getDataLayout()));
2686     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2687     for (SDValue Val : LiveGPRs) {
2688       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2689                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2690       SDValue Store =
2691           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2692                        MachinePointerInfo::getFixedStack(
2693                            DAG.getMachineFunction(),
2694                            FuncInfo->getRegSaveFrameIndex(), Offset),
2695                        false, false, 0);
2696       MemOps.push_back(Store);
2697       Offset += 8;
2698     }
2699
2700     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2701       // Now store the XMM (fp + vector) parameter registers.
2702       SmallVector<SDValue, 12> SaveXMMOps;
2703       SaveXMMOps.push_back(Chain);
2704       SaveXMMOps.push_back(ALVal);
2705       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2706                              FuncInfo->getRegSaveFrameIndex(), dl));
2707       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2708                              FuncInfo->getVarArgsFPOffset(), dl));
2709       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2710                         LiveXMMRegs.end());
2711       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2712                                    MVT::Other, SaveXMMOps));
2713     }
2714
2715     if (!MemOps.empty())
2716       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2717   } else if (IsWin64 && IsWinEHOutlined) {
2718     // Get to the caller-allocated home save location.  Add 8 to account
2719     // for the return address.
2720     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2721     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2722         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2723
2724     MMI.getWinEHFuncInfo(Fn)
2725         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2726         FuncInfo->getRegSaveFrameIndex();
2727
2728     // Store the second integer parameter (rdx) into rsp+16 relative to the
2729     // stack pointer at the entry of the function.
2730     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2731                                       getPointerTy(DAG.getDataLayout()));
2732     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2733     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2734     Chain = DAG.getStore(
2735         Val.getValue(1), dl, Val, RSFIN,
2736         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2737                                           FuncInfo->getRegSaveFrameIndex()),
2738         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2739   }
2740
2741   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2742     // Find the largest legal vector type.
2743     MVT VecVT = MVT::Other;
2744     // FIXME: Only some x86_32 calling conventions support AVX512.
2745     if (Subtarget->hasAVX512() &&
2746         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2747                      CallConv == CallingConv::Intel_OCL_BI)))
2748       VecVT = MVT::v16f32;
2749     else if (Subtarget->hasAVX())
2750       VecVT = MVT::v8f32;
2751     else if (Subtarget->hasSSE2())
2752       VecVT = MVT::v4f32;
2753
2754     // We forward some GPRs and some vector types.
2755     SmallVector<MVT, 2> RegParmTypes;
2756     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2757     RegParmTypes.push_back(IntVT);
2758     if (VecVT != MVT::Other)
2759       RegParmTypes.push_back(VecVT);
2760
2761     // Compute the set of forwarded registers. The rest are scratch.
2762     SmallVectorImpl<ForwardedRegister> &Forwards =
2763         FuncInfo->getForwardedMustTailRegParms();
2764     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2765
2766     // Conservatively forward AL on x86_64, since it might be used for varargs.
2767     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2768       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2769       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2770     }
2771
2772     // Copy all forwards from physical to virtual registers.
2773     for (ForwardedRegister &F : Forwards) {
2774       // FIXME: Can we use a less constrained schedule?
2775       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2776       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2777       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2778     }
2779   }
2780
2781   // Some CCs need callee pop.
2782   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2783                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2784     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2785   } else {
2786     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2787     // If this is an sret function, the return should pop the hidden pointer.
2788     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2789         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2790         argsAreStructReturn(Ins) == StackStructReturn)
2791       FuncInfo->setBytesToPopOnReturn(4);
2792   }
2793
2794   if (!Is64Bit) {
2795     // RegSaveFrameIndex is X86-64 only.
2796     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2797     if (CallConv == CallingConv::X86_FastCall ||
2798         CallConv == CallingConv::X86_ThisCall)
2799       // fastcc functions can't have varargs.
2800       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2801   }
2802
2803   FuncInfo->setArgumentStackSize(StackSize);
2804
2805   if (IsWinEHParent) {
2806     if (Is64Bit) {
2807       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2808       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2809       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2810       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2811       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2812                            MachinePointerInfo::getFixedStack(
2813                                DAG.getMachineFunction(), UnwindHelpFI),
2814                            /*isVolatile=*/true,
2815                            /*isNonTemporal=*/false, /*Alignment=*/0);
2816     } else {
2817       // Functions using Win32 EH are considered to have opaque SP adjustments
2818       // to force local variables to be addressed from the frame or base
2819       // pointers.
2820       MFI->setHasOpaqueSPAdjustment(true);
2821     }
2822   }
2823
2824   return Chain;
2825 }
2826
2827 SDValue
2828 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2829                                     SDValue StackPtr, SDValue Arg,
2830                                     SDLoc dl, SelectionDAG &DAG,
2831                                     const CCValAssign &VA,
2832                                     ISD::ArgFlagsTy Flags) const {
2833   unsigned LocMemOffset = VA.getLocMemOffset();
2834   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2835   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2836                        StackPtr, PtrOff);
2837   if (Flags.isByVal())
2838     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2839
2840   return DAG.getStore(
2841       Chain, dl, Arg, PtrOff,
2842       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2843       false, false, 0);
2844 }
2845
2846 /// Emit a load of return address if tail call
2847 /// optimization is performed and it is required.
2848 SDValue
2849 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2850                                            SDValue &OutRetAddr, SDValue Chain,
2851                                            bool IsTailCall, bool Is64Bit,
2852                                            int FPDiff, SDLoc dl) const {
2853   // Adjust the Return address stack slot.
2854   EVT VT = getPointerTy(DAG.getDataLayout());
2855   OutRetAddr = getReturnAddressFrameIndex(DAG);
2856
2857   // Load the "old" Return address.
2858   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2859                            false, false, false, 0);
2860   return SDValue(OutRetAddr.getNode(), 1);
2861 }
2862
2863 /// Emit a store of the return address if tail call
2864 /// optimization is performed and it is required (FPDiff!=0).
2865 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2866                                         SDValue Chain, SDValue RetAddrFrIdx,
2867                                         EVT PtrVT, unsigned SlotSize,
2868                                         int FPDiff, SDLoc dl) {
2869   // Store the return address to the appropriate stack slot.
2870   if (!FPDiff) return Chain;
2871   // Calculate the new stack slot for the return address.
2872   int NewReturnAddrFI =
2873     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2874                                          false);
2875   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2876   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2877                        MachinePointerInfo::getFixedStack(
2878                            DAG.getMachineFunction(), NewReturnAddrFI),
2879                        false, false, 0);
2880   return Chain;
2881 }
2882
2883 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2884 /// operation of specified width.
2885 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2886                        SDValue V2) {
2887   unsigned NumElems = VT.getVectorNumElements();
2888   SmallVector<int, 8> Mask;
2889   Mask.push_back(NumElems);
2890   for (unsigned i = 1; i != NumElems; ++i)
2891     Mask.push_back(i);
2892   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2893 }
2894
2895 SDValue
2896 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2897                              SmallVectorImpl<SDValue> &InVals) const {
2898   SelectionDAG &DAG                     = CLI.DAG;
2899   SDLoc &dl                             = CLI.DL;
2900   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2901   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2902   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2903   SDValue Chain                         = CLI.Chain;
2904   SDValue Callee                        = CLI.Callee;
2905   CallingConv::ID CallConv              = CLI.CallConv;
2906   bool &isTailCall                      = CLI.IsTailCall;
2907   bool isVarArg                         = CLI.IsVarArg;
2908
2909   MachineFunction &MF = DAG.getMachineFunction();
2910   bool Is64Bit        = Subtarget->is64Bit();
2911   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2912   StructReturnType SR = callIsStructReturn(Outs);
2913   bool IsSibcall      = false;
2914   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2915   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2916
2917   if (Attr.getValueAsString() == "true")
2918     isTailCall = false;
2919
2920   if (Subtarget->isPICStyleGOT() &&
2921       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2922     // If we are using a GOT, disable tail calls to external symbols with
2923     // default visibility. Tail calling such a symbol requires using a GOT
2924     // relocation, which forces early binding of the symbol. This breaks code
2925     // that require lazy function symbol resolution. Using musttail or
2926     // GuaranteedTailCallOpt will override this.
2927     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2928     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2929                G->getGlobal()->hasDefaultVisibility()))
2930       isTailCall = false;
2931   }
2932
2933   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2934   if (IsMustTail) {
2935     // Force this to be a tail call.  The verifier rules are enough to ensure
2936     // that we can lower this successfully without moving the return address
2937     // around.
2938     isTailCall = true;
2939   } else if (isTailCall) {
2940     // Check if it's really possible to do a tail call.
2941     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2942                     isVarArg, SR != NotStructReturn,
2943                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2944                     Outs, OutVals, Ins, DAG);
2945
2946     // Sibcalls are automatically detected tailcalls which do not require
2947     // ABI changes.
2948     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2949       IsSibcall = true;
2950
2951     if (isTailCall)
2952       ++NumTailCalls;
2953   }
2954
2955   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2956          "Var args not supported with calling convention fastcc, ghc or hipe");
2957
2958   // Analyze operands of the call, assigning locations to each operand.
2959   SmallVector<CCValAssign, 16> ArgLocs;
2960   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2961
2962   // Allocate shadow area for Win64
2963   if (IsWin64)
2964     CCInfo.AllocateStack(32, 8);
2965
2966   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2967
2968   // Get a count of how many bytes are to be pushed on the stack.
2969   unsigned NumBytes = CCInfo.getNextStackOffset();
2970   if (IsSibcall)
2971     // This is a sibcall. The memory operands are available in caller's
2972     // own caller's stack.
2973     NumBytes = 0;
2974   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2975            IsTailCallConvention(CallConv))
2976     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2977
2978   int FPDiff = 0;
2979   if (isTailCall && !IsSibcall && !IsMustTail) {
2980     // Lower arguments at fp - stackoffset + fpdiff.
2981     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2982
2983     FPDiff = NumBytesCallerPushed - NumBytes;
2984
2985     // Set the delta of movement of the returnaddr stackslot.
2986     // But only set if delta is greater than previous delta.
2987     if (FPDiff < X86Info->getTCReturnAddrDelta())
2988       X86Info->setTCReturnAddrDelta(FPDiff);
2989   }
2990
2991   unsigned NumBytesToPush = NumBytes;
2992   unsigned NumBytesToPop = NumBytes;
2993
2994   // If we have an inalloca argument, all stack space has already been allocated
2995   // for us and be right at the top of the stack.  We don't support multiple
2996   // arguments passed in memory when using inalloca.
2997   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2998     NumBytesToPush = 0;
2999     if (!ArgLocs.back().isMemLoc())
3000       report_fatal_error("cannot use inalloca attribute on a register "
3001                          "parameter");
3002     if (ArgLocs.back().getLocMemOffset() != 0)
3003       report_fatal_error("any parameter with the inalloca attribute must be "
3004                          "the only memory argument");
3005   }
3006
3007   if (!IsSibcall)
3008     Chain = DAG.getCALLSEQ_START(
3009         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3010
3011   SDValue RetAddrFrIdx;
3012   // Load return address for tail calls.
3013   if (isTailCall && FPDiff)
3014     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3015                                     Is64Bit, FPDiff, dl);
3016
3017   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3018   SmallVector<SDValue, 8> MemOpChains;
3019   SDValue StackPtr;
3020
3021   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3022   // of tail call optimization arguments are handle later.
3023   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3024   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3025     // Skip inalloca arguments, they have already been written.
3026     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3027     if (Flags.isInAlloca())
3028       continue;
3029
3030     CCValAssign &VA = ArgLocs[i];
3031     EVT RegVT = VA.getLocVT();
3032     SDValue Arg = OutVals[i];
3033     bool isByVal = Flags.isByVal();
3034
3035     // Promote the value if needed.
3036     switch (VA.getLocInfo()) {
3037     default: llvm_unreachable("Unknown loc info!");
3038     case CCValAssign::Full: break;
3039     case CCValAssign::SExt:
3040       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3041       break;
3042     case CCValAssign::ZExt:
3043       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3044       break;
3045     case CCValAssign::AExt:
3046       if (Arg.getValueType().isVector() &&
3047           Arg.getValueType().getScalarType() == MVT::i1)
3048         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3049       else if (RegVT.is128BitVector()) {
3050         // Special case: passing MMX values in XMM registers.
3051         Arg = DAG.getBitcast(MVT::i64, Arg);
3052         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3053         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3054       } else
3055         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3056       break;
3057     case CCValAssign::BCvt:
3058       Arg = DAG.getBitcast(RegVT, Arg);
3059       break;
3060     case CCValAssign::Indirect: {
3061       // Store the argument.
3062       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3063       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3064       Chain = DAG.getStore(
3065           Chain, dl, Arg, SpillSlot,
3066           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3067           false, false, 0);
3068       Arg = SpillSlot;
3069       break;
3070     }
3071     }
3072
3073     if (VA.isRegLoc()) {
3074       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3075       if (isVarArg && IsWin64) {
3076         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3077         // shadow reg if callee is a varargs function.
3078         unsigned ShadowReg = 0;
3079         switch (VA.getLocReg()) {
3080         case X86::XMM0: ShadowReg = X86::RCX; break;
3081         case X86::XMM1: ShadowReg = X86::RDX; break;
3082         case X86::XMM2: ShadowReg = X86::R8; break;
3083         case X86::XMM3: ShadowReg = X86::R9; break;
3084         }
3085         if (ShadowReg)
3086           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3087       }
3088     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3089       assert(VA.isMemLoc());
3090       if (!StackPtr.getNode())
3091         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3092                                       getPointerTy(DAG.getDataLayout()));
3093       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3094                                              dl, DAG, VA, Flags));
3095     }
3096   }
3097
3098   if (!MemOpChains.empty())
3099     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3100
3101   if (Subtarget->isPICStyleGOT()) {
3102     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3103     // GOT pointer.
3104     if (!isTailCall) {
3105       RegsToPass.push_back(std::make_pair(
3106           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3107                                           getPointerTy(DAG.getDataLayout()))));
3108     } else {
3109       // If we are tail calling and generating PIC/GOT style code load the
3110       // address of the callee into ECX. The value in ecx is used as target of
3111       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3112       // for tail calls on PIC/GOT architectures. Normally we would just put the
3113       // address of GOT into ebx and then call target@PLT. But for tail calls
3114       // ebx would be restored (since ebx is callee saved) before jumping to the
3115       // target@PLT.
3116
3117       // Note: The actual moving to ECX is done further down.
3118       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3119       if (G && !G->getGlobal()->hasLocalLinkage() &&
3120           G->getGlobal()->hasDefaultVisibility())
3121         Callee = LowerGlobalAddress(Callee, DAG);
3122       else if (isa<ExternalSymbolSDNode>(Callee))
3123         Callee = LowerExternalSymbol(Callee, DAG);
3124     }
3125   }
3126
3127   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3128     // From AMD64 ABI document:
3129     // For calls that may call functions that use varargs or stdargs
3130     // (prototype-less calls or calls to functions containing ellipsis (...) in
3131     // the declaration) %al is used as hidden argument to specify the number
3132     // of SSE registers used. The contents of %al do not need to match exactly
3133     // the number of registers, but must be an ubound on the number of SSE
3134     // registers used and is in the range 0 - 8 inclusive.
3135
3136     // Count the number of XMM registers allocated.
3137     static const MCPhysReg XMMArgRegs[] = {
3138       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3139       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3140     };
3141     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3142     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3143            && "SSE registers cannot be used when SSE is disabled");
3144
3145     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3146                                         DAG.getConstant(NumXMMRegs, dl,
3147                                                         MVT::i8)));
3148   }
3149
3150   if (isVarArg && IsMustTail) {
3151     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3152     for (const auto &F : Forwards) {
3153       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3154       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3155     }
3156   }
3157
3158   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3159   // don't need this because the eligibility check rejects calls that require
3160   // shuffling arguments passed in memory.
3161   if (!IsSibcall && isTailCall) {
3162     // Force all the incoming stack arguments to be loaded from the stack
3163     // before any new outgoing arguments are stored to the stack, because the
3164     // outgoing stack slots may alias the incoming argument stack slots, and
3165     // the alias isn't otherwise explicit. This is slightly more conservative
3166     // than necessary, because it means that each store effectively depends
3167     // on every argument instead of just those arguments it would clobber.
3168     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3169
3170     SmallVector<SDValue, 8> MemOpChains2;
3171     SDValue FIN;
3172     int FI = 0;
3173     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3174       CCValAssign &VA = ArgLocs[i];
3175       if (VA.isRegLoc())
3176         continue;
3177       assert(VA.isMemLoc());
3178       SDValue Arg = OutVals[i];
3179       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3180       // Skip inalloca arguments.  They don't require any work.
3181       if (Flags.isInAlloca())
3182         continue;
3183       // Create frame index.
3184       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3185       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3186       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3187       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3188
3189       if (Flags.isByVal()) {
3190         // Copy relative to framepointer.
3191         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3192         if (!StackPtr.getNode())
3193           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3194                                         getPointerTy(DAG.getDataLayout()));
3195         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3196                              StackPtr, Source);
3197
3198         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3199                                                          ArgChain,
3200                                                          Flags, DAG, dl));
3201       } else {
3202         // Store relative to framepointer.
3203         MemOpChains2.push_back(DAG.getStore(
3204             ArgChain, dl, Arg, FIN,
3205             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3206             false, false, 0));
3207       }
3208     }
3209
3210     if (!MemOpChains2.empty())
3211       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3212
3213     // Store the return address to the appropriate stack slot.
3214     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3215                                      getPointerTy(DAG.getDataLayout()),
3216                                      RegInfo->getSlotSize(), FPDiff, dl);
3217   }
3218
3219   // Build a sequence of copy-to-reg nodes chained together with token chain
3220   // and flag operands which copy the outgoing args into registers.
3221   SDValue InFlag;
3222   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3223     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3224                              RegsToPass[i].second, InFlag);
3225     InFlag = Chain.getValue(1);
3226   }
3227
3228   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3229     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3230     // In the 64-bit large code model, we have to make all calls
3231     // through a register, since the call instruction's 32-bit
3232     // pc-relative offset may not be large enough to hold the whole
3233     // address.
3234   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3235     // If the callee is a GlobalAddress node (quite common, every direct call
3236     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3237     // it.
3238     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3239
3240     // We should use extra load for direct calls to dllimported functions in
3241     // non-JIT mode.
3242     const GlobalValue *GV = G->getGlobal();
3243     if (!GV->hasDLLImportStorageClass()) {
3244       unsigned char OpFlags = 0;
3245       bool ExtraLoad = false;
3246       unsigned WrapperKind = ISD::DELETED_NODE;
3247
3248       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3249       // external symbols most go through the PLT in PIC mode.  If the symbol
3250       // has hidden or protected visibility, or if it is static or local, then
3251       // we don't need to use the PLT - we can directly call it.
3252       if (Subtarget->isTargetELF() &&
3253           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3254           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3255         OpFlags = X86II::MO_PLT;
3256       } else if (Subtarget->isPICStyleStubAny() &&
3257                  !GV->isStrongDefinitionForLinker() &&
3258                  (!Subtarget->getTargetTriple().isMacOSX() ||
3259                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3260         // PC-relative references to external symbols should go through $stub,
3261         // unless we're building with the leopard linker or later, which
3262         // automatically synthesizes these stubs.
3263         OpFlags = X86II::MO_DARWIN_STUB;
3264       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3265                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3266         // If the function is marked as non-lazy, generate an indirect call
3267         // which loads from the GOT directly. This avoids runtime overhead
3268         // at the cost of eager binding (and one extra byte of encoding).
3269         OpFlags = X86II::MO_GOTPCREL;
3270         WrapperKind = X86ISD::WrapperRIP;
3271         ExtraLoad = true;
3272       }
3273
3274       Callee = DAG.getTargetGlobalAddress(
3275           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3276
3277       // Add a wrapper if needed.
3278       if (WrapperKind != ISD::DELETED_NODE)
3279         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3280                              getPointerTy(DAG.getDataLayout()), Callee);
3281       // Add extra indirection if needed.
3282       if (ExtraLoad)
3283         Callee = DAG.getLoad(
3284             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3285             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3286             false, 0);
3287     }
3288   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3289     unsigned char OpFlags = 0;
3290
3291     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3292     // external symbols should go through the PLT.
3293     if (Subtarget->isTargetELF() &&
3294         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3295       OpFlags = X86II::MO_PLT;
3296     } else if (Subtarget->isPICStyleStubAny() &&
3297                (!Subtarget->getTargetTriple().isMacOSX() ||
3298                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3299       // PC-relative references to external symbols should go through $stub,
3300       // unless we're building with the leopard linker or later, which
3301       // automatically synthesizes these stubs.
3302       OpFlags = X86II::MO_DARWIN_STUB;
3303     }
3304
3305     Callee = DAG.getTargetExternalSymbol(
3306         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3307   } else if (Subtarget->isTarget64BitILP32() &&
3308              Callee->getValueType(0) == MVT::i32) {
3309     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3310     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3311   }
3312
3313   // Returns a chain & a flag for retval copy to use.
3314   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3315   SmallVector<SDValue, 8> Ops;
3316
3317   if (!IsSibcall && isTailCall) {
3318     Chain = DAG.getCALLSEQ_END(Chain,
3319                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3320                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3321     InFlag = Chain.getValue(1);
3322   }
3323
3324   Ops.push_back(Chain);
3325   Ops.push_back(Callee);
3326
3327   if (isTailCall)
3328     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3329
3330   // Add argument registers to the end of the list so that they are known live
3331   // into the call.
3332   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3333     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3334                                   RegsToPass[i].second.getValueType()));
3335
3336   // Add a register mask operand representing the call-preserved registers.
3337   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3338   assert(Mask && "Missing call preserved mask for calling convention");
3339
3340   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3341   // the function clobbers all registers. If an exception is thrown, the runtime
3342   // will not restore CSRs.
3343   // FIXME: Model this more precisely so that we can register allocate across
3344   // the normal edge and spill and fill across the exceptional edge.
3345   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3346     const Function *CallerFn = MF.getFunction();
3347     EHPersonality Pers =
3348         CallerFn->hasPersonalityFn()
3349             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3350             : EHPersonality::Unknown;
3351     if (isMSVCEHPersonality(Pers))
3352       Mask = RegInfo->getNoPreservedMask();
3353   }
3354
3355   Ops.push_back(DAG.getRegisterMask(Mask));
3356
3357   if (InFlag.getNode())
3358     Ops.push_back(InFlag);
3359
3360   if (isTailCall) {
3361     // We used to do:
3362     //// If this is the first return lowered for this function, add the regs
3363     //// to the liveout set for the function.
3364     // This isn't right, although it's probably harmless on x86; liveouts
3365     // should be computed from returns not tail calls.  Consider a void
3366     // function making a tail call to a function returning int.
3367     MF.getFrameInfo()->setHasTailCall();
3368     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3369   }
3370
3371   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3372   InFlag = Chain.getValue(1);
3373
3374   // Create the CALLSEQ_END node.
3375   unsigned NumBytesForCalleeToPop;
3376   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3377                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3378     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3379   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3380            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3381            SR == StackStructReturn)
3382     // If this is a call to a struct-return function, the callee
3383     // pops the hidden struct pointer, so we have to push it back.
3384     // This is common for Darwin/X86, Linux & Mingw32 targets.
3385     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3386     NumBytesForCalleeToPop = 4;
3387   else
3388     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3389
3390   // Returns a flag for retval copy to use.
3391   if (!IsSibcall) {
3392     Chain = DAG.getCALLSEQ_END(Chain,
3393                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3394                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3395                                                      true),
3396                                InFlag, dl);
3397     InFlag = Chain.getValue(1);
3398   }
3399
3400   // Handle result values, copying them out of physregs into vregs that we
3401   // return.
3402   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3403                          Ins, dl, DAG, InVals);
3404 }
3405
3406 //===----------------------------------------------------------------------===//
3407 //                Fast Calling Convention (tail call) implementation
3408 //===----------------------------------------------------------------------===//
3409
3410 //  Like std call, callee cleans arguments, convention except that ECX is
3411 //  reserved for storing the tail called function address. Only 2 registers are
3412 //  free for argument passing (inreg). Tail call optimization is performed
3413 //  provided:
3414 //                * tailcallopt is enabled
3415 //                * caller/callee are fastcc
3416 //  On X86_64 architecture with GOT-style position independent code only local
3417 //  (within module) calls are supported at the moment.
3418 //  To keep the stack aligned according to platform abi the function
3419 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3420 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3421 //  If a tail called function callee has more arguments than the caller the
3422 //  caller needs to make sure that there is room to move the RETADDR to. This is
3423 //  achieved by reserving an area the size of the argument delta right after the
3424 //  original RETADDR, but before the saved framepointer or the spilled registers
3425 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3426 //  stack layout:
3427 //    arg1
3428 //    arg2
3429 //    RETADDR
3430 //    [ new RETADDR
3431 //      move area ]
3432 //    (possible EBP)
3433 //    ESI
3434 //    EDI
3435 //    local1 ..
3436
3437 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3438 /// requirement.
3439 unsigned
3440 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3441                                                SelectionDAG& DAG) const {
3442   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3443   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3444   unsigned StackAlignment = TFI.getStackAlignment();
3445   uint64_t AlignMask = StackAlignment - 1;
3446   int64_t Offset = StackSize;
3447   unsigned SlotSize = RegInfo->getSlotSize();
3448   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3449     // Number smaller than 12 so just add the difference.
3450     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3451   } else {
3452     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3453     Offset = ((~AlignMask) & Offset) + StackAlignment +
3454       (StackAlignment-SlotSize);
3455   }
3456   return Offset;
3457 }
3458
3459 /// Return true if the given stack call argument is already available in the
3460 /// same position (relatively) of the caller's incoming argument stack.
3461 static
3462 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3463                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3464                          const X86InstrInfo *TII) {
3465   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3466   int FI = INT_MAX;
3467   if (Arg.getOpcode() == ISD::CopyFromReg) {
3468     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3469     if (!TargetRegisterInfo::isVirtualRegister(VR))
3470       return false;
3471     MachineInstr *Def = MRI->getVRegDef(VR);
3472     if (!Def)
3473       return false;
3474     if (!Flags.isByVal()) {
3475       if (!TII->isLoadFromStackSlot(Def, FI))
3476         return false;
3477     } else {
3478       unsigned Opcode = Def->getOpcode();
3479       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3480            Opcode == X86::LEA64_32r) &&
3481           Def->getOperand(1).isFI()) {
3482         FI = Def->getOperand(1).getIndex();
3483         Bytes = Flags.getByValSize();
3484       } else
3485         return false;
3486     }
3487   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3488     if (Flags.isByVal())
3489       // ByVal argument is passed in as a pointer but it's now being
3490       // dereferenced. e.g.
3491       // define @foo(%struct.X* %A) {
3492       //   tail call @bar(%struct.X* byval %A)
3493       // }
3494       return false;
3495     SDValue Ptr = Ld->getBasePtr();
3496     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3497     if (!FINode)
3498       return false;
3499     FI = FINode->getIndex();
3500   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3501     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3502     FI = FINode->getIndex();
3503     Bytes = Flags.getByValSize();
3504   } else
3505     return false;
3506
3507   assert(FI != INT_MAX);
3508   if (!MFI->isFixedObjectIndex(FI))
3509     return false;
3510   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3511 }
3512
3513 /// Check whether the call is eligible for tail call optimization. Targets
3514 /// that want to do tail call optimization should implement this function.
3515 bool
3516 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3517                                                      CallingConv::ID CalleeCC,
3518                                                      bool isVarArg,
3519                                                      bool isCalleeStructRet,
3520                                                      bool isCallerStructRet,
3521                                                      Type *RetTy,
3522                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3523                                     const SmallVectorImpl<SDValue> &OutVals,
3524                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3525                                                      SelectionDAG &DAG) const {
3526   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3527     return false;
3528
3529   // If -tailcallopt is specified, make fastcc functions tail-callable.
3530   const MachineFunction &MF = DAG.getMachineFunction();
3531   const Function *CallerF = MF.getFunction();
3532
3533   // If the function return type is x86_fp80 and the callee return type is not,
3534   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3535   // perform a tailcall optimization here.
3536   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3537     return false;
3538
3539   CallingConv::ID CallerCC = CallerF->getCallingConv();
3540   bool CCMatch = CallerCC == CalleeCC;
3541   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3542   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3543
3544   // Win64 functions have extra shadow space for argument homing. Don't do the
3545   // sibcall if the caller and callee have mismatched expectations for this
3546   // space.
3547   if (IsCalleeWin64 != IsCallerWin64)
3548     return false;
3549
3550   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3551     if (IsTailCallConvention(CalleeCC) && CCMatch)
3552       return true;
3553     return false;
3554   }
3555
3556   // Look for obvious safe cases to perform tail call optimization that do not
3557   // require ABI changes. This is what gcc calls sibcall.
3558
3559   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3560   // emit a special epilogue.
3561   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3562   if (RegInfo->needsStackRealignment(MF))
3563     return false;
3564
3565   // Also avoid sibcall optimization if either caller or callee uses struct
3566   // return semantics.
3567   if (isCalleeStructRet || isCallerStructRet)
3568     return false;
3569
3570   // An stdcall/thiscall caller is expected to clean up its arguments; the
3571   // callee isn't going to do that.
3572   // FIXME: this is more restrictive than needed. We could produce a tailcall
3573   // when the stack adjustment matches. For example, with a thiscall that takes
3574   // only one argument.
3575   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3576                    CallerCC == CallingConv::X86_ThisCall))
3577     return false;
3578
3579   // Do not sibcall optimize vararg calls unless all arguments are passed via
3580   // registers.
3581   if (isVarArg && !Outs.empty()) {
3582
3583     // Optimizing for varargs on Win64 is unlikely to be safe without
3584     // additional testing.
3585     if (IsCalleeWin64 || IsCallerWin64)
3586       return false;
3587
3588     SmallVector<CCValAssign, 16> ArgLocs;
3589     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3590                    *DAG.getContext());
3591
3592     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3593     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3594       if (!ArgLocs[i].isRegLoc())
3595         return false;
3596   }
3597
3598   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3599   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3600   // this into a sibcall.
3601   bool Unused = false;
3602   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3603     if (!Ins[i].Used) {
3604       Unused = true;
3605       break;
3606     }
3607   }
3608   if (Unused) {
3609     SmallVector<CCValAssign, 16> RVLocs;
3610     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3611                    *DAG.getContext());
3612     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3613     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3614       CCValAssign &VA = RVLocs[i];
3615       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3616         return false;
3617     }
3618   }
3619
3620   // If the calling conventions do not match, then we'd better make sure the
3621   // results are returned in the same way as what the caller expects.
3622   if (!CCMatch) {
3623     SmallVector<CCValAssign, 16> RVLocs1;
3624     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3625                     *DAG.getContext());
3626     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3627
3628     SmallVector<CCValAssign, 16> RVLocs2;
3629     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3630                     *DAG.getContext());
3631     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3632
3633     if (RVLocs1.size() != RVLocs2.size())
3634       return false;
3635     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3636       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3637         return false;
3638       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3639         return false;
3640       if (RVLocs1[i].isRegLoc()) {
3641         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3642           return false;
3643       } else {
3644         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3645           return false;
3646       }
3647     }
3648   }
3649
3650   // If the callee takes no arguments then go on to check the results of the
3651   // call.
3652   if (!Outs.empty()) {
3653     // Check if stack adjustment is needed. For now, do not do this if any
3654     // argument is passed on the stack.
3655     SmallVector<CCValAssign, 16> ArgLocs;
3656     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3657                    *DAG.getContext());
3658
3659     // Allocate shadow area for Win64
3660     if (IsCalleeWin64)
3661       CCInfo.AllocateStack(32, 8);
3662
3663     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3664     if (CCInfo.getNextStackOffset()) {
3665       MachineFunction &MF = DAG.getMachineFunction();
3666       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3667         return false;
3668
3669       // Check if the arguments are already laid out in the right way as
3670       // the caller's fixed stack objects.
3671       MachineFrameInfo *MFI = MF.getFrameInfo();
3672       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3673       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3674       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3675         CCValAssign &VA = ArgLocs[i];
3676         SDValue Arg = OutVals[i];
3677         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3678         if (VA.getLocInfo() == CCValAssign::Indirect)
3679           return false;
3680         if (!VA.isRegLoc()) {
3681           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3682                                    MFI, MRI, TII))
3683             return false;
3684         }
3685       }
3686     }
3687
3688     // If the tailcall address may be in a register, then make sure it's
3689     // possible to register allocate for it. In 32-bit, the call address can
3690     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3691     // callee-saved registers are restored. These happen to be the same
3692     // registers used to pass 'inreg' arguments so watch out for those.
3693     if (!Subtarget->is64Bit() &&
3694         ((!isa<GlobalAddressSDNode>(Callee) &&
3695           !isa<ExternalSymbolSDNode>(Callee)) ||
3696          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3697       unsigned NumInRegs = 0;
3698       // In PIC we need an extra register to formulate the address computation
3699       // for the callee.
3700       unsigned MaxInRegs =
3701         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3702
3703       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3704         CCValAssign &VA = ArgLocs[i];
3705         if (!VA.isRegLoc())
3706           continue;
3707         unsigned Reg = VA.getLocReg();
3708         switch (Reg) {
3709         default: break;
3710         case X86::EAX: case X86::EDX: case X86::ECX:
3711           if (++NumInRegs == MaxInRegs)
3712             return false;
3713           break;
3714         }
3715       }
3716     }
3717   }
3718
3719   return true;
3720 }
3721
3722 FastISel *
3723 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3724                                   const TargetLibraryInfo *libInfo) const {
3725   return X86::createFastISel(funcInfo, libInfo);
3726 }
3727
3728 //===----------------------------------------------------------------------===//
3729 //                           Other Lowering Hooks
3730 //===----------------------------------------------------------------------===//
3731
3732 static bool MayFoldLoad(SDValue Op) {
3733   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3734 }
3735
3736 static bool MayFoldIntoStore(SDValue Op) {
3737   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3738 }
3739
3740 static bool isTargetShuffle(unsigned Opcode) {
3741   switch(Opcode) {
3742   default: return false;
3743   case X86ISD::BLENDI:
3744   case X86ISD::PSHUFB:
3745   case X86ISD::PSHUFD:
3746   case X86ISD::PSHUFHW:
3747   case X86ISD::PSHUFLW:
3748   case X86ISD::SHUFP:
3749   case X86ISD::PALIGNR:
3750   case X86ISD::MOVLHPS:
3751   case X86ISD::MOVLHPD:
3752   case X86ISD::MOVHLPS:
3753   case X86ISD::MOVLPS:
3754   case X86ISD::MOVLPD:
3755   case X86ISD::MOVSHDUP:
3756   case X86ISD::MOVSLDUP:
3757   case X86ISD::MOVDDUP:
3758   case X86ISD::MOVSS:
3759   case X86ISD::MOVSD:
3760   case X86ISD::UNPCKL:
3761   case X86ISD::UNPCKH:
3762   case X86ISD::VPERMILPI:
3763   case X86ISD::VPERM2X128:
3764   case X86ISD::VPERMI:
3765     return true;
3766   }
3767 }
3768
3769 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3770                                     SDValue V1, unsigned TargetMask,
3771                                     SelectionDAG &DAG) {
3772   switch(Opc) {
3773   default: llvm_unreachable("Unknown x86 shuffle node");
3774   case X86ISD::PSHUFD:
3775   case X86ISD::PSHUFHW:
3776   case X86ISD::PSHUFLW:
3777   case X86ISD::VPERMILPI:
3778   case X86ISD::VPERMI:
3779     return DAG.getNode(Opc, dl, VT, V1,
3780                        DAG.getConstant(TargetMask, dl, MVT::i8));
3781   }
3782 }
3783
3784 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3785                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3786   switch(Opc) {
3787   default: llvm_unreachable("Unknown x86 shuffle node");
3788   case X86ISD::MOVLHPS:
3789   case X86ISD::MOVLHPD:
3790   case X86ISD::MOVHLPS:
3791   case X86ISD::MOVLPS:
3792   case X86ISD::MOVLPD:
3793   case X86ISD::MOVSS:
3794   case X86ISD::MOVSD:
3795   case X86ISD::UNPCKL:
3796   case X86ISD::UNPCKH:
3797     return DAG.getNode(Opc, dl, VT, V1, V2);
3798   }
3799 }
3800
3801 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3802   MachineFunction &MF = DAG.getMachineFunction();
3803   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3804   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3805   int ReturnAddrIndex = FuncInfo->getRAIndex();
3806
3807   if (ReturnAddrIndex == 0) {
3808     // Set up a frame object for the return address.
3809     unsigned SlotSize = RegInfo->getSlotSize();
3810     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3811                                                            -(int64_t)SlotSize,
3812                                                            false);
3813     FuncInfo->setRAIndex(ReturnAddrIndex);
3814   }
3815
3816   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3817 }
3818
3819 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3820                                        bool hasSymbolicDisplacement) {
3821   // Offset should fit into 32 bit immediate field.
3822   if (!isInt<32>(Offset))
3823     return false;
3824
3825   // If we don't have a symbolic displacement - we don't have any extra
3826   // restrictions.
3827   if (!hasSymbolicDisplacement)
3828     return true;
3829
3830   // FIXME: Some tweaks might be needed for medium code model.
3831   if (M != CodeModel::Small && M != CodeModel::Kernel)
3832     return false;
3833
3834   // For small code model we assume that latest object is 16MB before end of 31
3835   // bits boundary. We may also accept pretty large negative constants knowing
3836   // that all objects are in the positive half of address space.
3837   if (M == CodeModel::Small && Offset < 16*1024*1024)
3838     return true;
3839
3840   // For kernel code model we know that all object resist in the negative half
3841   // of 32bits address space. We may not accept negative offsets, since they may
3842   // be just off and we may accept pretty large positive ones.
3843   if (M == CodeModel::Kernel && Offset >= 0)
3844     return true;
3845
3846   return false;
3847 }
3848
3849 /// Determines whether the callee is required to pop its own arguments.
3850 /// Callee pop is necessary to support tail calls.
3851 bool X86::isCalleePop(CallingConv::ID CallingConv,
3852                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3853   switch (CallingConv) {
3854   default:
3855     return false;
3856   case CallingConv::X86_StdCall:
3857   case CallingConv::X86_FastCall:
3858   case CallingConv::X86_ThisCall:
3859     return !is64Bit;
3860   case CallingConv::Fast:
3861   case CallingConv::GHC:
3862   case CallingConv::HiPE:
3863     if (IsVarArg)
3864       return false;
3865     return TailCallOpt;
3866   }
3867 }
3868
3869 /// \brief Return true if the condition is an unsigned comparison operation.
3870 static bool isX86CCUnsigned(unsigned X86CC) {
3871   switch (X86CC) {
3872   default: llvm_unreachable("Invalid integer condition!");
3873   case X86::COND_E:     return true;
3874   case X86::COND_G:     return false;
3875   case X86::COND_GE:    return false;
3876   case X86::COND_L:     return false;
3877   case X86::COND_LE:    return false;
3878   case X86::COND_NE:    return true;
3879   case X86::COND_B:     return true;
3880   case X86::COND_A:     return true;
3881   case X86::COND_BE:    return true;
3882   case X86::COND_AE:    return true;
3883   }
3884   llvm_unreachable("covered switch fell through?!");
3885 }
3886
3887 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3888 /// condition code, returning the condition code and the LHS/RHS of the
3889 /// comparison to make.
3890 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3891                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3892   if (!isFP) {
3893     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3894       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3895         // X > -1   -> X == 0, jump !sign.
3896         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3897         return X86::COND_NS;
3898       }
3899       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3900         // X < 0   -> X == 0, jump on sign.
3901         return X86::COND_S;
3902       }
3903       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3904         // X < 1   -> X <= 0
3905         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3906         return X86::COND_LE;
3907       }
3908     }
3909
3910     switch (SetCCOpcode) {
3911     default: llvm_unreachable("Invalid integer condition!");
3912     case ISD::SETEQ:  return X86::COND_E;
3913     case ISD::SETGT:  return X86::COND_G;
3914     case ISD::SETGE:  return X86::COND_GE;
3915     case ISD::SETLT:  return X86::COND_L;
3916     case ISD::SETLE:  return X86::COND_LE;
3917     case ISD::SETNE:  return X86::COND_NE;
3918     case ISD::SETULT: return X86::COND_B;
3919     case ISD::SETUGT: return X86::COND_A;
3920     case ISD::SETULE: return X86::COND_BE;
3921     case ISD::SETUGE: return X86::COND_AE;
3922     }
3923   }
3924
3925   // First determine if it is required or is profitable to flip the operands.
3926
3927   // If LHS is a foldable load, but RHS is not, flip the condition.
3928   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3929       !ISD::isNON_EXTLoad(RHS.getNode())) {
3930     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3931     std::swap(LHS, RHS);
3932   }
3933
3934   switch (SetCCOpcode) {
3935   default: break;
3936   case ISD::SETOLT:
3937   case ISD::SETOLE:
3938   case ISD::SETUGT:
3939   case ISD::SETUGE:
3940     std::swap(LHS, RHS);
3941     break;
3942   }
3943
3944   // On a floating point condition, the flags are set as follows:
3945   // ZF  PF  CF   op
3946   //  0 | 0 | 0 | X > Y
3947   //  0 | 0 | 1 | X < Y
3948   //  1 | 0 | 0 | X == Y
3949   //  1 | 1 | 1 | unordered
3950   switch (SetCCOpcode) {
3951   default: llvm_unreachable("Condcode should be pre-legalized away");
3952   case ISD::SETUEQ:
3953   case ISD::SETEQ:   return X86::COND_E;
3954   case ISD::SETOLT:              // flipped
3955   case ISD::SETOGT:
3956   case ISD::SETGT:   return X86::COND_A;
3957   case ISD::SETOLE:              // flipped
3958   case ISD::SETOGE:
3959   case ISD::SETGE:   return X86::COND_AE;
3960   case ISD::SETUGT:              // flipped
3961   case ISD::SETULT:
3962   case ISD::SETLT:   return X86::COND_B;
3963   case ISD::SETUGE:              // flipped
3964   case ISD::SETULE:
3965   case ISD::SETLE:   return X86::COND_BE;
3966   case ISD::SETONE:
3967   case ISD::SETNE:   return X86::COND_NE;
3968   case ISD::SETUO:   return X86::COND_P;
3969   case ISD::SETO:    return X86::COND_NP;
3970   case ISD::SETOEQ:
3971   case ISD::SETUNE:  return X86::COND_INVALID;
3972   }
3973 }
3974
3975 /// Is there a floating point cmov for the specific X86 condition code?
3976 /// Current x86 isa includes the following FP cmov instructions:
3977 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3978 static bool hasFPCMov(unsigned X86CC) {
3979   switch (X86CC) {
3980   default:
3981     return false;
3982   case X86::COND_B:
3983   case X86::COND_BE:
3984   case X86::COND_E:
3985   case X86::COND_P:
3986   case X86::COND_A:
3987   case X86::COND_AE:
3988   case X86::COND_NE:
3989   case X86::COND_NP:
3990     return true;
3991   }
3992 }
3993
3994 /// Returns true if the target can instruction select the
3995 /// specified FP immediate natively. If false, the legalizer will
3996 /// materialize the FP immediate as a load from a constant pool.
3997 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3998   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3999     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4000       return true;
4001   }
4002   return false;
4003 }
4004
4005 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4006                                               ISD::LoadExtType ExtTy,
4007                                               EVT NewVT) const {
4008   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4009   // relocation target a movq or addq instruction: don't let the load shrink.
4010   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4011   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4012     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4013       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4014   return true;
4015 }
4016
4017 /// \brief Returns true if it is beneficial to convert a load of a constant
4018 /// to just the constant itself.
4019 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4020                                                           Type *Ty) const {
4021   assert(Ty->isIntegerTy());
4022
4023   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4024   if (BitSize == 0 || BitSize > 64)
4025     return false;
4026   return true;
4027 }
4028
4029 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4030                                                 unsigned Index) const {
4031   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4032     return false;
4033
4034   return (Index == 0 || Index == ResVT.getVectorNumElements());
4035 }
4036
4037 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4038   // Speculate cttz only if we can directly use TZCNT.
4039   return Subtarget->hasBMI();
4040 }
4041
4042 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4043   // Speculate ctlz only if we can directly use LZCNT.
4044   return Subtarget->hasLZCNT();
4045 }
4046
4047 /// Return true if every element in Mask, beginning
4048 /// from position Pos and ending in Pos+Size is undef.
4049 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4050   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4051     if (0 <= Mask[i])
4052       return false;
4053   return true;
4054 }
4055
4056 /// Return true if Val is undef or if its value falls within the
4057 /// specified range (L, H].
4058 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4059   return (Val < 0) || (Val >= Low && Val < Hi);
4060 }
4061
4062 /// Val is either less than zero (undef) or equal to the specified value.
4063 static bool isUndefOrEqual(int Val, int CmpVal) {
4064   return (Val < 0 || Val == CmpVal);
4065 }
4066
4067 /// Return true if every element in Mask, beginning
4068 /// from position Pos and ending in Pos+Size, falls within the specified
4069 /// sequential range (Low, Low+Size]. or is undef.
4070 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4071                                        unsigned Pos, unsigned Size, int Low) {
4072   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4073     if (!isUndefOrEqual(Mask[i], Low))
4074       return false;
4075   return true;
4076 }
4077
4078 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4079 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4080 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4081   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4082   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4083     return false;
4084
4085   // The index should be aligned on a vecWidth-bit boundary.
4086   uint64_t Index =
4087     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4088
4089   MVT VT = N->getSimpleValueType(0);
4090   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4091   bool Result = (Index * ElSize) % vecWidth == 0;
4092
4093   return Result;
4094 }
4095
4096 /// Return true if the specified INSERT_SUBVECTOR
4097 /// operand specifies a subvector insert that is suitable for input to
4098 /// insertion of 128 or 256-bit subvectors
4099 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4100   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4101   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4102     return false;
4103   // The index should be aligned on a vecWidth-bit boundary.
4104   uint64_t Index =
4105     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4106
4107   MVT VT = N->getSimpleValueType(0);
4108   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4109   bool Result = (Index * ElSize) % vecWidth == 0;
4110
4111   return Result;
4112 }
4113
4114 bool X86::isVINSERT128Index(SDNode *N) {
4115   return isVINSERTIndex(N, 128);
4116 }
4117
4118 bool X86::isVINSERT256Index(SDNode *N) {
4119   return isVINSERTIndex(N, 256);
4120 }
4121
4122 bool X86::isVEXTRACT128Index(SDNode *N) {
4123   return isVEXTRACTIndex(N, 128);
4124 }
4125
4126 bool X86::isVEXTRACT256Index(SDNode *N) {
4127   return isVEXTRACTIndex(N, 256);
4128 }
4129
4130 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4131   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4132   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4133     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4134
4135   uint64_t Index =
4136     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4137
4138   MVT VecVT = N->getOperand(0).getSimpleValueType();
4139   MVT ElVT = VecVT.getVectorElementType();
4140
4141   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4142   return Index / NumElemsPerChunk;
4143 }
4144
4145 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4146   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4147   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4148     llvm_unreachable("Illegal insert subvector for VINSERT");
4149
4150   uint64_t Index =
4151     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4152
4153   MVT VecVT = N->getSimpleValueType(0);
4154   MVT ElVT = VecVT.getVectorElementType();
4155
4156   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4157   return Index / NumElemsPerChunk;
4158 }
4159
4160 /// Return the appropriate immediate to extract the specified
4161 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4162 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4163   return getExtractVEXTRACTImmediate(N, 128);
4164 }
4165
4166 /// Return the appropriate immediate to extract the specified
4167 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4168 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4169   return getExtractVEXTRACTImmediate(N, 256);
4170 }
4171
4172 /// Return the appropriate immediate to insert at the specified
4173 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4174 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4175   return getInsertVINSERTImmediate(N, 128);
4176 }
4177
4178 /// Return the appropriate immediate to insert at the specified
4179 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4180 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4181   return getInsertVINSERTImmediate(N, 256);
4182 }
4183
4184 /// Returns true if Elt is a constant integer zero
4185 static bool isZero(SDValue V) {
4186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4187   return C && C->isNullValue();
4188 }
4189
4190 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4191 bool X86::isZeroNode(SDValue Elt) {
4192   if (isZero(Elt))
4193     return true;
4194   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4195     return CFP->getValueAPF().isPosZero();
4196   return false;
4197 }
4198
4199 /// Returns a vector of specified type with all zero elements.
4200 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4201                              SelectionDAG &DAG, SDLoc dl) {
4202   assert(VT.isVector() && "Expected a vector type");
4203
4204   // Always build SSE zero vectors as <4 x i32> bitcasted
4205   // to their dest type. This ensures they get CSE'd.
4206   SDValue Vec;
4207   if (VT.is128BitVector()) {  // SSE
4208     if (Subtarget->hasSSE2()) {  // SSE2
4209       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4210       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4211     } else { // SSE1
4212       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4213       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4214     }
4215   } else if (VT.is256BitVector()) { // AVX
4216     if (Subtarget->hasInt256()) { // AVX2
4217       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4218       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4219       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4220     } else {
4221       // 256-bit logic and arithmetic instructions in AVX are all
4222       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4223       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4224       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4225       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4226     }
4227   } else if (VT.is512BitVector()) { // AVX-512
4228       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4229       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4230                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4232   } else if (VT.getScalarType() == MVT::i1) {
4233
4234     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4235             && "Unexpected vector type");
4236     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4237             && "Unexpected vector type");
4238     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4239     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4240     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4241   } else
4242     llvm_unreachable("Unexpected vector type");
4243
4244   return DAG.getBitcast(VT, Vec);
4245 }
4246
4247 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4248                                 SelectionDAG &DAG, SDLoc dl,
4249                                 unsigned vectorWidth) {
4250   assert((vectorWidth == 128 || vectorWidth == 256) &&
4251          "Unsupported vector width");
4252   EVT VT = Vec.getValueType();
4253   EVT ElVT = VT.getVectorElementType();
4254   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4255   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4256                                   VT.getVectorNumElements()/Factor);
4257
4258   // Extract from UNDEF is UNDEF.
4259   if (Vec.getOpcode() == ISD::UNDEF)
4260     return DAG.getUNDEF(ResultVT);
4261
4262   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4263   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4264
4265   // This is the index of the first element of the vectorWidth-bit chunk
4266   // we want.
4267   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4268                                * ElemsPerChunk);
4269
4270   // If the input is a buildvector just emit a smaller one.
4271   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4272     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4273                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4274                                     ElemsPerChunk));
4275
4276   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4277   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4278 }
4279
4280 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4281 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4282 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4283 /// instructions or a simple subregister reference. Idx is an index in the
4284 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4285 /// lowering EXTRACT_VECTOR_ELT operations easier.
4286 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4287                                    SelectionDAG &DAG, SDLoc dl) {
4288   assert((Vec.getValueType().is256BitVector() ||
4289           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4290   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4291 }
4292
4293 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4294 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4295                                    SelectionDAG &DAG, SDLoc dl) {
4296   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4297   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4298 }
4299
4300 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4301                                unsigned IdxVal, SelectionDAG &DAG,
4302                                SDLoc dl, unsigned vectorWidth) {
4303   assert((vectorWidth == 128 || vectorWidth == 256) &&
4304          "Unsupported vector width");
4305   // Inserting UNDEF is Result
4306   if (Vec.getOpcode() == ISD::UNDEF)
4307     return Result;
4308   EVT VT = Vec.getValueType();
4309   EVT ElVT = VT.getVectorElementType();
4310   EVT ResultVT = Result.getValueType();
4311
4312   // Insert the relevant vectorWidth bits.
4313   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4314
4315   // This is the index of the first element of the vectorWidth-bit chunk
4316   // we want.
4317   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4318                                * ElemsPerChunk);
4319
4320   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4321   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4322 }
4323
4324 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4325 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4326 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4327 /// simple superregister reference.  Idx is an index in the 128 bits
4328 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4329 /// lowering INSERT_VECTOR_ELT operations easier.
4330 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4331                                   SelectionDAG &DAG, SDLoc dl) {
4332   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4333
4334   // For insertion into the zero index (low half) of a 256-bit vector, it is
4335   // more efficient to generate a blend with immediate instead of an insert*128.
4336   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4337   // extend the subvector to the size of the result vector. Make sure that
4338   // we are not recursing on that node by checking for undef here.
4339   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4340       Result.getOpcode() != ISD::UNDEF) {
4341     EVT ResultVT = Result.getValueType();
4342     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4343     SDValue Undef = DAG.getUNDEF(ResultVT);
4344     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4345                                  Vec, ZeroIndex);
4346
4347     // The blend instruction, and therefore its mask, depend on the data type.
4348     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4349     if (ScalarType.isFloatingPoint()) {
4350       // Choose either vblendps (float) or vblendpd (double).
4351       unsigned ScalarSize = ScalarType.getSizeInBits();
4352       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4353       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4354       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4355       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4356     }
4357
4358     const X86Subtarget &Subtarget =
4359     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4360
4361     // AVX2 is needed for 256-bit integer blend support.
4362     // Integers must be cast to 32-bit because there is only vpblendd;
4363     // vpblendw can't be used for this because it has a handicapped mask.
4364
4365     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4366     // is still more efficient than using the wrong domain vinsertf128 that
4367     // will be created by InsertSubVector().
4368     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4369
4370     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4371     Vec256 = DAG.getBitcast(CastVT, Vec256);
4372     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4373     return DAG.getBitcast(ResultVT, Vec256);
4374   }
4375
4376   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4377 }
4378
4379 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4380                                   SelectionDAG &DAG, SDLoc dl) {
4381   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4382   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4383 }
4384
4385 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4386 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4387 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4388 /// large BUILD_VECTORS.
4389 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4390                                    unsigned NumElems, SelectionDAG &DAG,
4391                                    SDLoc dl) {
4392   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4393   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4394 }
4395
4396 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4397                                    unsigned NumElems, SelectionDAG &DAG,
4398                                    SDLoc dl) {
4399   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4400   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4401 }
4402
4403 /// Returns a vector of specified type with all bits set.
4404 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4405 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4406 /// Then bitcast to their original type, ensuring they get CSE'd.
4407 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4408                              SDLoc dl) {
4409   assert(VT.isVector() && "Expected a vector type");
4410
4411   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4412   SDValue Vec;
4413   if (VT.is256BitVector()) {
4414     if (HasInt256) { // AVX2
4415       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4416       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4417     } else { // AVX
4418       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4419       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4420     }
4421   } else if (VT.is128BitVector()) {
4422     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4423   } else
4424     llvm_unreachable("Unexpected vector type");
4425
4426   return DAG.getBitcast(VT, Vec);
4427 }
4428
4429 /// Returns a vector_shuffle node for an unpackl operation.
4430 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4431                           SDValue V2) {
4432   unsigned NumElems = VT.getVectorNumElements();
4433   SmallVector<int, 8> Mask;
4434   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4435     Mask.push_back(i);
4436     Mask.push_back(i + NumElems);
4437   }
4438   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4439 }
4440
4441 /// Returns a vector_shuffle node for an unpackh operation.
4442 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4443                           SDValue V2) {
4444   unsigned NumElems = VT.getVectorNumElements();
4445   SmallVector<int, 8> Mask;
4446   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4447     Mask.push_back(i + Half);
4448     Mask.push_back(i + NumElems + Half);
4449   }
4450   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451 }
4452
4453 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4454 /// This produces a shuffle where the low element of V2 is swizzled into the
4455 /// zero/undef vector, landing at element Idx.
4456 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4457 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4458                                            bool IsZero,
4459                                            const X86Subtarget *Subtarget,
4460                                            SelectionDAG &DAG) {
4461   MVT VT = V2.getSimpleValueType();
4462   SDValue V1 = IsZero
4463     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4464   unsigned NumElems = VT.getVectorNumElements();
4465   SmallVector<int, 16> MaskVec;
4466   for (unsigned i = 0; i != NumElems; ++i)
4467     // If this is the insertion idx, put the low elt of V2 here.
4468     MaskVec.push_back(i == Idx ? NumElems : i);
4469   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4470 }
4471
4472 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4473 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4474 /// uses one source. Note that this will set IsUnary for shuffles which use a
4475 /// single input multiple times, and in those cases it will
4476 /// adjust the mask to only have indices within that single input.
4477 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4478 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4479                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4480   unsigned NumElems = VT.getVectorNumElements();
4481   SDValue ImmN;
4482
4483   IsUnary = false;
4484   bool IsFakeUnary = false;
4485   switch(N->getOpcode()) {
4486   case X86ISD::BLENDI:
4487     ImmN = N->getOperand(N->getNumOperands()-1);
4488     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4489     break;
4490   case X86ISD::SHUFP:
4491     ImmN = N->getOperand(N->getNumOperands()-1);
4492     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4493     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4494     break;
4495   case X86ISD::UNPCKH:
4496     DecodeUNPCKHMask(VT, Mask);
4497     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4498     break;
4499   case X86ISD::UNPCKL:
4500     DecodeUNPCKLMask(VT, Mask);
4501     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4502     break;
4503   case X86ISD::MOVHLPS:
4504     DecodeMOVHLPSMask(NumElems, Mask);
4505     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506     break;
4507   case X86ISD::MOVLHPS:
4508     DecodeMOVLHPSMask(NumElems, Mask);
4509     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4510     break;
4511   case X86ISD::PALIGNR:
4512     ImmN = N->getOperand(N->getNumOperands()-1);
4513     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514     break;
4515   case X86ISD::PSHUFD:
4516   case X86ISD::VPERMILPI:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     IsUnary = true;
4520     break;
4521   case X86ISD::PSHUFHW:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::PSHUFLW:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     IsUnary = true;
4530     break;
4531   case X86ISD::PSHUFB: {
4532     IsUnary = true;
4533     SDValue MaskNode = N->getOperand(1);
4534     while (MaskNode->getOpcode() == ISD::BITCAST)
4535       MaskNode = MaskNode->getOperand(0);
4536
4537     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4538       // If we have a build-vector, then things are easy.
4539       EVT VT = MaskNode.getValueType();
4540       assert(VT.isVector() &&
4541              "Can't produce a non-vector with a build_vector!");
4542       if (!VT.isInteger())
4543         return false;
4544
4545       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4546
4547       SmallVector<uint64_t, 32> RawMask;
4548       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4549         SDValue Op = MaskNode->getOperand(i);
4550         if (Op->getOpcode() == ISD::UNDEF) {
4551           RawMask.push_back((uint64_t)SM_SentinelUndef);
4552           continue;
4553         }
4554         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4555         if (!CN)
4556           return false;
4557         APInt MaskElement = CN->getAPIntValue();
4558
4559         // We now have to decode the element which could be any integer size and
4560         // extract each byte of it.
4561         for (int j = 0; j < NumBytesPerElement; ++j) {
4562           // Note that this is x86 and so always little endian: the low byte is
4563           // the first byte of the mask.
4564           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4565           MaskElement = MaskElement.lshr(8);
4566         }
4567       }
4568       DecodePSHUFBMask(RawMask, Mask);
4569       break;
4570     }
4571
4572     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4573     if (!MaskLoad)
4574       return false;
4575
4576     SDValue Ptr = MaskLoad->getBasePtr();
4577     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4578         Ptr->getOpcode() == X86ISD::WrapperRIP)
4579       Ptr = Ptr->getOperand(0);
4580
4581     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4582     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4583       return false;
4584
4585     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4586       DecodePSHUFBMask(C, Mask);
4587       if (Mask.empty())
4588         return false;
4589       break;
4590     }
4591
4592     return false;
4593   }
4594   case X86ISD::VPERMI:
4595     ImmN = N->getOperand(N->getNumOperands()-1);
4596     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4597     IsUnary = true;
4598     break;
4599   case X86ISD::MOVSS:
4600   case X86ISD::MOVSD:
4601     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4602     break;
4603   case X86ISD::VPERM2X128:
4604     ImmN = N->getOperand(N->getNumOperands()-1);
4605     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606     if (Mask.empty()) return false;
4607     // Mask only contains negative index if an element is zero.
4608     if (std::any_of(Mask.begin(), Mask.end(),
4609                     [](int M){ return M == SM_SentinelZero; }))
4610       return false;
4611     break;
4612   case X86ISD::MOVSLDUP:
4613     DecodeMOVSLDUPMask(VT, Mask);
4614     IsUnary = true;
4615     break;
4616   case X86ISD::MOVSHDUP:
4617     DecodeMOVSHDUPMask(VT, Mask);
4618     IsUnary = true;
4619     break;
4620   case X86ISD::MOVDDUP:
4621     DecodeMOVDDUPMask(VT, Mask);
4622     IsUnary = true;
4623     break;
4624   case X86ISD::MOVLHPD:
4625   case X86ISD::MOVLPD:
4626   case X86ISD::MOVLPS:
4627     // Not yet implemented
4628     return false;
4629   default: llvm_unreachable("unknown target shuffle node");
4630   }
4631
4632   // If we have a fake unary shuffle, the shuffle mask is spread across two
4633   // inputs that are actually the same node. Re-map the mask to always point
4634   // into the first input.
4635   if (IsFakeUnary)
4636     for (int &M : Mask)
4637       if (M >= (int)Mask.size())
4638         M -= Mask.size();
4639
4640   return true;
4641 }
4642
4643 /// Returns the scalar element that will make up the ith
4644 /// element of the result of the vector shuffle.
4645 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4646                                    unsigned Depth) {
4647   if (Depth == 6)
4648     return SDValue();  // Limit search depth.
4649
4650   SDValue V = SDValue(N, 0);
4651   EVT VT = V.getValueType();
4652   unsigned Opcode = V.getOpcode();
4653
4654   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4655   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4656     int Elt = SV->getMaskElt(Index);
4657
4658     if (Elt < 0)
4659       return DAG.getUNDEF(VT.getVectorElementType());
4660
4661     unsigned NumElems = VT.getVectorNumElements();
4662     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4663                                          : SV->getOperand(1);
4664     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4665   }
4666
4667   // Recurse into target specific vector shuffles to find scalars.
4668   if (isTargetShuffle(Opcode)) {
4669     MVT ShufVT = V.getSimpleValueType();
4670     unsigned NumElems = ShufVT.getVectorNumElements();
4671     SmallVector<int, 16> ShuffleMask;
4672     bool IsUnary;
4673
4674     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4675       return SDValue();
4676
4677     int Elt = ShuffleMask[Index];
4678     if (Elt < 0)
4679       return DAG.getUNDEF(ShufVT.getVectorElementType());
4680
4681     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4682                                          : N->getOperand(1);
4683     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4684                                Depth+1);
4685   }
4686
4687   // Actual nodes that may contain scalar elements
4688   if (Opcode == ISD::BITCAST) {
4689     V = V.getOperand(0);
4690     EVT SrcVT = V.getValueType();
4691     unsigned NumElems = VT.getVectorNumElements();
4692
4693     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4694       return SDValue();
4695   }
4696
4697   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4698     return (Index == 0) ? V.getOperand(0)
4699                         : DAG.getUNDEF(VT.getVectorElementType());
4700
4701   if (V.getOpcode() == ISD::BUILD_VECTOR)
4702     return V.getOperand(Index);
4703
4704   return SDValue();
4705 }
4706
4707 /// Custom lower build_vector of v16i8.
4708 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4709                                        unsigned NumNonZero, unsigned NumZero,
4710                                        SelectionDAG &DAG,
4711                                        const X86Subtarget* Subtarget,
4712                                        const TargetLowering &TLI) {
4713   if (NumNonZero > 8)
4714     return SDValue();
4715
4716   SDLoc dl(Op);
4717   SDValue V;
4718   bool First = true;
4719
4720   // SSE4.1 - use PINSRB to insert each byte directly.
4721   if (Subtarget->hasSSE41()) {
4722     for (unsigned i = 0; i < 16; ++i) {
4723       bool isNonZero = (NonZeros & (1 << i)) != 0;
4724       if (isNonZero) {
4725         if (First) {
4726           if (NumZero)
4727             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4728           else
4729             V = DAG.getUNDEF(MVT::v16i8);
4730           First = false;
4731         }
4732         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4733                         MVT::v16i8, V, Op.getOperand(i),
4734                         DAG.getIntPtrConstant(i, dl));
4735       }
4736     }
4737
4738     return V;
4739   }
4740
4741   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4742   for (unsigned i = 0; i < 16; ++i) {
4743     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4744     if (ThisIsNonZero && First) {
4745       if (NumZero)
4746         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4747       else
4748         V = DAG.getUNDEF(MVT::v8i16);
4749       First = false;
4750     }
4751
4752     if ((i & 1) != 0) {
4753       SDValue ThisElt, LastElt;
4754       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4755       if (LastIsNonZero) {
4756         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4757                               MVT::i16, Op.getOperand(i-1));
4758       }
4759       if (ThisIsNonZero) {
4760         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4761         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4762                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4763         if (LastIsNonZero)
4764           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4765       } else
4766         ThisElt = LastElt;
4767
4768       if (ThisElt.getNode())
4769         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4770                         DAG.getIntPtrConstant(i/2, dl));
4771     }
4772   }
4773
4774   return DAG.getBitcast(MVT::v16i8, V);
4775 }
4776
4777 /// Custom lower build_vector of v8i16.
4778 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4779                                      unsigned NumNonZero, unsigned NumZero,
4780                                      SelectionDAG &DAG,
4781                                      const X86Subtarget* Subtarget,
4782                                      const TargetLowering &TLI) {
4783   if (NumNonZero > 4)
4784     return SDValue();
4785
4786   SDLoc dl(Op);
4787   SDValue V;
4788   bool First = true;
4789   for (unsigned i = 0; i < 8; ++i) {
4790     bool isNonZero = (NonZeros & (1 << i)) != 0;
4791     if (isNonZero) {
4792       if (First) {
4793         if (NumZero)
4794           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4795         else
4796           V = DAG.getUNDEF(MVT::v8i16);
4797         First = false;
4798       }
4799       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4800                       MVT::v8i16, V, Op.getOperand(i),
4801                       DAG.getIntPtrConstant(i, dl));
4802     }
4803   }
4804
4805   return V;
4806 }
4807
4808 /// Custom lower build_vector of v4i32 or v4f32.
4809 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4810                                      const X86Subtarget *Subtarget,
4811                                      const TargetLowering &TLI) {
4812   // Find all zeroable elements.
4813   std::bitset<4> Zeroable;
4814   for (int i=0; i < 4; ++i) {
4815     SDValue Elt = Op->getOperand(i);
4816     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4817   }
4818   assert(Zeroable.size() - Zeroable.count() > 1 &&
4819          "We expect at least two non-zero elements!");
4820
4821   // We only know how to deal with build_vector nodes where elements are either
4822   // zeroable or extract_vector_elt with constant index.
4823   SDValue FirstNonZero;
4824   unsigned FirstNonZeroIdx;
4825   for (unsigned i=0; i < 4; ++i) {
4826     if (Zeroable[i])
4827       continue;
4828     SDValue Elt = Op->getOperand(i);
4829     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4830         !isa<ConstantSDNode>(Elt.getOperand(1)))
4831       return SDValue();
4832     // Make sure that this node is extracting from a 128-bit vector.
4833     MVT VT = Elt.getOperand(0).getSimpleValueType();
4834     if (!VT.is128BitVector())
4835       return SDValue();
4836     if (!FirstNonZero.getNode()) {
4837       FirstNonZero = Elt;
4838       FirstNonZeroIdx = i;
4839     }
4840   }
4841
4842   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4843   SDValue V1 = FirstNonZero.getOperand(0);
4844   MVT VT = V1.getSimpleValueType();
4845
4846   // See if this build_vector can be lowered as a blend with zero.
4847   SDValue Elt;
4848   unsigned EltMaskIdx, EltIdx;
4849   int Mask[4];
4850   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4851     if (Zeroable[EltIdx]) {
4852       // The zero vector will be on the right hand side.
4853       Mask[EltIdx] = EltIdx+4;
4854       continue;
4855     }
4856
4857     Elt = Op->getOperand(EltIdx);
4858     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4859     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4860     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4861       break;
4862     Mask[EltIdx] = EltIdx;
4863   }
4864
4865   if (EltIdx == 4) {
4866     // Let the shuffle legalizer deal with blend operations.
4867     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4868     if (V1.getSimpleValueType() != VT)
4869       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4870     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4871   }
4872
4873   // See if we can lower this build_vector to a INSERTPS.
4874   if (!Subtarget->hasSSE41())
4875     return SDValue();
4876
4877   SDValue V2 = Elt.getOperand(0);
4878   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4879     V1 = SDValue();
4880
4881   bool CanFold = true;
4882   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4883     if (Zeroable[i])
4884       continue;
4885
4886     SDValue Current = Op->getOperand(i);
4887     SDValue SrcVector = Current->getOperand(0);
4888     if (!V1.getNode())
4889       V1 = SrcVector;
4890     CanFold = SrcVector == V1 &&
4891       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4892   }
4893
4894   if (!CanFold)
4895     return SDValue();
4896
4897   assert(V1.getNode() && "Expected at least two non-zero elements!");
4898   if (V1.getSimpleValueType() != MVT::v4f32)
4899     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4900   if (V2.getSimpleValueType() != MVT::v4f32)
4901     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4902
4903   // Ok, we can emit an INSERTPS instruction.
4904   unsigned ZMask = Zeroable.to_ulong();
4905
4906   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4907   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4908   SDLoc DL(Op);
4909   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4910                                DAG.getIntPtrConstant(InsertPSMask, DL));
4911   return DAG.getBitcast(VT, Result);
4912 }
4913
4914 /// Return a vector logical shift node.
4915 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4916                          unsigned NumBits, SelectionDAG &DAG,
4917                          const TargetLowering &TLI, SDLoc dl) {
4918   assert(VT.is128BitVector() && "Unknown type for VShift");
4919   MVT ShVT = MVT::v2i64;
4920   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4921   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4922   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4923   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4924   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4925   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4926 }
4927
4928 static SDValue
4929 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4930
4931   // Check if the scalar load can be widened into a vector load. And if
4932   // the address is "base + cst" see if the cst can be "absorbed" into
4933   // the shuffle mask.
4934   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4935     SDValue Ptr = LD->getBasePtr();
4936     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4937       return SDValue();
4938     EVT PVT = LD->getValueType(0);
4939     if (PVT != MVT::i32 && PVT != MVT::f32)
4940       return SDValue();
4941
4942     int FI = -1;
4943     int64_t Offset = 0;
4944     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4945       FI = FINode->getIndex();
4946       Offset = 0;
4947     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4948                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4949       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4950       Offset = Ptr.getConstantOperandVal(1);
4951       Ptr = Ptr.getOperand(0);
4952     } else {
4953       return SDValue();
4954     }
4955
4956     // FIXME: 256-bit vector instructions don't require a strict alignment,
4957     // improve this code to support it better.
4958     unsigned RequiredAlign = VT.getSizeInBits()/8;
4959     SDValue Chain = LD->getChain();
4960     // Make sure the stack object alignment is at least 16 or 32.
4961     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4962     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4963       if (MFI->isFixedObjectIndex(FI)) {
4964         // Can't change the alignment. FIXME: It's possible to compute
4965         // the exact stack offset and reference FI + adjust offset instead.
4966         // If someone *really* cares about this. That's the way to implement it.
4967         return SDValue();
4968       } else {
4969         MFI->setObjectAlignment(FI, RequiredAlign);
4970       }
4971     }
4972
4973     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4974     // Ptr + (Offset & ~15).
4975     if (Offset < 0)
4976       return SDValue();
4977     if ((Offset % RequiredAlign) & 3)
4978       return SDValue();
4979     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4980     if (StartOffset) {
4981       SDLoc DL(Ptr);
4982       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4983                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4984     }
4985
4986     int EltNo = (Offset - StartOffset) >> 2;
4987     unsigned NumElems = VT.getVectorNumElements();
4988
4989     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4990     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4991                              LD->getPointerInfo().getWithOffset(StartOffset),
4992                              false, false, false, 0);
4993
4994     SmallVector<int, 8> Mask(NumElems, EltNo);
4995
4996     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4997   }
4998
4999   return SDValue();
5000 }
5001
5002 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5003 /// elements can be replaced by a single large load which has the same value as
5004 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5005 ///
5006 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5007 ///
5008 /// FIXME: we'd also like to handle the case where the last elements are zero
5009 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5010 /// There's even a handy isZeroNode for that purpose.
5011 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5012                                         SDLoc &DL, SelectionDAG &DAG,
5013                                         bool isAfterLegalize) {
5014   unsigned NumElems = Elts.size();
5015
5016   LoadSDNode *LDBase = nullptr;
5017   unsigned LastLoadedElt = -1U;
5018
5019   // For each element in the initializer, see if we've found a load or an undef.
5020   // If we don't find an initial load element, or later load elements are
5021   // non-consecutive, bail out.
5022   for (unsigned i = 0; i < NumElems; ++i) {
5023     SDValue Elt = Elts[i];
5024     // Look through a bitcast.
5025     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5026       Elt = Elt.getOperand(0);
5027     if (!Elt.getNode() ||
5028         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5029       return SDValue();
5030     if (!LDBase) {
5031       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5032         return SDValue();
5033       LDBase = cast<LoadSDNode>(Elt.getNode());
5034       LastLoadedElt = i;
5035       continue;
5036     }
5037     if (Elt.getOpcode() == ISD::UNDEF)
5038       continue;
5039
5040     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5041     EVT LdVT = Elt.getValueType();
5042     // Each loaded element must be the correct fractional portion of the
5043     // requested vector load.
5044     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5045       return SDValue();
5046     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5047       return SDValue();
5048     LastLoadedElt = i;
5049   }
5050
5051   // If we have found an entire vector of loads and undefs, then return a large
5052   // load of the entire vector width starting at the base pointer.  If we found
5053   // consecutive loads for the low half, generate a vzext_load node.
5054   if (LastLoadedElt == NumElems - 1) {
5055     assert(LDBase && "Did not find base load for merging consecutive loads");
5056     EVT EltVT = LDBase->getValueType(0);
5057     // Ensure that the input vector size for the merged loads matches the
5058     // cumulative size of the input elements.
5059     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5060       return SDValue();
5061
5062     if (isAfterLegalize &&
5063         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5064       return SDValue();
5065
5066     SDValue NewLd = SDValue();
5067
5068     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5069                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5070                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5071                         LDBase->getAlignment());
5072
5073     if (LDBase->hasAnyUseOfValue(1)) {
5074       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5075                                      SDValue(LDBase, 1),
5076                                      SDValue(NewLd.getNode(), 1));
5077       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5078       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5079                              SDValue(NewLd.getNode(), 1));
5080     }
5081
5082     return NewLd;
5083   }
5084
5085   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5086   //of a v4i32 / v4f32. It's probably worth generalizing.
5087   EVT EltVT = VT.getVectorElementType();
5088   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5089       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5090     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5091     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5092     SDValue ResNode =
5093         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5094                                 LDBase->getPointerInfo(),
5095                                 LDBase->getAlignment(),
5096                                 false/*isVolatile*/, true/*ReadMem*/,
5097                                 false/*WriteMem*/);
5098
5099     // Make sure the newly-created LOAD is in the same position as LDBase in
5100     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5101     // update uses of LDBase's output chain to use the TokenFactor.
5102     if (LDBase->hasAnyUseOfValue(1)) {
5103       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5104                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5105       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5106       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5107                              SDValue(ResNode.getNode(), 1));
5108     }
5109
5110     return DAG.getBitcast(VT, ResNode);
5111   }
5112   return SDValue();
5113 }
5114
5115 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5116 /// to generate a splat value for the following cases:
5117 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5118 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5119 /// a scalar load, or a constant.
5120 /// The VBROADCAST node is returned when a pattern is found,
5121 /// or SDValue() otherwise.
5122 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5123                                     SelectionDAG &DAG) {
5124   // VBROADCAST requires AVX.
5125   // TODO: Splats could be generated for non-AVX CPUs using SSE
5126   // instructions, but there's less potential gain for only 128-bit vectors.
5127   if (!Subtarget->hasAVX())
5128     return SDValue();
5129
5130   MVT VT = Op.getSimpleValueType();
5131   SDLoc dl(Op);
5132
5133   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5134          "Unsupported vector type for broadcast.");
5135
5136   SDValue Ld;
5137   bool ConstSplatVal;
5138
5139   switch (Op.getOpcode()) {
5140     default:
5141       // Unknown pattern found.
5142       return SDValue();
5143
5144     case ISD::BUILD_VECTOR: {
5145       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5146       BitVector UndefElements;
5147       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5148
5149       // We need a splat of a single value to use broadcast, and it doesn't
5150       // make any sense if the value is only in one element of the vector.
5151       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5152         return SDValue();
5153
5154       Ld = Splat;
5155       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5156                        Ld.getOpcode() == ISD::ConstantFP);
5157
5158       // Make sure that all of the users of a non-constant load are from the
5159       // BUILD_VECTOR node.
5160       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5161         return SDValue();
5162       break;
5163     }
5164
5165     case ISD::VECTOR_SHUFFLE: {
5166       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5167
5168       // Shuffles must have a splat mask where the first element is
5169       // broadcasted.
5170       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5171         return SDValue();
5172
5173       SDValue Sc = Op.getOperand(0);
5174       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5175           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5176
5177         if (!Subtarget->hasInt256())
5178           return SDValue();
5179
5180         // Use the register form of the broadcast instruction available on AVX2.
5181         if (VT.getSizeInBits() >= 256)
5182           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5183         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5184       }
5185
5186       Ld = Sc.getOperand(0);
5187       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5188                        Ld.getOpcode() == ISD::ConstantFP);
5189
5190       // The scalar_to_vector node and the suspected
5191       // load node must have exactly one user.
5192       // Constants may have multiple users.
5193
5194       // AVX-512 has register version of the broadcast
5195       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5196         Ld.getValueType().getSizeInBits() >= 32;
5197       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5198           !hasRegVer))
5199         return SDValue();
5200       break;
5201     }
5202   }
5203
5204   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5205   bool IsGE256 = (VT.getSizeInBits() >= 256);
5206
5207   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5208   // instruction to save 8 or more bytes of constant pool data.
5209   // TODO: If multiple splats are generated to load the same constant,
5210   // it may be detrimental to overall size. There needs to be a way to detect
5211   // that condition to know if this is truly a size win.
5212   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5213
5214   // Handle broadcasting a single constant scalar from the constant pool
5215   // into a vector.
5216   // On Sandybridge (no AVX2), it is still better to load a constant vector
5217   // from the constant pool and not to broadcast it from a scalar.
5218   // But override that restriction when optimizing for size.
5219   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5220   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5221     EVT CVT = Ld.getValueType();
5222     assert(!CVT.isVector() && "Must not broadcast a vector type");
5223
5224     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5225     // For size optimization, also splat v2f64 and v2i64, and for size opt
5226     // with AVX2, also splat i8 and i16.
5227     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5228     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5229         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5230       const Constant *C = nullptr;
5231       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5232         C = CI->getConstantIntValue();
5233       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5234         C = CF->getConstantFPValue();
5235
5236       assert(C && "Invalid constant type");
5237
5238       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5239       SDValue CP =
5240           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5241       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242       Ld = DAG.getLoad(
5243           CVT, dl, DAG.getEntryNode(), CP,
5244           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5245           false, false, Alignment);
5246
5247       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5248     }
5249   }
5250
5251   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5252
5253   // Handle AVX2 in-register broadcasts.
5254   if (!IsLoad && Subtarget->hasInt256() &&
5255       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5256     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257
5258   // The scalar source must be a normal load.
5259   if (!IsLoad)
5260     return SDValue();
5261
5262   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5263       (Subtarget->hasVLX() && ScalarSize == 64))
5264     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5265
5266   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5267   // double since there is no vbroadcastsd xmm
5268   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5269     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5270       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5271   }
5272
5273   // Unsupported broadcast.
5274   return SDValue();
5275 }
5276
5277 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5278 /// underlying vector and index.
5279 ///
5280 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5281 /// index.
5282 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5283                                          SDValue ExtIdx) {
5284   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5285   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5286     return Idx;
5287
5288   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5289   // lowered this:
5290   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5291   // to:
5292   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5293   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5294   //                           undef)
5295   //                       Constant<0>)
5296   // In this case the vector is the extract_subvector expression and the index
5297   // is 2, as specified by the shuffle.
5298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5299   SDValue ShuffleVec = SVOp->getOperand(0);
5300   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5301   assert(ShuffleVecVT.getVectorElementType() ==
5302          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5303
5304   int ShuffleIdx = SVOp->getMaskElt(Idx);
5305   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5306     ExtractedFromVec = ShuffleVec;
5307     return ShuffleIdx;
5308   }
5309   return Idx;
5310 }
5311
5312 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5313   MVT VT = Op.getSimpleValueType();
5314
5315   // Skip if insert_vec_elt is not supported.
5316   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5317   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5318     return SDValue();
5319
5320   SDLoc DL(Op);
5321   unsigned NumElems = Op.getNumOperands();
5322
5323   SDValue VecIn1;
5324   SDValue VecIn2;
5325   SmallVector<unsigned, 4> InsertIndices;
5326   SmallVector<int, 8> Mask(NumElems, -1);
5327
5328   for (unsigned i = 0; i != NumElems; ++i) {
5329     unsigned Opc = Op.getOperand(i).getOpcode();
5330
5331     if (Opc == ISD::UNDEF)
5332       continue;
5333
5334     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5335       // Quit if more than 1 elements need inserting.
5336       if (InsertIndices.size() > 1)
5337         return SDValue();
5338
5339       InsertIndices.push_back(i);
5340       continue;
5341     }
5342
5343     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5344     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5345     // Quit if non-constant index.
5346     if (!isa<ConstantSDNode>(ExtIdx))
5347       return SDValue();
5348     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5349
5350     // Quit if extracted from vector of different type.
5351     if (ExtractedFromVec.getValueType() != VT)
5352       return SDValue();
5353
5354     if (!VecIn1.getNode())
5355       VecIn1 = ExtractedFromVec;
5356     else if (VecIn1 != ExtractedFromVec) {
5357       if (!VecIn2.getNode())
5358         VecIn2 = ExtractedFromVec;
5359       else if (VecIn2 != ExtractedFromVec)
5360         // Quit if more than 2 vectors to shuffle
5361         return SDValue();
5362     }
5363
5364     if (ExtractedFromVec == VecIn1)
5365       Mask[i] = Idx;
5366     else if (ExtractedFromVec == VecIn2)
5367       Mask[i] = Idx + NumElems;
5368   }
5369
5370   if (!VecIn1.getNode())
5371     return SDValue();
5372
5373   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5374   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5375   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5376     unsigned Idx = InsertIndices[i];
5377     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5378                      DAG.getIntPtrConstant(Idx, DL));
5379   }
5380
5381   return NV;
5382 }
5383
5384 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5385   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5386          Op.getScalarValueSizeInBits() == 1 &&
5387          "Can not convert non-constant vector");
5388   uint64_t Immediate = 0;
5389   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5390     SDValue In = Op.getOperand(idx);
5391     if (In.getOpcode() != ISD::UNDEF)
5392       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5393   }
5394   SDLoc dl(Op);
5395   MVT VT =
5396    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5397   return DAG.getConstant(Immediate, dl, VT);
5398 }
5399 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5400 SDValue
5401 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5402
5403   MVT VT = Op.getSimpleValueType();
5404   assert((VT.getVectorElementType() == MVT::i1) &&
5405          "Unexpected type in LowerBUILD_VECTORvXi1!");
5406
5407   SDLoc dl(Op);
5408   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5409     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5410     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5411     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5412   }
5413
5414   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5415     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5416     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5417     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5418   }
5419
5420   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5421     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5422     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5423       return DAG.getBitcast(VT, Imm);
5424     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5425     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5426                         DAG.getIntPtrConstant(0, dl));
5427   }
5428
5429   // Vector has one or more non-const elements
5430   uint64_t Immediate = 0;
5431   SmallVector<unsigned, 16> NonConstIdx;
5432   bool IsSplat = true;
5433   bool HasConstElts = false;
5434   int SplatIdx = -1;
5435   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5436     SDValue In = Op.getOperand(idx);
5437     if (In.getOpcode() == ISD::UNDEF)
5438       continue;
5439     if (!isa<ConstantSDNode>(In))
5440       NonConstIdx.push_back(idx);
5441     else {
5442       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5443       HasConstElts = true;
5444     }
5445     if (SplatIdx == -1)
5446       SplatIdx = idx;
5447     else if (In != Op.getOperand(SplatIdx))
5448       IsSplat = false;
5449   }
5450
5451   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5452   if (IsSplat)
5453     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5454                        DAG.getConstant(1, dl, VT),
5455                        DAG.getConstant(0, dl, VT));
5456
5457   // insert elements one by one
5458   SDValue DstVec;
5459   SDValue Imm;
5460   if (Immediate) {
5461     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5462     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5463   }
5464   else if (HasConstElts)
5465     Imm = DAG.getConstant(0, dl, VT);
5466   else
5467     Imm = DAG.getUNDEF(VT);
5468   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5469     DstVec = DAG.getBitcast(VT, Imm);
5470   else {
5471     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5472     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5473                          DAG.getIntPtrConstant(0, dl));
5474   }
5475
5476   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5477     unsigned InsertIdx = NonConstIdx[i];
5478     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5479                          Op.getOperand(InsertIdx),
5480                          DAG.getIntPtrConstant(InsertIdx, dl));
5481   }
5482   return DstVec;
5483 }
5484
5485 /// \brief Return true if \p N implements a horizontal binop and return the
5486 /// operands for the horizontal binop into V0 and V1.
5487 ///
5488 /// This is a helper function of LowerToHorizontalOp().
5489 /// This function checks that the build_vector \p N in input implements a
5490 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5491 /// operation to match.
5492 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5493 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5494 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5495 /// arithmetic sub.
5496 ///
5497 /// This function only analyzes elements of \p N whose indices are
5498 /// in range [BaseIdx, LastIdx).
5499 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5500                               SelectionDAG &DAG,
5501                               unsigned BaseIdx, unsigned LastIdx,
5502                               SDValue &V0, SDValue &V1) {
5503   EVT VT = N->getValueType(0);
5504
5505   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5506   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5507          "Invalid Vector in input!");
5508
5509   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5510   bool CanFold = true;
5511   unsigned ExpectedVExtractIdx = BaseIdx;
5512   unsigned NumElts = LastIdx - BaseIdx;
5513   V0 = DAG.getUNDEF(VT);
5514   V1 = DAG.getUNDEF(VT);
5515
5516   // Check if N implements a horizontal binop.
5517   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5518     SDValue Op = N->getOperand(i + BaseIdx);
5519
5520     // Skip UNDEFs.
5521     if (Op->getOpcode() == ISD::UNDEF) {
5522       // Update the expected vector extract index.
5523       if (i * 2 == NumElts)
5524         ExpectedVExtractIdx = BaseIdx;
5525       ExpectedVExtractIdx += 2;
5526       continue;
5527     }
5528
5529     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5530
5531     if (!CanFold)
5532       break;
5533
5534     SDValue Op0 = Op.getOperand(0);
5535     SDValue Op1 = Op.getOperand(1);
5536
5537     // Try to match the following pattern:
5538     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5539     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5540         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5541         Op0.getOperand(0) == Op1.getOperand(0) &&
5542         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5543         isa<ConstantSDNode>(Op1.getOperand(1)));
5544     if (!CanFold)
5545       break;
5546
5547     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5548     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5549
5550     if (i * 2 < NumElts) {
5551       if (V0.getOpcode() == ISD::UNDEF) {
5552         V0 = Op0.getOperand(0);
5553         if (V0.getValueType() != VT)
5554           return false;
5555       }
5556     } else {
5557       if (V1.getOpcode() == ISD::UNDEF) {
5558         V1 = Op0.getOperand(0);
5559         if (V1.getValueType() != VT)
5560           return false;
5561       }
5562       if (i * 2 == NumElts)
5563         ExpectedVExtractIdx = BaseIdx;
5564     }
5565
5566     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5567     if (I0 == ExpectedVExtractIdx)
5568       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5569     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5570       // Try to match the following dag sequence:
5571       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5572       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5573     } else
5574       CanFold = false;
5575
5576     ExpectedVExtractIdx += 2;
5577   }
5578
5579   return CanFold;
5580 }
5581
5582 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5583 /// a concat_vector.
5584 ///
5585 /// This is a helper function of LowerToHorizontalOp().
5586 /// This function expects two 256-bit vectors called V0 and V1.
5587 /// At first, each vector is split into two separate 128-bit vectors.
5588 /// Then, the resulting 128-bit vectors are used to implement two
5589 /// horizontal binary operations.
5590 ///
5591 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5592 ///
5593 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5594 /// the two new horizontal binop.
5595 /// When Mode is set, the first horizontal binop dag node would take as input
5596 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5597 /// horizontal binop dag node would take as input the lower 128-bit of V1
5598 /// and the upper 128-bit of V1.
5599 ///   Example:
5600 ///     HADD V0_LO, V0_HI
5601 ///     HADD V1_LO, V1_HI
5602 ///
5603 /// Otherwise, the first horizontal binop dag node takes as input the lower
5604 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5605 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5606 ///   Example:
5607 ///     HADD V0_LO, V1_LO
5608 ///     HADD V0_HI, V1_HI
5609 ///
5610 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5611 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5612 /// the upper 128-bits of the result.
5613 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5614                                      SDLoc DL, SelectionDAG &DAG,
5615                                      unsigned X86Opcode, bool Mode,
5616                                      bool isUndefLO, bool isUndefHI) {
5617   EVT VT = V0.getValueType();
5618   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5619          "Invalid nodes in input!");
5620
5621   unsigned NumElts = VT.getVectorNumElements();
5622   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5623   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5624   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5625   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5626   EVT NewVT = V0_LO.getValueType();
5627
5628   SDValue LO = DAG.getUNDEF(NewVT);
5629   SDValue HI = DAG.getUNDEF(NewVT);
5630
5631   if (Mode) {
5632     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5633     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5634       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5635     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5636       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5637   } else {
5638     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5639     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5640                        V1_LO->getOpcode() != ISD::UNDEF))
5641       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5642
5643     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5644                        V1_HI->getOpcode() != ISD::UNDEF))
5645       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5646   }
5647
5648   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5649 }
5650
5651 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5652 /// node.
5653 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5654                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5655   EVT VT = BV->getValueType(0);
5656   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5657       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5658     return SDValue();
5659
5660   SDLoc DL(BV);
5661   unsigned NumElts = VT.getVectorNumElements();
5662   SDValue InVec0 = DAG.getUNDEF(VT);
5663   SDValue InVec1 = DAG.getUNDEF(VT);
5664
5665   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5666           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5667
5668   // Odd-numbered elements in the input build vector are obtained from
5669   // adding two integer/float elements.
5670   // Even-numbered elements in the input build vector are obtained from
5671   // subtracting two integer/float elements.
5672   unsigned ExpectedOpcode = ISD::FSUB;
5673   unsigned NextExpectedOpcode = ISD::FADD;
5674   bool AddFound = false;
5675   bool SubFound = false;
5676
5677   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5678     SDValue Op = BV->getOperand(i);
5679
5680     // Skip 'undef' values.
5681     unsigned Opcode = Op.getOpcode();
5682     if (Opcode == ISD::UNDEF) {
5683       std::swap(ExpectedOpcode, NextExpectedOpcode);
5684       continue;
5685     }
5686
5687     // Early exit if we found an unexpected opcode.
5688     if (Opcode != ExpectedOpcode)
5689       return SDValue();
5690
5691     SDValue Op0 = Op.getOperand(0);
5692     SDValue Op1 = Op.getOperand(1);
5693
5694     // Try to match the following pattern:
5695     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5696     // Early exit if we cannot match that sequence.
5697     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5698         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5699         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5700         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5701         Op0.getOperand(1) != Op1.getOperand(1))
5702       return SDValue();
5703
5704     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5705     if (I0 != i)
5706       return SDValue();
5707
5708     // We found a valid add/sub node. Update the information accordingly.
5709     if (i & 1)
5710       AddFound = true;
5711     else
5712       SubFound = true;
5713
5714     // Update InVec0 and InVec1.
5715     if (InVec0.getOpcode() == ISD::UNDEF) {
5716       InVec0 = Op0.getOperand(0);
5717       if (InVec0.getValueType() != VT)
5718         return SDValue();
5719     }
5720     if (InVec1.getOpcode() == ISD::UNDEF) {
5721       InVec1 = Op1.getOperand(0);
5722       if (InVec1.getValueType() != VT)
5723         return SDValue();
5724     }
5725
5726     // Make sure that operands in input to each add/sub node always
5727     // come from a same pair of vectors.
5728     if (InVec0 != Op0.getOperand(0)) {
5729       if (ExpectedOpcode == ISD::FSUB)
5730         return SDValue();
5731
5732       // FADD is commutable. Try to commute the operands
5733       // and then test again.
5734       std::swap(Op0, Op1);
5735       if (InVec0 != Op0.getOperand(0))
5736         return SDValue();
5737     }
5738
5739     if (InVec1 != Op1.getOperand(0))
5740       return SDValue();
5741
5742     // Update the pair of expected opcodes.
5743     std::swap(ExpectedOpcode, NextExpectedOpcode);
5744   }
5745
5746   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5747   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5748       InVec1.getOpcode() != ISD::UNDEF)
5749     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5750
5751   return SDValue();
5752 }
5753
5754 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5755 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5756                                    const X86Subtarget *Subtarget,
5757                                    SelectionDAG &DAG) {
5758   EVT VT = BV->getValueType(0);
5759   unsigned NumElts = VT.getVectorNumElements();
5760   unsigned NumUndefsLO = 0;
5761   unsigned NumUndefsHI = 0;
5762   unsigned Half = NumElts/2;
5763
5764   // Count the number of UNDEF operands in the build_vector in input.
5765   for (unsigned i = 0, e = Half; i != e; ++i)
5766     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5767       NumUndefsLO++;
5768
5769   for (unsigned i = Half, e = NumElts; i != e; ++i)
5770     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5771       NumUndefsHI++;
5772
5773   // Early exit if this is either a build_vector of all UNDEFs or all the
5774   // operands but one are UNDEF.
5775   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5776     return SDValue();
5777
5778   SDLoc DL(BV);
5779   SDValue InVec0, InVec1;
5780   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5781     // Try to match an SSE3 float HADD/HSUB.
5782     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5783       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5784
5785     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5786       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5787   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5788     // Try to match an SSSE3 integer HADD/HSUB.
5789     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5790       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5791
5792     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5793       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5794   }
5795
5796   if (!Subtarget->hasAVX())
5797     return SDValue();
5798
5799   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5800     // Try to match an AVX horizontal add/sub of packed single/double
5801     // precision floating point values from 256-bit vectors.
5802     SDValue InVec2, InVec3;
5803     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5804         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5805         ((InVec0.getOpcode() == ISD::UNDEF ||
5806           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5807         ((InVec1.getOpcode() == ISD::UNDEF ||
5808           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5809       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5810
5811     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5812         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5813         ((InVec0.getOpcode() == ISD::UNDEF ||
5814           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5815         ((InVec1.getOpcode() == ISD::UNDEF ||
5816           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5817       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5818   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5819     // Try to match an AVX2 horizontal add/sub of signed integers.
5820     SDValue InVec2, InVec3;
5821     unsigned X86Opcode;
5822     bool CanFold = true;
5823
5824     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5825         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5826         ((InVec0.getOpcode() == ISD::UNDEF ||
5827           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5828         ((InVec1.getOpcode() == ISD::UNDEF ||
5829           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5830       X86Opcode = X86ISD::HADD;
5831     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5832         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5833         ((InVec0.getOpcode() == ISD::UNDEF ||
5834           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5835         ((InVec1.getOpcode() == ISD::UNDEF ||
5836           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5837       X86Opcode = X86ISD::HSUB;
5838     else
5839       CanFold = false;
5840
5841     if (CanFold) {
5842       // Fold this build_vector into a single horizontal add/sub.
5843       // Do this only if the target has AVX2.
5844       if (Subtarget->hasAVX2())
5845         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5846
5847       // Do not try to expand this build_vector into a pair of horizontal
5848       // add/sub if we can emit a pair of scalar add/sub.
5849       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5850         return SDValue();
5851
5852       // Convert this build_vector into a pair of horizontal binop followed by
5853       // a concat vector.
5854       bool isUndefLO = NumUndefsLO == Half;
5855       bool isUndefHI = NumUndefsHI == Half;
5856       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5857                                    isUndefLO, isUndefHI);
5858     }
5859   }
5860
5861   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5862        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5863     unsigned X86Opcode;
5864     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5865       X86Opcode = X86ISD::HADD;
5866     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5867       X86Opcode = X86ISD::HSUB;
5868     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5869       X86Opcode = X86ISD::FHADD;
5870     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5871       X86Opcode = X86ISD::FHSUB;
5872     else
5873       return SDValue();
5874
5875     // Don't try to expand this build_vector into a pair of horizontal add/sub
5876     // if we can simply emit a pair of scalar add/sub.
5877     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5878       return SDValue();
5879
5880     // Convert this build_vector into two horizontal add/sub followed by
5881     // a concat vector.
5882     bool isUndefLO = NumUndefsLO == Half;
5883     bool isUndefHI = NumUndefsHI == Half;
5884     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5885                                  isUndefLO, isUndefHI);
5886   }
5887
5888   return SDValue();
5889 }
5890
5891 SDValue
5892 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5893   SDLoc dl(Op);
5894
5895   MVT VT = Op.getSimpleValueType();
5896   MVT ExtVT = VT.getVectorElementType();
5897   unsigned NumElems = Op.getNumOperands();
5898
5899   // Generate vectors for predicate vectors.
5900   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5901     return LowerBUILD_VECTORvXi1(Op, DAG);
5902
5903   // Vectors containing all zeros can be matched by pxor and xorps later
5904   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5905     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5906     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5907     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5908       return Op;
5909
5910     return getZeroVector(VT, Subtarget, DAG, dl);
5911   }
5912
5913   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5914   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5915   // vpcmpeqd on 256-bit vectors.
5916   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5917     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5918       return Op;
5919
5920     if (!VT.is512BitVector())
5921       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5922   }
5923
5924   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5925   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5926     return AddSub;
5927   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5928     return HorizontalOp;
5929   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5930     return Broadcast;
5931
5932   unsigned EVTBits = ExtVT.getSizeInBits();
5933
5934   unsigned NumZero  = 0;
5935   unsigned NumNonZero = 0;
5936   unsigned NonZeros = 0;
5937   bool IsAllConstants = true;
5938   SmallSet<SDValue, 8> Values;
5939   for (unsigned i = 0; i < NumElems; ++i) {
5940     SDValue Elt = Op.getOperand(i);
5941     if (Elt.getOpcode() == ISD::UNDEF)
5942       continue;
5943     Values.insert(Elt);
5944     if (Elt.getOpcode() != ISD::Constant &&
5945         Elt.getOpcode() != ISD::ConstantFP)
5946       IsAllConstants = false;
5947     if (X86::isZeroNode(Elt))
5948       NumZero++;
5949     else {
5950       NonZeros |= (1 << i);
5951       NumNonZero++;
5952     }
5953   }
5954
5955   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5956   if (NumNonZero == 0)
5957     return DAG.getUNDEF(VT);
5958
5959   // Special case for single non-zero, non-undef, element.
5960   if (NumNonZero == 1) {
5961     unsigned Idx = countTrailingZeros(NonZeros);
5962     SDValue Item = Op.getOperand(Idx);
5963
5964     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5965     // the value are obviously zero, truncate the value to i32 and do the
5966     // insertion that way.  Only do this if the value is non-constant or if the
5967     // value is a constant being inserted into element 0.  It is cheaper to do
5968     // a constant pool load than it is to do a movd + shuffle.
5969     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5970         (!IsAllConstants || Idx == 0)) {
5971       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5972         // Handle SSE only.
5973         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5974         EVT VecVT = MVT::v4i32;
5975
5976         // Truncate the value (which may itself be a constant) to i32, and
5977         // convert it to a vector with movd (S2V+shuffle to zero extend).
5978         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5979         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5980         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5981                                       Item, Idx * 2, true, Subtarget, DAG));
5982       }
5983     }
5984
5985     // If we have a constant or non-constant insertion into the low element of
5986     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5987     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5988     // depending on what the source datatype is.
5989     if (Idx == 0) {
5990       if (NumZero == 0)
5991         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5992
5993       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5994           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5995         if (VT.is512BitVector()) {
5996           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5997           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5998                              Item, DAG.getIntPtrConstant(0, dl));
5999         }
6000         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6001                "Expected an SSE value type!");
6002         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6003         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6004         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6005       }
6006
6007       // We can't directly insert an i8 or i16 into a vector, so zero extend
6008       // it to i32 first.
6009       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6010         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6011         if (VT.is256BitVector()) {
6012           if (Subtarget->hasAVX()) {
6013             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6014             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6015           } else {
6016             // Without AVX, we need to extend to a 128-bit vector and then
6017             // insert into the 256-bit vector.
6018             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6019             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6020             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6021           }
6022         } else {
6023           assert(VT.is128BitVector() && "Expected an SSE value type!");
6024           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6025           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6026         }
6027         return DAG.getBitcast(VT, Item);
6028       }
6029     }
6030
6031     // Is it a vector logical left shift?
6032     if (NumElems == 2 && Idx == 1 &&
6033         X86::isZeroNode(Op.getOperand(0)) &&
6034         !X86::isZeroNode(Op.getOperand(1))) {
6035       unsigned NumBits = VT.getSizeInBits();
6036       return getVShift(true, VT,
6037                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6038                                    VT, Op.getOperand(1)),
6039                        NumBits/2, DAG, *this, dl);
6040     }
6041
6042     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6043       return SDValue();
6044
6045     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6046     // is a non-constant being inserted into an element other than the low one,
6047     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6048     // movd/movss) to move this into the low element, then shuffle it into
6049     // place.
6050     if (EVTBits == 32) {
6051       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6052       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6053     }
6054   }
6055
6056   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6057   if (Values.size() == 1) {
6058     if (EVTBits == 32) {
6059       // Instead of a shuffle like this:
6060       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6061       // Check if it's possible to issue this instead.
6062       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6063       unsigned Idx = countTrailingZeros(NonZeros);
6064       SDValue Item = Op.getOperand(Idx);
6065       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6066         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6067     }
6068     return SDValue();
6069   }
6070
6071   // A vector full of immediates; various special cases are already
6072   // handled, so this is best done with a single constant-pool load.
6073   if (IsAllConstants)
6074     return SDValue();
6075
6076   // For AVX-length vectors, see if we can use a vector load to get all of the
6077   // elements, otherwise build the individual 128-bit pieces and use
6078   // shuffles to put them in place.
6079   if (VT.is256BitVector() || VT.is512BitVector()) {
6080     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6081
6082     // Check for a build vector of consecutive loads.
6083     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6084       return LD;
6085
6086     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6087
6088     // Build both the lower and upper subvector.
6089     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6090                                 makeArrayRef(&V[0], NumElems/2));
6091     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6092                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6093
6094     // Recreate the wider vector with the lower and upper part.
6095     if (VT.is256BitVector())
6096       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6097     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6098   }
6099
6100   // Let legalizer expand 2-wide build_vectors.
6101   if (EVTBits == 64) {
6102     if (NumNonZero == 1) {
6103       // One half is zero or undef.
6104       unsigned Idx = countTrailingZeros(NonZeros);
6105       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6106                                  Op.getOperand(Idx));
6107       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6108     }
6109     return SDValue();
6110   }
6111
6112   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6113   if (EVTBits == 8 && NumElems == 16)
6114     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6115                                         Subtarget, *this))
6116       return V;
6117
6118   if (EVTBits == 16 && NumElems == 8)
6119     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6120                                       Subtarget, *this))
6121       return V;
6122
6123   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6124   if (EVTBits == 32 && NumElems == 4)
6125     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6126       return V;
6127
6128   // If element VT is == 32 bits, turn it into a number of shuffles.
6129   SmallVector<SDValue, 8> V(NumElems);
6130   if (NumElems == 4 && NumZero > 0) {
6131     for (unsigned i = 0; i < 4; ++i) {
6132       bool isZero = !(NonZeros & (1 << i));
6133       if (isZero)
6134         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6135       else
6136         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6137     }
6138
6139     for (unsigned i = 0; i < 2; ++i) {
6140       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6141         default: break;
6142         case 0:
6143           V[i] = V[i*2];  // Must be a zero vector.
6144           break;
6145         case 1:
6146           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6147           break;
6148         case 2:
6149           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6150           break;
6151         case 3:
6152           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6153           break;
6154       }
6155     }
6156
6157     bool Reverse1 = (NonZeros & 0x3) == 2;
6158     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6159     int MaskVec[] = {
6160       Reverse1 ? 1 : 0,
6161       Reverse1 ? 0 : 1,
6162       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6163       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6164     };
6165     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6166   }
6167
6168   if (Values.size() > 1 && VT.is128BitVector()) {
6169     // Check for a build vector of consecutive loads.
6170     for (unsigned i = 0; i < NumElems; ++i)
6171       V[i] = Op.getOperand(i);
6172
6173     // Check for elements which are consecutive loads.
6174     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6175       return LD;
6176
6177     // Check for a build vector from mostly shuffle plus few inserting.
6178     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6179       return Sh;
6180
6181     // For SSE 4.1, use insertps to put the high elements into the low element.
6182     if (Subtarget->hasSSE41()) {
6183       SDValue Result;
6184       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6185         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6186       else
6187         Result = DAG.getUNDEF(VT);
6188
6189       for (unsigned i = 1; i < NumElems; ++i) {
6190         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6191         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6192                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6193       }
6194       return Result;
6195     }
6196
6197     // Otherwise, expand into a number of unpckl*, start by extending each of
6198     // our (non-undef) elements to the full vector width with the element in the
6199     // bottom slot of the vector (which generates no code for SSE).
6200     for (unsigned i = 0; i < NumElems; ++i) {
6201       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6202         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6203       else
6204         V[i] = DAG.getUNDEF(VT);
6205     }
6206
6207     // Next, we iteratively mix elements, e.g. for v4f32:
6208     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6209     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6210     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6211     unsigned EltStride = NumElems >> 1;
6212     while (EltStride != 0) {
6213       for (unsigned i = 0; i < EltStride; ++i) {
6214         // If V[i+EltStride] is undef and this is the first round of mixing,
6215         // then it is safe to just drop this shuffle: V[i] is already in the
6216         // right place, the one element (since it's the first round) being
6217         // inserted as undef can be dropped.  This isn't safe for successive
6218         // rounds because they will permute elements within both vectors.
6219         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6220             EltStride == NumElems/2)
6221           continue;
6222
6223         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6224       }
6225       EltStride >>= 1;
6226     }
6227     return V[0];
6228   }
6229   return SDValue();
6230 }
6231
6232 // 256-bit AVX can use the vinsertf128 instruction
6233 // to create 256-bit vectors from two other 128-bit ones.
6234 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6235   SDLoc dl(Op);
6236   MVT ResVT = Op.getSimpleValueType();
6237
6238   assert((ResVT.is256BitVector() ||
6239           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6240
6241   SDValue V1 = Op.getOperand(0);
6242   SDValue V2 = Op.getOperand(1);
6243   unsigned NumElems = ResVT.getVectorNumElements();
6244   if (ResVT.is256BitVector())
6245     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6246
6247   if (Op.getNumOperands() == 4) {
6248     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6249                                 ResVT.getVectorNumElements()/2);
6250     SDValue V3 = Op.getOperand(2);
6251     SDValue V4 = Op.getOperand(3);
6252     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6253       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6254   }
6255   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6256 }
6257
6258 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6259                                        const X86Subtarget *Subtarget,
6260                                        SelectionDAG & DAG) {
6261   SDLoc dl(Op);
6262   MVT ResVT = Op.getSimpleValueType();
6263   unsigned NumOfOperands = Op.getNumOperands();
6264
6265   assert(isPowerOf2_32(NumOfOperands) &&
6266          "Unexpected number of operands in CONCAT_VECTORS");
6267
6268   if (NumOfOperands > 2) {
6269     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6270                                   ResVT.getVectorNumElements()/2);
6271     SmallVector<SDValue, 2> Ops;
6272     for (unsigned i = 0; i < NumOfOperands/2; i++)
6273       Ops.push_back(Op.getOperand(i));
6274     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6275     Ops.clear();
6276     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6277       Ops.push_back(Op.getOperand(i));
6278     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6279     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6280   }
6281
6282   SDValue V1 = Op.getOperand(0);
6283   SDValue V2 = Op.getOperand(1);
6284   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6285   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6286
6287   if (IsZeroV1 && IsZeroV2)
6288     return getZeroVector(ResVT, Subtarget, DAG, dl);
6289
6290   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6291   SDValue Undef = DAG.getUNDEF(ResVT);
6292   unsigned NumElems = ResVT.getVectorNumElements();
6293   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6294
6295   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6296   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6297   if (IsZeroV1)
6298     return V2;
6299
6300   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6301   // Zero the upper bits of V1
6302   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6303   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6304   if (IsZeroV2)
6305     return V1;
6306   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6307 }
6308
6309 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6310                                    const X86Subtarget *Subtarget,
6311                                    SelectionDAG &DAG) {
6312   MVT VT = Op.getSimpleValueType();
6313   if (VT.getVectorElementType() == MVT::i1)
6314     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6315
6316   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6317          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6318           Op.getNumOperands() == 4)));
6319
6320   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6321   // from two other 128-bit ones.
6322
6323   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6324   return LowerAVXCONCAT_VECTORS(Op, DAG);
6325 }
6326
6327
6328 //===----------------------------------------------------------------------===//
6329 // Vector shuffle lowering
6330 //
6331 // This is an experimental code path for lowering vector shuffles on x86. It is
6332 // designed to handle arbitrary vector shuffles and blends, gracefully
6333 // degrading performance as necessary. It works hard to recognize idiomatic
6334 // shuffles and lower them to optimal instruction patterns without leaving
6335 // a framework that allows reasonably efficient handling of all vector shuffle
6336 // patterns.
6337 //===----------------------------------------------------------------------===//
6338
6339 /// \brief Tiny helper function to identify a no-op mask.
6340 ///
6341 /// This is a somewhat boring predicate function. It checks whether the mask
6342 /// array input, which is assumed to be a single-input shuffle mask of the kind
6343 /// used by the X86 shuffle instructions (not a fully general
6344 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6345 /// in-place shuffle are 'no-op's.
6346 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6347   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6348     if (Mask[i] != -1 && Mask[i] != i)
6349       return false;
6350   return true;
6351 }
6352
6353 /// \brief Helper function to classify a mask as a single-input mask.
6354 ///
6355 /// This isn't a generic single-input test because in the vector shuffle
6356 /// lowering we canonicalize single inputs to be the first input operand. This
6357 /// means we can more quickly test for a single input by only checking whether
6358 /// an input from the second operand exists. We also assume that the size of
6359 /// mask corresponds to the size of the input vectors which isn't true in the
6360 /// fully general case.
6361 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6362   for (int M : Mask)
6363     if (M >= (int)Mask.size())
6364       return false;
6365   return true;
6366 }
6367
6368 /// \brief Test whether there are elements crossing 128-bit lanes in this
6369 /// shuffle mask.
6370 ///
6371 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6372 /// and we routinely test for these.
6373 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6374   int LaneSize = 128 / VT.getScalarSizeInBits();
6375   int Size = Mask.size();
6376   for (int i = 0; i < Size; ++i)
6377     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6378       return true;
6379   return false;
6380 }
6381
6382 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6383 ///
6384 /// This checks a shuffle mask to see if it is performing the same
6385 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6386 /// that it is also not lane-crossing. It may however involve a blend from the
6387 /// same lane of a second vector.
6388 ///
6389 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6390 /// non-trivial to compute in the face of undef lanes. The representation is
6391 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6392 /// entries from both V1 and V2 inputs to the wider mask.
6393 static bool
6394 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6395                                 SmallVectorImpl<int> &RepeatedMask) {
6396   int LaneSize = 128 / VT.getScalarSizeInBits();
6397   RepeatedMask.resize(LaneSize, -1);
6398   int Size = Mask.size();
6399   for (int i = 0; i < Size; ++i) {
6400     if (Mask[i] < 0)
6401       continue;
6402     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6403       // This entry crosses lanes, so there is no way to model this shuffle.
6404       return false;
6405
6406     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6407     if (RepeatedMask[i % LaneSize] == -1)
6408       // This is the first non-undef entry in this slot of a 128-bit lane.
6409       RepeatedMask[i % LaneSize] =
6410           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6411     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6412       // Found a mismatch with the repeated mask.
6413       return false;
6414   }
6415   return true;
6416 }
6417
6418 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6419 /// arguments.
6420 ///
6421 /// This is a fast way to test a shuffle mask against a fixed pattern:
6422 ///
6423 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6424 ///
6425 /// It returns true if the mask is exactly as wide as the argument list, and
6426 /// each element of the mask is either -1 (signifying undef) or the value given
6427 /// in the argument.
6428 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6429                                 ArrayRef<int> ExpectedMask) {
6430   if (Mask.size() != ExpectedMask.size())
6431     return false;
6432
6433   int Size = Mask.size();
6434
6435   // If the values are build vectors, we can look through them to find
6436   // equivalent inputs that make the shuffles equivalent.
6437   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6438   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6439
6440   for (int i = 0; i < Size; ++i)
6441     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6442       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6443       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6444       if (!MaskBV || !ExpectedBV ||
6445           MaskBV->getOperand(Mask[i] % Size) !=
6446               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6447         return false;
6448     }
6449
6450   return true;
6451 }
6452
6453 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6454 ///
6455 /// This helper function produces an 8-bit shuffle immediate corresponding to
6456 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6457 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6458 /// example.
6459 ///
6460 /// NB: We rely heavily on "undef" masks preserving the input lane.
6461 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6462                                           SelectionDAG &DAG) {
6463   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6464   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6465   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6466   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6467   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6468
6469   unsigned Imm = 0;
6470   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6471   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6472   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6473   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6474   return DAG.getConstant(Imm, DL, MVT::i8);
6475 }
6476
6477 /// \brief Compute whether each element of a shuffle is zeroable.
6478 ///
6479 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6480 /// Either it is an undef element in the shuffle mask, the element of the input
6481 /// referenced is undef, or the element of the input referenced is known to be
6482 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6483 /// as many lanes with this technique as possible to simplify the remaining
6484 /// shuffle.
6485 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6486                                                      SDValue V1, SDValue V2) {
6487   SmallBitVector Zeroable(Mask.size(), false);
6488
6489   while (V1.getOpcode() == ISD::BITCAST)
6490     V1 = V1->getOperand(0);
6491   while (V2.getOpcode() == ISD::BITCAST)
6492     V2 = V2->getOperand(0);
6493
6494   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6495   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6496
6497   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6498     int M = Mask[i];
6499     // Handle the easy cases.
6500     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6501       Zeroable[i] = true;
6502       continue;
6503     }
6504
6505     // If this is an index into a build_vector node (which has the same number
6506     // of elements), dig out the input value and use it.
6507     SDValue V = M < Size ? V1 : V2;
6508     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6509       continue;
6510
6511     SDValue Input = V.getOperand(M % Size);
6512     // The UNDEF opcode check really should be dead code here, but not quite
6513     // worth asserting on (it isn't invalid, just unexpected).
6514     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6515       Zeroable[i] = true;
6516   }
6517
6518   return Zeroable;
6519 }
6520
6521 /// \brief Try to emit a bitmask instruction for a shuffle.
6522 ///
6523 /// This handles cases where we can model a blend exactly as a bitmask due to
6524 /// one of the inputs being zeroable.
6525 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6526                                            SDValue V2, ArrayRef<int> Mask,
6527                                            SelectionDAG &DAG) {
6528   MVT EltVT = VT.getScalarType();
6529   int NumEltBits = EltVT.getSizeInBits();
6530   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6531   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6532   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6533                                     IntEltVT);
6534   if (EltVT.isFloatingPoint()) {
6535     Zero = DAG.getBitcast(EltVT, Zero);
6536     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6537   }
6538   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6539   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6540   SDValue V;
6541   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6542     if (Zeroable[i])
6543       continue;
6544     if (Mask[i] % Size != i)
6545       return SDValue(); // Not a blend.
6546     if (!V)
6547       V = Mask[i] < Size ? V1 : V2;
6548     else if (V != (Mask[i] < Size ? V1 : V2))
6549       return SDValue(); // Can only let one input through the mask.
6550
6551     VMaskOps[i] = AllOnes;
6552   }
6553   if (!V)
6554     return SDValue(); // No non-zeroable elements!
6555
6556   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6557   V = DAG.getNode(VT.isFloatingPoint()
6558                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6559                   DL, VT, V, VMask);
6560   return V;
6561 }
6562
6563 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6564 ///
6565 /// This is used as a fallback approach when first class blend instructions are
6566 /// unavailable. Currently it is only suitable for integer vectors, but could
6567 /// be generalized for floating point vectors if desirable.
6568 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6569                                             SDValue V2, ArrayRef<int> Mask,
6570                                             SelectionDAG &DAG) {
6571   assert(VT.isInteger() && "Only supports integer vector types!");
6572   MVT EltVT = VT.getScalarType();
6573   int NumEltBits = EltVT.getSizeInBits();
6574   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6575   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6576                                     EltVT);
6577   SmallVector<SDValue, 16> MaskOps;
6578   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6579     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6580       return SDValue(); // Shuffled input!
6581     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6582   }
6583
6584   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6585   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6586   // We have to cast V2 around.
6587   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6588   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6589                                       DAG.getBitcast(MaskVT, V1Mask),
6590                                       DAG.getBitcast(MaskVT, V2)));
6591   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6592 }
6593
6594 /// \brief Try to emit a blend instruction for a shuffle.
6595 ///
6596 /// This doesn't do any checks for the availability of instructions for blending
6597 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6598 /// be matched in the backend with the type given. What it does check for is
6599 /// that the shuffle mask is in fact a blend.
6600 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6601                                          SDValue V2, ArrayRef<int> Mask,
6602                                          const X86Subtarget *Subtarget,
6603                                          SelectionDAG &DAG) {
6604   unsigned BlendMask = 0;
6605   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6606     if (Mask[i] >= Size) {
6607       if (Mask[i] != i + Size)
6608         return SDValue(); // Shuffled V2 input!
6609       BlendMask |= 1u << i;
6610       continue;
6611     }
6612     if (Mask[i] >= 0 && Mask[i] != i)
6613       return SDValue(); // Shuffled V1 input!
6614   }
6615   switch (VT.SimpleTy) {
6616   case MVT::v2f64:
6617   case MVT::v4f32:
6618   case MVT::v4f64:
6619   case MVT::v8f32:
6620     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6621                        DAG.getConstant(BlendMask, DL, MVT::i8));
6622
6623   case MVT::v4i64:
6624   case MVT::v8i32:
6625     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6626     // FALLTHROUGH
6627   case MVT::v2i64:
6628   case MVT::v4i32:
6629     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6630     // that instruction.
6631     if (Subtarget->hasAVX2()) {
6632       // Scale the blend by the number of 32-bit dwords per element.
6633       int Scale =  VT.getScalarSizeInBits() / 32;
6634       BlendMask = 0;
6635       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6636         if (Mask[i] >= Size)
6637           for (int j = 0; j < Scale; ++j)
6638             BlendMask |= 1u << (i * Scale + j);
6639
6640       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6641       V1 = DAG.getBitcast(BlendVT, V1);
6642       V2 = DAG.getBitcast(BlendVT, V2);
6643       return DAG.getBitcast(
6644           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6645                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6646     }
6647     // FALLTHROUGH
6648   case MVT::v8i16: {
6649     // For integer shuffles we need to expand the mask and cast the inputs to
6650     // v8i16s prior to blending.
6651     int Scale = 8 / VT.getVectorNumElements();
6652     BlendMask = 0;
6653     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6654       if (Mask[i] >= Size)
6655         for (int j = 0; j < Scale; ++j)
6656           BlendMask |= 1u << (i * Scale + j);
6657
6658     V1 = DAG.getBitcast(MVT::v8i16, V1);
6659     V2 = DAG.getBitcast(MVT::v8i16, V2);
6660     return DAG.getBitcast(VT,
6661                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6662                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6663   }
6664
6665   case MVT::v16i16: {
6666     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6667     SmallVector<int, 8> RepeatedMask;
6668     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6669       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6670       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6671       BlendMask = 0;
6672       for (int i = 0; i < 8; ++i)
6673         if (RepeatedMask[i] >= 16)
6674           BlendMask |= 1u << i;
6675       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6676                          DAG.getConstant(BlendMask, DL, MVT::i8));
6677     }
6678   }
6679     // FALLTHROUGH
6680   case MVT::v16i8:
6681   case MVT::v32i8: {
6682     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6683            "256-bit byte-blends require AVX2 support!");
6684
6685     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6686     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6687       return Masked;
6688
6689     // Scale the blend by the number of bytes per element.
6690     int Scale = VT.getScalarSizeInBits() / 8;
6691
6692     // This form of blend is always done on bytes. Compute the byte vector
6693     // type.
6694     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6695
6696     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6697     // mix of LLVM's code generator and the x86 backend. We tell the code
6698     // generator that boolean values in the elements of an x86 vector register
6699     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6700     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6701     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6702     // of the element (the remaining are ignored) and 0 in that high bit would
6703     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6704     // the LLVM model for boolean values in vector elements gets the relevant
6705     // bit set, it is set backwards and over constrained relative to x86's
6706     // actual model.
6707     SmallVector<SDValue, 32> VSELECTMask;
6708     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6709       for (int j = 0; j < Scale; ++j)
6710         VSELECTMask.push_back(
6711             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6712                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6713                                           MVT::i8));
6714
6715     V1 = DAG.getBitcast(BlendVT, V1);
6716     V2 = DAG.getBitcast(BlendVT, V2);
6717     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6718                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6719                                                       BlendVT, VSELECTMask),
6720                                           V1, V2));
6721   }
6722
6723   default:
6724     llvm_unreachable("Not a supported integer vector type!");
6725   }
6726 }
6727
6728 /// \brief Try to lower as a blend of elements from two inputs followed by
6729 /// a single-input permutation.
6730 ///
6731 /// This matches the pattern where we can blend elements from two inputs and
6732 /// then reduce the shuffle to a single-input permutation.
6733 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6734                                                    SDValue V2,
6735                                                    ArrayRef<int> Mask,
6736                                                    SelectionDAG &DAG) {
6737   // We build up the blend mask while checking whether a blend is a viable way
6738   // to reduce the shuffle.
6739   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6740   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6741
6742   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6743     if (Mask[i] < 0)
6744       continue;
6745
6746     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6747
6748     if (BlendMask[Mask[i] % Size] == -1)
6749       BlendMask[Mask[i] % Size] = Mask[i];
6750     else if (BlendMask[Mask[i] % Size] != Mask[i])
6751       return SDValue(); // Can't blend in the needed input!
6752
6753     PermuteMask[i] = Mask[i] % Size;
6754   }
6755
6756   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6757   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6758 }
6759
6760 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6761 /// blends and permutes.
6762 ///
6763 /// This matches the extremely common pattern for handling combined
6764 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6765 /// operations. It will try to pick the best arrangement of shuffles and
6766 /// blends.
6767 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6768                                                           SDValue V1,
6769                                                           SDValue V2,
6770                                                           ArrayRef<int> Mask,
6771                                                           SelectionDAG &DAG) {
6772   // Shuffle the input elements into the desired positions in V1 and V2 and
6773   // blend them together.
6774   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6775   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6776   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6777   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6778     if (Mask[i] >= 0 && Mask[i] < Size) {
6779       V1Mask[i] = Mask[i];
6780       BlendMask[i] = i;
6781     } else if (Mask[i] >= Size) {
6782       V2Mask[i] = Mask[i] - Size;
6783       BlendMask[i] = i + Size;
6784     }
6785
6786   // Try to lower with the simpler initial blend strategy unless one of the
6787   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6788   // shuffle may be able to fold with a load or other benefit. However, when
6789   // we'll have to do 2x as many shuffles in order to achieve this, blending
6790   // first is a better strategy.
6791   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6792     if (SDValue BlendPerm =
6793             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6794       return BlendPerm;
6795
6796   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6797   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6798   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6799 }
6800
6801 /// \brief Try to lower a vector shuffle as a byte rotation.
6802 ///
6803 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6804 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6805 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6806 /// try to generically lower a vector shuffle through such an pattern. It
6807 /// does not check for the profitability of lowering either as PALIGNR or
6808 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6809 /// This matches shuffle vectors that look like:
6810 ///
6811 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6812 ///
6813 /// Essentially it concatenates V1 and V2, shifts right by some number of
6814 /// elements, and takes the low elements as the result. Note that while this is
6815 /// specified as a *right shift* because x86 is little-endian, it is a *left
6816 /// rotate* of the vector lanes.
6817 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6818                                               SDValue V2,
6819                                               ArrayRef<int> Mask,
6820                                               const X86Subtarget *Subtarget,
6821                                               SelectionDAG &DAG) {
6822   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6823
6824   int NumElts = Mask.size();
6825   int NumLanes = VT.getSizeInBits() / 128;
6826   int NumLaneElts = NumElts / NumLanes;
6827
6828   // We need to detect various ways of spelling a rotation:
6829   //   [11, 12, 13, 14, 15,  0,  1,  2]
6830   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6831   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6832   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6833   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6834   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6835   int Rotation = 0;
6836   SDValue Lo, Hi;
6837   for (int l = 0; l < NumElts; l += NumLaneElts) {
6838     for (int i = 0; i < NumLaneElts; ++i) {
6839       if (Mask[l + i] == -1)
6840         continue;
6841       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6842
6843       // Get the mod-Size index and lane correct it.
6844       int LaneIdx = (Mask[l + i] % NumElts) - l;
6845       // Make sure it was in this lane.
6846       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6847         return SDValue();
6848
6849       // Determine where a rotated vector would have started.
6850       int StartIdx = i - LaneIdx;
6851       if (StartIdx == 0)
6852         // The identity rotation isn't interesting, stop.
6853         return SDValue();
6854
6855       // If we found the tail of a vector the rotation must be the missing
6856       // front. If we found the head of a vector, it must be how much of the
6857       // head.
6858       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6859
6860       if (Rotation == 0)
6861         Rotation = CandidateRotation;
6862       else if (Rotation != CandidateRotation)
6863         // The rotations don't match, so we can't match this mask.
6864         return SDValue();
6865
6866       // Compute which value this mask is pointing at.
6867       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6868
6869       // Compute which of the two target values this index should be assigned
6870       // to. This reflects whether the high elements are remaining or the low
6871       // elements are remaining.
6872       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6873
6874       // Either set up this value if we've not encountered it before, or check
6875       // that it remains consistent.
6876       if (!TargetV)
6877         TargetV = MaskV;
6878       else if (TargetV != MaskV)
6879         // This may be a rotation, but it pulls from the inputs in some
6880         // unsupported interleaving.
6881         return SDValue();
6882     }
6883   }
6884
6885   // Check that we successfully analyzed the mask, and normalize the results.
6886   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6887   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6888   if (!Lo)
6889     Lo = Hi;
6890   else if (!Hi)
6891     Hi = Lo;
6892
6893   // The actual rotate instruction rotates bytes, so we need to scale the
6894   // rotation based on how many bytes are in the vector lane.
6895   int Scale = 16 / NumLaneElts;
6896
6897   // SSSE3 targets can use the palignr instruction.
6898   if (Subtarget->hasSSSE3()) {
6899     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6900     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6901     Lo = DAG.getBitcast(AlignVT, Lo);
6902     Hi = DAG.getBitcast(AlignVT, Hi);
6903
6904     return DAG.getBitcast(
6905         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6906                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6907   }
6908
6909   assert(VT.getSizeInBits() == 128 &&
6910          "Rotate-based lowering only supports 128-bit lowering!");
6911   assert(Mask.size() <= 16 &&
6912          "Can shuffle at most 16 bytes in a 128-bit vector!");
6913
6914   // Default SSE2 implementation
6915   int LoByteShift = 16 - Rotation * Scale;
6916   int HiByteShift = Rotation * Scale;
6917
6918   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6919   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6920   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6921
6922   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6923                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6924   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6925                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6926   return DAG.getBitcast(VT,
6927                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6928 }
6929
6930 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6931 ///
6932 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6933 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6934 /// matches elements from one of the input vectors shuffled to the left or
6935 /// right with zeroable elements 'shifted in'. It handles both the strictly
6936 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6937 /// quad word lane.
6938 ///
6939 /// PSHL : (little-endian) left bit shift.
6940 /// [ zz, 0, zz,  2 ]
6941 /// [ -1, 4, zz, -1 ]
6942 /// PSRL : (little-endian) right bit shift.
6943 /// [  1, zz,  3, zz]
6944 /// [ -1, -1,  7, zz]
6945 /// PSLLDQ : (little-endian) left byte shift
6946 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6947 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6948 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6949 /// PSRLDQ : (little-endian) right byte shift
6950 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6951 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6952 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6953 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6954                                          SDValue V2, ArrayRef<int> Mask,
6955                                          SelectionDAG &DAG) {
6956   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6957
6958   int Size = Mask.size();
6959   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6960
6961   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6962     for (int i = 0; i < Size; i += Scale)
6963       for (int j = 0; j < Shift; ++j)
6964         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6965           return false;
6966
6967     return true;
6968   };
6969
6970   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6971     for (int i = 0; i != Size; i += Scale) {
6972       unsigned Pos = Left ? i + Shift : i;
6973       unsigned Low = Left ? i : i + Shift;
6974       unsigned Len = Scale - Shift;
6975       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6976                                       Low + (V == V1 ? 0 : Size)))
6977         return SDValue();
6978     }
6979
6980     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6981     bool ByteShift = ShiftEltBits > 64;
6982     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6983                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6984     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6985
6986     // Normalize the scale for byte shifts to still produce an i64 element
6987     // type.
6988     Scale = ByteShift ? Scale / 2 : Scale;
6989
6990     // We need to round trip through the appropriate type for the shift.
6991     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6992     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6993     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6994            "Illegal integer vector type");
6995     V = DAG.getBitcast(ShiftVT, V);
6996
6997     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6998                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6999     return DAG.getBitcast(VT, V);
7000   };
7001
7002   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7003   // keep doubling the size of the integer elements up to that. We can
7004   // then shift the elements of the integer vector by whole multiples of
7005   // their width within the elements of the larger integer vector. Test each
7006   // multiple to see if we can find a match with the moved element indices
7007   // and that the shifted in elements are all zeroable.
7008   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7009     for (int Shift = 1; Shift != Scale; ++Shift)
7010       for (bool Left : {true, false})
7011         if (CheckZeros(Shift, Scale, Left))
7012           for (SDValue V : {V1, V2})
7013             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7014               return Match;
7015
7016   // no match
7017   return SDValue();
7018 }
7019
7020 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7021 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7022                                            SDValue V2, ArrayRef<int> Mask,
7023                                            SelectionDAG &DAG) {
7024   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7025   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7026
7027   int Size = Mask.size();
7028   int HalfSize = Size / 2;
7029   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7030
7031   // Upper half must be undefined.
7032   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7033     return SDValue();
7034
7035   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7036   // Remainder of lower half result is zero and upper half is all undef.
7037   auto LowerAsEXTRQ = [&]() {
7038     // Determine the extraction length from the part of the
7039     // lower half that isn't zeroable.
7040     int Len = HalfSize;
7041     for (; Len >= 0; --Len)
7042       if (!Zeroable[Len - 1])
7043         break;
7044     assert(Len > 0 && "Zeroable shuffle mask");
7045
7046     // Attempt to match first Len sequential elements from the lower half.
7047     SDValue Src;
7048     int Idx = -1;
7049     for (int i = 0; i != Len; ++i) {
7050       int M = Mask[i];
7051       if (M < 0)
7052         continue;
7053       SDValue &V = (M < Size ? V1 : V2);
7054       M = M % Size;
7055
7056       // All mask elements must be in the lower half.
7057       if (M > HalfSize)
7058         return SDValue();
7059
7060       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7061         Src = V;
7062         Idx = M - i;
7063         continue;
7064       }
7065       return SDValue();
7066     }
7067
7068     if (Idx < 0)
7069       return SDValue();
7070
7071     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7072     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7073     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7074     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7075                        DAG.getConstant(BitLen, DL, MVT::i8),
7076                        DAG.getConstant(BitIdx, DL, MVT::i8));
7077   };
7078
7079   if (SDValue ExtrQ = LowerAsEXTRQ())
7080     return ExtrQ;
7081
7082   // INSERTQ: Extract lowest Len elements from lower half of second source and
7083   // insert over first source, starting at Idx.
7084   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7085   auto LowerAsInsertQ = [&]() {
7086     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7087       SDValue Base;
7088
7089       // Attempt to match first source from mask before insertion point.
7090       if (isUndefInRange(Mask, 0, Idx)) {
7091         /* EMPTY */
7092       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7093         Base = V1;
7094       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7095         Base = V2;
7096       } else {
7097         continue;
7098       }
7099
7100       // Extend the extraction length looking to match both the insertion of
7101       // the second source and the remaining elements of the first.
7102       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7103         SDValue Insert;
7104         int Len = Hi - Idx;
7105
7106         // Match insertion.
7107         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7108           Insert = V1;
7109         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7110           Insert = V2;
7111         } else {
7112           continue;
7113         }
7114
7115         // Match the remaining elements of the lower half.
7116         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7117           /* EMPTY */
7118         } else if ((!Base || (Base == V1)) &&
7119                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7120           Base = V1;
7121         } else if ((!Base || (Base == V2)) &&
7122                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7123                                               Size + Hi)) {
7124           Base = V2;
7125         } else {
7126           continue;
7127         }
7128
7129         // We may not have a base (first source) - this can safely be undefined.
7130         if (!Base)
7131           Base = DAG.getUNDEF(VT);
7132
7133         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7134         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7135         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7136                            DAG.getConstant(BitLen, DL, MVT::i8),
7137                            DAG.getConstant(BitIdx, DL, MVT::i8));
7138       }
7139     }
7140
7141     return SDValue();
7142   };
7143
7144   if (SDValue InsertQ = LowerAsInsertQ())
7145     return InsertQ;
7146
7147   return SDValue();
7148 }
7149
7150 /// \brief Lower a vector shuffle as a zero or any extension.
7151 ///
7152 /// Given a specific number of elements, element bit width, and extension
7153 /// stride, produce either a zero or any extension based on the available
7154 /// features of the subtarget.
7155 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7156     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7157     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7158   assert(Scale > 1 && "Need a scale to extend.");
7159   int NumElements = VT.getVectorNumElements();
7160   int EltBits = VT.getScalarSizeInBits();
7161   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7162          "Only 8, 16, and 32 bit elements can be extended.");
7163   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7164
7165   // Found a valid zext mask! Try various lowering strategies based on the
7166   // input type and available ISA extensions.
7167   if (Subtarget->hasSSE41()) {
7168     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7169                                  NumElements / Scale);
7170     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7171   }
7172
7173   // For any extends we can cheat for larger element sizes and use shuffle
7174   // instructions that can fold with a load and/or copy.
7175   if (AnyExt && EltBits == 32) {
7176     int PSHUFDMask[4] = {0, -1, 1, -1};
7177     return DAG.getBitcast(
7178         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7179                         DAG.getBitcast(MVT::v4i32, InputV),
7180                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7181   }
7182   if (AnyExt && EltBits == 16 && Scale > 2) {
7183     int PSHUFDMask[4] = {0, -1, 0, -1};
7184     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7185                          DAG.getBitcast(MVT::v4i32, InputV),
7186                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7187     int PSHUFHWMask[4] = {1, -1, -1, -1};
7188     return DAG.getBitcast(
7189         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7190                         DAG.getBitcast(MVT::v8i16, InputV),
7191                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7192   }
7193
7194   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7195   // to 64-bits.
7196   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7197     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7198     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7199
7200     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7201                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7202                                          DAG.getConstant(EltBits, DL, MVT::i8),
7203                                          DAG.getConstant(0, DL, MVT::i8)));
7204     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7205       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7206
7207     SDValue Hi =
7208         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7209                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7210                                 DAG.getConstant(EltBits, DL, MVT::i8),
7211                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7212     return DAG.getNode(ISD::BITCAST, DL, VT,
7213                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7214   }
7215
7216   // If this would require more than 2 unpack instructions to expand, use
7217   // pshufb when available. We can only use more than 2 unpack instructions
7218   // when zero extending i8 elements which also makes it easier to use pshufb.
7219   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7220     assert(NumElements == 16 && "Unexpected byte vector width!");
7221     SDValue PSHUFBMask[16];
7222     for (int i = 0; i < 16; ++i)
7223       PSHUFBMask[i] =
7224           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7225     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7226     return DAG.getBitcast(VT,
7227                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7228                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7229                                                   MVT::v16i8, PSHUFBMask)));
7230   }
7231
7232   // Otherwise emit a sequence of unpacks.
7233   do {
7234     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7235     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7236                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7237     InputV = DAG.getBitcast(InputVT, InputV);
7238     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7239     Scale /= 2;
7240     EltBits *= 2;
7241     NumElements /= 2;
7242   } while (Scale > 1);
7243   return DAG.getBitcast(VT, InputV);
7244 }
7245
7246 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7247 ///
7248 /// This routine will try to do everything in its power to cleverly lower
7249 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7250 /// check for the profitability of this lowering,  it tries to aggressively
7251 /// match this pattern. It will use all of the micro-architectural details it
7252 /// can to emit an efficient lowering. It handles both blends with all-zero
7253 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7254 /// masking out later).
7255 ///
7256 /// The reason we have dedicated lowering for zext-style shuffles is that they
7257 /// are both incredibly common and often quite performance sensitive.
7258 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7259     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7260     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7261   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7262
7263   int Bits = VT.getSizeInBits();
7264   int NumElements = VT.getVectorNumElements();
7265   assert(VT.getScalarSizeInBits() <= 32 &&
7266          "Exceeds 32-bit integer zero extension limit");
7267   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7268
7269   // Define a helper function to check a particular ext-scale and lower to it if
7270   // valid.
7271   auto Lower = [&](int Scale) -> SDValue {
7272     SDValue InputV;
7273     bool AnyExt = true;
7274     for (int i = 0; i < NumElements; ++i) {
7275       if (Mask[i] == -1)
7276         continue; // Valid anywhere but doesn't tell us anything.
7277       if (i % Scale != 0) {
7278         // Each of the extended elements need to be zeroable.
7279         if (!Zeroable[i])
7280           return SDValue();
7281
7282         // We no longer are in the anyext case.
7283         AnyExt = false;
7284         continue;
7285       }
7286
7287       // Each of the base elements needs to be consecutive indices into the
7288       // same input vector.
7289       SDValue V = Mask[i] < NumElements ? V1 : V2;
7290       if (!InputV)
7291         InputV = V;
7292       else if (InputV != V)
7293         return SDValue(); // Flip-flopping inputs.
7294
7295       if (Mask[i] % NumElements != i / Scale)
7296         return SDValue(); // Non-consecutive strided elements.
7297     }
7298
7299     // If we fail to find an input, we have a zero-shuffle which should always
7300     // have already been handled.
7301     // FIXME: Maybe handle this here in case during blending we end up with one?
7302     if (!InputV)
7303       return SDValue();
7304
7305     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7306         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7307   };
7308
7309   // The widest scale possible for extending is to a 64-bit integer.
7310   assert(Bits % 64 == 0 &&
7311          "The number of bits in a vector must be divisible by 64 on x86!");
7312   int NumExtElements = Bits / 64;
7313
7314   // Each iteration, try extending the elements half as much, but into twice as
7315   // many elements.
7316   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7317     assert(NumElements % NumExtElements == 0 &&
7318            "The input vector size must be divisible by the extended size.");
7319     if (SDValue V = Lower(NumElements / NumExtElements))
7320       return V;
7321   }
7322
7323   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7324   if (Bits != 128)
7325     return SDValue();
7326
7327   // Returns one of the source operands if the shuffle can be reduced to a
7328   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7329   auto CanZExtLowHalf = [&]() {
7330     for (int i = NumElements / 2; i != NumElements; ++i)
7331       if (!Zeroable[i])
7332         return SDValue();
7333     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7334       return V1;
7335     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7336       return V2;
7337     return SDValue();
7338   };
7339
7340   if (SDValue V = CanZExtLowHalf()) {
7341     V = DAG.getBitcast(MVT::v2i64, V);
7342     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7343     return DAG.getBitcast(VT, V);
7344   }
7345
7346   // No viable ext lowering found.
7347   return SDValue();
7348 }
7349
7350 /// \brief Try to get a scalar value for a specific element of a vector.
7351 ///
7352 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7353 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7354                                               SelectionDAG &DAG) {
7355   MVT VT = V.getSimpleValueType();
7356   MVT EltVT = VT.getVectorElementType();
7357   while (V.getOpcode() == ISD::BITCAST)
7358     V = V.getOperand(0);
7359   // If the bitcasts shift the element size, we can't extract an equivalent
7360   // element from it.
7361   MVT NewVT = V.getSimpleValueType();
7362   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7363     return SDValue();
7364
7365   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7366       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7367     // Ensure the scalar operand is the same size as the destination.
7368     // FIXME: Add support for scalar truncation where possible.
7369     SDValue S = V.getOperand(Idx);
7370     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7371       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7372   }
7373
7374   return SDValue();
7375 }
7376
7377 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7378 ///
7379 /// This is particularly important because the set of instructions varies
7380 /// significantly based on whether the operand is a load or not.
7381 static bool isShuffleFoldableLoad(SDValue V) {
7382   while (V.getOpcode() == ISD::BITCAST)
7383     V = V.getOperand(0);
7384
7385   return ISD::isNON_EXTLoad(V.getNode());
7386 }
7387
7388 /// \brief Try to lower insertion of a single element into a zero vector.
7389 ///
7390 /// This is a common pattern that we have especially efficient patterns to lower
7391 /// across all subtarget feature sets.
7392 static SDValue lowerVectorShuffleAsElementInsertion(
7393     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7394     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7395   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7396   MVT ExtVT = VT;
7397   MVT EltVT = VT.getVectorElementType();
7398
7399   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7400                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7401                 Mask.begin();
7402   bool IsV1Zeroable = true;
7403   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7404     if (i != V2Index && !Zeroable[i]) {
7405       IsV1Zeroable = false;
7406       break;
7407     }
7408
7409   // Check for a single input from a SCALAR_TO_VECTOR node.
7410   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7411   // all the smarts here sunk into that routine. However, the current
7412   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7413   // vector shuffle lowering is dead.
7414   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7415                                                DAG);
7416   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7417     // We need to zext the scalar if it is smaller than an i32.
7418     V2S = DAG.getBitcast(EltVT, V2S);
7419     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7420       // Using zext to expand a narrow element won't work for non-zero
7421       // insertions.
7422       if (!IsV1Zeroable)
7423         return SDValue();
7424
7425       // Zero-extend directly to i32.
7426       ExtVT = MVT::v4i32;
7427       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7428     }
7429     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7430   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7431              EltVT == MVT::i16) {
7432     // Either not inserting from the low element of the input or the input
7433     // element size is too small to use VZEXT_MOVL to clear the high bits.
7434     return SDValue();
7435   }
7436
7437   if (!IsV1Zeroable) {
7438     // If V1 can't be treated as a zero vector we have fewer options to lower
7439     // this. We can't support integer vectors or non-zero targets cheaply, and
7440     // the V1 elements can't be permuted in any way.
7441     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7442     if (!VT.isFloatingPoint() || V2Index != 0)
7443       return SDValue();
7444     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7445     V1Mask[V2Index] = -1;
7446     if (!isNoopShuffleMask(V1Mask))
7447       return SDValue();
7448     // This is essentially a special case blend operation, but if we have
7449     // general purpose blend operations, they are always faster. Bail and let
7450     // the rest of the lowering handle these as blends.
7451     if (Subtarget->hasSSE41())
7452       return SDValue();
7453
7454     // Otherwise, use MOVSD or MOVSS.
7455     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7456            "Only two types of floating point element types to handle!");
7457     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7458                        ExtVT, V1, V2);
7459   }
7460
7461   // This lowering only works for the low element with floating point vectors.
7462   if (VT.isFloatingPoint() && V2Index != 0)
7463     return SDValue();
7464
7465   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7466   if (ExtVT != VT)
7467     V2 = DAG.getBitcast(VT, V2);
7468
7469   if (V2Index != 0) {
7470     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7471     // the desired position. Otherwise it is more efficient to do a vector
7472     // shift left. We know that we can do a vector shift left because all
7473     // the inputs are zero.
7474     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7475       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7476       V2Shuffle[V2Index] = 0;
7477       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7478     } else {
7479       V2 = DAG.getBitcast(MVT::v2i64, V2);
7480       V2 = DAG.getNode(
7481           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7482           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7483                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7484                               DAG.getDataLayout(), VT)));
7485       V2 = DAG.getBitcast(VT, V2);
7486     }
7487   }
7488   return V2;
7489 }
7490
7491 /// \brief Try to lower broadcast of a single element.
7492 ///
7493 /// For convenience, this code also bundles all of the subtarget feature set
7494 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7495 /// a convenient way to factor it out.
7496 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7497                                              ArrayRef<int> Mask,
7498                                              const X86Subtarget *Subtarget,
7499                                              SelectionDAG &DAG) {
7500   if (!Subtarget->hasAVX())
7501     return SDValue();
7502   if (VT.isInteger() && !Subtarget->hasAVX2())
7503     return SDValue();
7504
7505   // Check that the mask is a broadcast.
7506   int BroadcastIdx = -1;
7507   for (int M : Mask)
7508     if (M >= 0 && BroadcastIdx == -1)
7509       BroadcastIdx = M;
7510     else if (M >= 0 && M != BroadcastIdx)
7511       return SDValue();
7512
7513   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7514                                             "a sorted mask where the broadcast "
7515                                             "comes from V1.");
7516
7517   // Go up the chain of (vector) values to find a scalar load that we can
7518   // combine with the broadcast.
7519   for (;;) {
7520     switch (V.getOpcode()) {
7521     case ISD::CONCAT_VECTORS: {
7522       int OperandSize = Mask.size() / V.getNumOperands();
7523       V = V.getOperand(BroadcastIdx / OperandSize);
7524       BroadcastIdx %= OperandSize;
7525       continue;
7526     }
7527
7528     case ISD::INSERT_SUBVECTOR: {
7529       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7530       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7531       if (!ConstantIdx)
7532         break;
7533
7534       int BeginIdx = (int)ConstantIdx->getZExtValue();
7535       int EndIdx =
7536           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7537       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7538         BroadcastIdx -= BeginIdx;
7539         V = VInner;
7540       } else {
7541         V = VOuter;
7542       }
7543       continue;
7544     }
7545     }
7546     break;
7547   }
7548
7549   // Check if this is a broadcast of a scalar. We special case lowering
7550   // for scalars so that we can more effectively fold with loads.
7551   // First, look through bitcast: if the original value has a larger element
7552   // type than the shuffle, the broadcast element is in essence truncated.
7553   // Make that explicit to ease folding.
7554   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7555     EVT EltVT = VT.getVectorElementType();
7556     SDValue V0 = V.getOperand(0);
7557     EVT V0VT = V0.getValueType();
7558
7559     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7560         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7561          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7562       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7563       BroadcastIdx = 0;
7564     }
7565   }
7566
7567   // Also check the simpler case, where we can directly reuse the scalar.
7568   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7569       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7570     V = V.getOperand(BroadcastIdx);
7571
7572     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7573     // Only AVX2 has register broadcasts.
7574     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7575       return SDValue();
7576   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7577     // We can't broadcast from a vector register without AVX2, and we can only
7578     // broadcast from the zero-element of a vector register.
7579     return SDValue();
7580   }
7581
7582   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7583 }
7584
7585 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7586 // INSERTPS when the V1 elements are already in the correct locations
7587 // because otherwise we can just always use two SHUFPS instructions which
7588 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7589 // perform INSERTPS if a single V1 element is out of place and all V2
7590 // elements are zeroable.
7591 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7592                                             ArrayRef<int> Mask,
7593                                             SelectionDAG &DAG) {
7594   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7595   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7596   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7597   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7598
7599   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7600
7601   unsigned ZMask = 0;
7602   int V1DstIndex = -1;
7603   int V2DstIndex = -1;
7604   bool V1UsedInPlace = false;
7605
7606   for (int i = 0; i < 4; ++i) {
7607     // Synthesize a zero mask from the zeroable elements (includes undefs).
7608     if (Zeroable[i]) {
7609       ZMask |= 1 << i;
7610       continue;
7611     }
7612
7613     // Flag if we use any V1 inputs in place.
7614     if (i == Mask[i]) {
7615       V1UsedInPlace = true;
7616       continue;
7617     }
7618
7619     // We can only insert a single non-zeroable element.
7620     if (V1DstIndex != -1 || V2DstIndex != -1)
7621       return SDValue();
7622
7623     if (Mask[i] < 4) {
7624       // V1 input out of place for insertion.
7625       V1DstIndex = i;
7626     } else {
7627       // V2 input for insertion.
7628       V2DstIndex = i;
7629     }
7630   }
7631
7632   // Don't bother if we have no (non-zeroable) element for insertion.
7633   if (V1DstIndex == -1 && V2DstIndex == -1)
7634     return SDValue();
7635
7636   // Determine element insertion src/dst indices. The src index is from the
7637   // start of the inserted vector, not the start of the concatenated vector.
7638   unsigned V2SrcIndex = 0;
7639   if (V1DstIndex != -1) {
7640     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7641     // and don't use the original V2 at all.
7642     V2SrcIndex = Mask[V1DstIndex];
7643     V2DstIndex = V1DstIndex;
7644     V2 = V1;
7645   } else {
7646     V2SrcIndex = Mask[V2DstIndex] - 4;
7647   }
7648
7649   // If no V1 inputs are used in place, then the result is created only from
7650   // the zero mask and the V2 insertion - so remove V1 dependency.
7651   if (!V1UsedInPlace)
7652     V1 = DAG.getUNDEF(MVT::v4f32);
7653
7654   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7655   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7656
7657   // Insert the V2 element into the desired position.
7658   SDLoc DL(Op);
7659   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7660                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7661 }
7662
7663 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7664 /// UNPCK instruction.
7665 ///
7666 /// This specifically targets cases where we end up with alternating between
7667 /// the two inputs, and so can permute them into something that feeds a single
7668 /// UNPCK instruction. Note that this routine only targets integer vectors
7669 /// because for floating point vectors we have a generalized SHUFPS lowering
7670 /// strategy that handles everything that doesn't *exactly* match an unpack,
7671 /// making this clever lowering unnecessary.
7672 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7673                                           SDValue V2, ArrayRef<int> Mask,
7674                                           SelectionDAG &DAG) {
7675   assert(!VT.isFloatingPoint() &&
7676          "This routine only supports integer vectors.");
7677   assert(!isSingleInputShuffleMask(Mask) &&
7678          "This routine should only be used when blending two inputs.");
7679   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7680
7681   int Size = Mask.size();
7682
7683   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7684     return M >= 0 && M % Size < Size / 2;
7685   });
7686   int NumHiInputs = std::count_if(
7687       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7688
7689   bool UnpackLo = NumLoInputs >= NumHiInputs;
7690
7691   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7692     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7693     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7694
7695     for (int i = 0; i < Size; ++i) {
7696       if (Mask[i] < 0)
7697         continue;
7698
7699       // Each element of the unpack contains Scale elements from this mask.
7700       int UnpackIdx = i / Scale;
7701
7702       // We only handle the case where V1 feeds the first slots of the unpack.
7703       // We rely on canonicalization to ensure this is the case.
7704       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7705         return SDValue();
7706
7707       // Setup the mask for this input. The indexing is tricky as we have to
7708       // handle the unpack stride.
7709       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7710       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7711           Mask[i] % Size;
7712     }
7713
7714     // If we will have to shuffle both inputs to use the unpack, check whether
7715     // we can just unpack first and shuffle the result. If so, skip this unpack.
7716     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7717         !isNoopShuffleMask(V2Mask))
7718       return SDValue();
7719
7720     // Shuffle the inputs into place.
7721     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7722     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7723
7724     // Cast the inputs to the type we will use to unpack them.
7725     V1 = DAG.getBitcast(UnpackVT, V1);
7726     V2 = DAG.getBitcast(UnpackVT, V2);
7727
7728     // Unpack the inputs and cast the result back to the desired type.
7729     return DAG.getBitcast(
7730         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7731                         UnpackVT, V1, V2));
7732   };
7733
7734   // We try each unpack from the largest to the smallest to try and find one
7735   // that fits this mask.
7736   int OrigNumElements = VT.getVectorNumElements();
7737   int OrigScalarSize = VT.getScalarSizeInBits();
7738   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7739     int Scale = ScalarSize / OrigScalarSize;
7740     int NumElements = OrigNumElements / Scale;
7741     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7742     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7743       return Unpack;
7744   }
7745
7746   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7747   // initial unpack.
7748   if (NumLoInputs == 0 || NumHiInputs == 0) {
7749     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7750            "We have to have *some* inputs!");
7751     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7752
7753     // FIXME: We could consider the total complexity of the permute of each
7754     // possible unpacking. Or at the least we should consider how many
7755     // half-crossings are created.
7756     // FIXME: We could consider commuting the unpacks.
7757
7758     SmallVector<int, 32> PermMask;
7759     PermMask.assign(Size, -1);
7760     for (int i = 0; i < Size; ++i) {
7761       if (Mask[i] < 0)
7762         continue;
7763
7764       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7765
7766       PermMask[i] =
7767           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7768     }
7769     return DAG.getVectorShuffle(
7770         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7771                             DL, VT, V1, V2),
7772         DAG.getUNDEF(VT), PermMask);
7773   }
7774
7775   return SDValue();
7776 }
7777
7778 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7779 ///
7780 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7781 /// support for floating point shuffles but not integer shuffles. These
7782 /// instructions will incur a domain crossing penalty on some chips though so
7783 /// it is better to avoid lowering through this for integer vectors where
7784 /// possible.
7785 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7786                                        const X86Subtarget *Subtarget,
7787                                        SelectionDAG &DAG) {
7788   SDLoc DL(Op);
7789   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7790   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7791   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7793   ArrayRef<int> Mask = SVOp->getMask();
7794   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7795
7796   if (isSingleInputShuffleMask(Mask)) {
7797     // Use low duplicate instructions for masks that match their pattern.
7798     if (Subtarget->hasSSE3())
7799       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7800         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7801
7802     // Straight shuffle of a single input vector. Simulate this by using the
7803     // single input as both of the "inputs" to this instruction..
7804     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7805
7806     if (Subtarget->hasAVX()) {
7807       // If we have AVX, we can use VPERMILPS which will allow folding a load
7808       // into the shuffle.
7809       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7810                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7811     }
7812
7813     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7814                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7815   }
7816   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7817   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7818
7819   // If we have a single input, insert that into V1 if we can do so cheaply.
7820   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7821     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7822             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7823       return Insertion;
7824     // Try inverting the insertion since for v2 masks it is easy to do and we
7825     // can't reliably sort the mask one way or the other.
7826     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7827                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7828     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7829             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7830       return Insertion;
7831   }
7832
7833   // Try to use one of the special instruction patterns to handle two common
7834   // blend patterns if a zero-blend above didn't work.
7835   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7836       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7837     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7838       // We can either use a special instruction to load over the low double or
7839       // to move just the low double.
7840       return DAG.getNode(
7841           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7842           DL, MVT::v2f64, V2,
7843           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7844
7845   if (Subtarget->hasSSE41())
7846     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7847                                                   Subtarget, DAG))
7848       return Blend;
7849
7850   // Use dedicated unpack instructions for masks that match their pattern.
7851   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7852     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7853   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7854     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7855
7856   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7857   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7858                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7859 }
7860
7861 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7862 ///
7863 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7864 /// the integer unit to minimize domain crossing penalties. However, for blends
7865 /// it falls back to the floating point shuffle operation with appropriate bit
7866 /// casting.
7867 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7868                                        const X86Subtarget *Subtarget,
7869                                        SelectionDAG &DAG) {
7870   SDLoc DL(Op);
7871   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7872   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7873   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7875   ArrayRef<int> Mask = SVOp->getMask();
7876   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7877
7878   if (isSingleInputShuffleMask(Mask)) {
7879     // Check for being able to broadcast a single element.
7880     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7881                                                           Mask, Subtarget, DAG))
7882       return Broadcast;
7883
7884     // Straight shuffle of a single input vector. For everything from SSE2
7885     // onward this has a single fast instruction with no scary immediates.
7886     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7887     V1 = DAG.getBitcast(MVT::v4i32, V1);
7888     int WidenedMask[4] = {
7889         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7890         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7891     return DAG.getBitcast(
7892         MVT::v2i64,
7893         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7894                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7895   }
7896   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7897   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7898   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7899   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7900
7901   // If we have a blend of two PACKUS operations an the blend aligns with the
7902   // low and half halves, we can just merge the PACKUS operations. This is
7903   // particularly important as it lets us merge shuffles that this routine itself
7904   // creates.
7905   auto GetPackNode = [](SDValue V) {
7906     while (V.getOpcode() == ISD::BITCAST)
7907       V = V.getOperand(0);
7908
7909     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7910   };
7911   if (SDValue V1Pack = GetPackNode(V1))
7912     if (SDValue V2Pack = GetPackNode(V2))
7913       return DAG.getBitcast(MVT::v2i64,
7914                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7915                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7916                                                      : V1Pack.getOperand(1),
7917                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7918                                                      : V2Pack.getOperand(1)));
7919
7920   // Try to use shift instructions.
7921   if (SDValue Shift =
7922           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7923     return Shift;
7924
7925   // When loading a scalar and then shuffling it into a vector we can often do
7926   // the insertion cheaply.
7927   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7928           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7929     return Insertion;
7930   // Try inverting the insertion since for v2 masks it is easy to do and we
7931   // can't reliably sort the mask one way or the other.
7932   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7933   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7934           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7935     return Insertion;
7936
7937   // We have different paths for blend lowering, but they all must use the
7938   // *exact* same predicate.
7939   bool IsBlendSupported = Subtarget->hasSSE41();
7940   if (IsBlendSupported)
7941     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7942                                                   Subtarget, DAG))
7943       return Blend;
7944
7945   // Use dedicated unpack instructions for masks that match their pattern.
7946   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7947     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7948   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7949     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7950
7951   // Try to use byte rotation instructions.
7952   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7953   if (Subtarget->hasSSSE3())
7954     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7955             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7956       return Rotate;
7957
7958   // If we have direct support for blends, we should lower by decomposing into
7959   // a permute. That will be faster than the domain cross.
7960   if (IsBlendSupported)
7961     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7962                                                       Mask, DAG);
7963
7964   // We implement this with SHUFPD which is pretty lame because it will likely
7965   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7966   // However, all the alternatives are still more cycles and newer chips don't
7967   // have this problem. It would be really nice if x86 had better shuffles here.
7968   V1 = DAG.getBitcast(MVT::v2f64, V1);
7969   V2 = DAG.getBitcast(MVT::v2f64, V2);
7970   return DAG.getBitcast(MVT::v2i64,
7971                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7972 }
7973
7974 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7975 ///
7976 /// This is used to disable more specialized lowerings when the shufps lowering
7977 /// will happen to be efficient.
7978 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7979   // This routine only handles 128-bit shufps.
7980   assert(Mask.size() == 4 && "Unsupported mask size!");
7981
7982   // To lower with a single SHUFPS we need to have the low half and high half
7983   // each requiring a single input.
7984   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7985     return false;
7986   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7987     return false;
7988
7989   return true;
7990 }
7991
7992 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7993 ///
7994 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7995 /// It makes no assumptions about whether this is the *best* lowering, it simply
7996 /// uses it.
7997 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7998                                             ArrayRef<int> Mask, SDValue V1,
7999                                             SDValue V2, SelectionDAG &DAG) {
8000   SDValue LowV = V1, HighV = V2;
8001   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8002
8003   int NumV2Elements =
8004       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8005
8006   if (NumV2Elements == 1) {
8007     int V2Index =
8008         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8009         Mask.begin();
8010
8011     // Compute the index adjacent to V2Index and in the same half by toggling
8012     // the low bit.
8013     int V2AdjIndex = V2Index ^ 1;
8014
8015     if (Mask[V2AdjIndex] == -1) {
8016       // Handles all the cases where we have a single V2 element and an undef.
8017       // This will only ever happen in the high lanes because we commute the
8018       // vector otherwise.
8019       if (V2Index < 2)
8020         std::swap(LowV, HighV);
8021       NewMask[V2Index] -= 4;
8022     } else {
8023       // Handle the case where the V2 element ends up adjacent to a V1 element.
8024       // To make this work, blend them together as the first step.
8025       int V1Index = V2AdjIndex;
8026       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8027       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8028                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8029
8030       // Now proceed to reconstruct the final blend as we have the necessary
8031       // high or low half formed.
8032       if (V2Index < 2) {
8033         LowV = V2;
8034         HighV = V1;
8035       } else {
8036         HighV = V2;
8037       }
8038       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8039       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8040     }
8041   } else if (NumV2Elements == 2) {
8042     if (Mask[0] < 4 && Mask[1] < 4) {
8043       // Handle the easy case where we have V1 in the low lanes and V2 in the
8044       // high lanes.
8045       NewMask[2] -= 4;
8046       NewMask[3] -= 4;
8047     } else if (Mask[2] < 4 && Mask[3] < 4) {
8048       // We also handle the reversed case because this utility may get called
8049       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8050       // arrange things in the right direction.
8051       NewMask[0] -= 4;
8052       NewMask[1] -= 4;
8053       HighV = V1;
8054       LowV = V2;
8055     } else {
8056       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8057       // trying to place elements directly, just blend them and set up the final
8058       // shuffle to place them.
8059
8060       // The first two blend mask elements are for V1, the second two are for
8061       // V2.
8062       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8063                           Mask[2] < 4 ? Mask[2] : Mask[3],
8064                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8065                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8066       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8067                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8068
8069       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8070       // a blend.
8071       LowV = HighV = V1;
8072       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8073       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8074       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8075       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8076     }
8077   }
8078   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8079                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8080 }
8081
8082 /// \brief Lower 4-lane 32-bit floating point shuffles.
8083 ///
8084 /// Uses instructions exclusively from the floating point unit to minimize
8085 /// domain crossing penalties, as these are sufficient to implement all v4f32
8086 /// shuffles.
8087 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8088                                        const X86Subtarget *Subtarget,
8089                                        SelectionDAG &DAG) {
8090   SDLoc DL(Op);
8091   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8092   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8093   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8095   ArrayRef<int> Mask = SVOp->getMask();
8096   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8097
8098   int NumV2Elements =
8099       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8100
8101   if (NumV2Elements == 0) {
8102     // Check for being able to broadcast a single element.
8103     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8104                                                           Mask, Subtarget, DAG))
8105       return Broadcast;
8106
8107     // Use even/odd duplicate instructions for masks that match their pattern.
8108     if (Subtarget->hasSSE3()) {
8109       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8110         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8111       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8112         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8113     }
8114
8115     if (Subtarget->hasAVX()) {
8116       // If we have AVX, we can use VPERMILPS which will allow folding a load
8117       // into the shuffle.
8118       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8119                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8120     }
8121
8122     // Otherwise, use a straight shuffle of a single input vector. We pass the
8123     // input vector to both operands to simulate this with a SHUFPS.
8124     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8125                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8126   }
8127
8128   // There are special ways we can lower some single-element blends. However, we
8129   // have custom ways we can lower more complex single-element blends below that
8130   // we defer to if both this and BLENDPS fail to match, so restrict this to
8131   // when the V2 input is targeting element 0 of the mask -- that is the fast
8132   // case here.
8133   if (NumV2Elements == 1 && Mask[0] >= 4)
8134     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8135                                                          Mask, Subtarget, DAG))
8136       return V;
8137
8138   if (Subtarget->hasSSE41()) {
8139     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8140                                                   Subtarget, DAG))
8141       return Blend;
8142
8143     // Use INSERTPS if we can complete the shuffle efficiently.
8144     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8145       return V;
8146
8147     if (!isSingleSHUFPSMask(Mask))
8148       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8149               DL, MVT::v4f32, V1, V2, Mask, DAG))
8150         return BlendPerm;
8151   }
8152
8153   // Use dedicated unpack instructions for masks that match their pattern.
8154   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8155     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8156   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8157     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8158   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8159     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8160   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8161     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8162
8163   // Otherwise fall back to a SHUFPS lowering strategy.
8164   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8165 }
8166
8167 /// \brief Lower 4-lane i32 vector shuffles.
8168 ///
8169 /// We try to handle these with integer-domain shuffles where we can, but for
8170 /// blends we use the floating point domain blend instructions.
8171 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8172                                        const X86Subtarget *Subtarget,
8173                                        SelectionDAG &DAG) {
8174   SDLoc DL(Op);
8175   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8176   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8177   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8178   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8179   ArrayRef<int> Mask = SVOp->getMask();
8180   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8181
8182   // Whenever we can lower this as a zext, that instruction is strictly faster
8183   // than any alternative. It also allows us to fold memory operands into the
8184   // shuffle in many cases.
8185   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8186                                                          Mask, Subtarget, DAG))
8187     return ZExt;
8188
8189   int NumV2Elements =
8190       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8191
8192   if (NumV2Elements == 0) {
8193     // Check for being able to broadcast a single element.
8194     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8195                                                           Mask, Subtarget, DAG))
8196       return Broadcast;
8197
8198     // Straight shuffle of a single input vector. For everything from SSE2
8199     // onward this has a single fast instruction with no scary immediates.
8200     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8201     // but we aren't actually going to use the UNPCK instruction because doing
8202     // so prevents folding a load into this instruction or making a copy.
8203     const int UnpackLoMask[] = {0, 0, 1, 1};
8204     const int UnpackHiMask[] = {2, 2, 3, 3};
8205     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8206       Mask = UnpackLoMask;
8207     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8208       Mask = UnpackHiMask;
8209
8210     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8211                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8212   }
8213
8214   // Try to use shift instructions.
8215   if (SDValue Shift =
8216           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8217     return Shift;
8218
8219   // There are special ways we can lower some single-element blends.
8220   if (NumV2Elements == 1)
8221     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8222                                                          Mask, Subtarget, DAG))
8223       return V;
8224
8225   // We have different paths for blend lowering, but they all must use the
8226   // *exact* same predicate.
8227   bool IsBlendSupported = Subtarget->hasSSE41();
8228   if (IsBlendSupported)
8229     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8230                                                   Subtarget, DAG))
8231       return Blend;
8232
8233   if (SDValue Masked =
8234           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8235     return Masked;
8236
8237   // Use dedicated unpack instructions for masks that match their pattern.
8238   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8239     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8240   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8241     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8242   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8243     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8244   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8245     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8246
8247   // Try to use byte rotation instructions.
8248   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8249   if (Subtarget->hasSSSE3())
8250     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8251             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8252       return Rotate;
8253
8254   // If we have direct support for blends, we should lower by decomposing into
8255   // a permute. That will be faster than the domain cross.
8256   if (IsBlendSupported)
8257     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8258                                                       Mask, DAG);
8259
8260   // Try to lower by permuting the inputs into an unpack instruction.
8261   if (SDValue Unpack =
8262           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8263     return Unpack;
8264
8265   // We implement this with SHUFPS because it can blend from two vectors.
8266   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8267   // up the inputs, bypassing domain shift penalties that we would encur if we
8268   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8269   // relevant.
8270   return DAG.getBitcast(
8271       MVT::v4i32,
8272       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8273                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8274 }
8275
8276 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8277 /// shuffle lowering, and the most complex part.
8278 ///
8279 /// The lowering strategy is to try to form pairs of input lanes which are
8280 /// targeted at the same half of the final vector, and then use a dword shuffle
8281 /// to place them onto the right half, and finally unpack the paired lanes into
8282 /// their final position.
8283 ///
8284 /// The exact breakdown of how to form these dword pairs and align them on the
8285 /// correct sides is really tricky. See the comments within the function for
8286 /// more of the details.
8287 ///
8288 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8289 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8290 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8291 /// vector, form the analogous 128-bit 8-element Mask.
8292 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8293     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8294     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8295   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8296   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8297
8298   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8299   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8300   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8301
8302   SmallVector<int, 4> LoInputs;
8303   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8304                [](int M) { return M >= 0; });
8305   std::sort(LoInputs.begin(), LoInputs.end());
8306   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8307   SmallVector<int, 4> HiInputs;
8308   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8309                [](int M) { return M >= 0; });
8310   std::sort(HiInputs.begin(), HiInputs.end());
8311   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8312   int NumLToL =
8313       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8314   int NumHToL = LoInputs.size() - NumLToL;
8315   int NumLToH =
8316       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8317   int NumHToH = HiInputs.size() - NumLToH;
8318   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8319   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8320   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8321   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8322
8323   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8324   // such inputs we can swap two of the dwords across the half mark and end up
8325   // with <=2 inputs to each half in each half. Once there, we can fall through
8326   // to the generic code below. For example:
8327   //
8328   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8329   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8330   //
8331   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8332   // and an existing 2-into-2 on the other half. In this case we may have to
8333   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8334   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8335   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8336   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8337   // half than the one we target for fixing) will be fixed when we re-enter this
8338   // path. We will also combine away any sequence of PSHUFD instructions that
8339   // result into a single instruction. Here is an example of the tricky case:
8340   //
8341   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8342   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8343   //
8344   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8345   //
8346   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8347   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8348   //
8349   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8350   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8351   //
8352   // The result is fine to be handled by the generic logic.
8353   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8354                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8355                           int AOffset, int BOffset) {
8356     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8357            "Must call this with A having 3 or 1 inputs from the A half.");
8358     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8359            "Must call this with B having 1 or 3 inputs from the B half.");
8360     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8361            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8362
8363     bool ThreeAInputs = AToAInputs.size() == 3;
8364
8365     // Compute the index of dword with only one word among the three inputs in
8366     // a half by taking the sum of the half with three inputs and subtracting
8367     // the sum of the actual three inputs. The difference is the remaining
8368     // slot.
8369     int ADWord, BDWord;
8370     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8371     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8372     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8373     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8374     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8375     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8376     int TripleNonInputIdx =
8377         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8378     TripleDWord = TripleNonInputIdx / 2;
8379
8380     // We use xor with one to compute the adjacent DWord to whichever one the
8381     // OneInput is in.
8382     OneInputDWord = (OneInput / 2) ^ 1;
8383
8384     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8385     // and BToA inputs. If there is also such a problem with the BToB and AToB
8386     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8387     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8388     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8389     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8390       // Compute how many inputs will be flipped by swapping these DWords. We
8391       // need
8392       // to balance this to ensure we don't form a 3-1 shuffle in the other
8393       // half.
8394       int NumFlippedAToBInputs =
8395           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8396           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8397       int NumFlippedBToBInputs =
8398           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8399           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8400       if ((NumFlippedAToBInputs == 1 &&
8401            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8402           (NumFlippedBToBInputs == 1 &&
8403            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8404         // We choose whether to fix the A half or B half based on whether that
8405         // half has zero flipped inputs. At zero, we may not be able to fix it
8406         // with that half. We also bias towards fixing the B half because that
8407         // will more commonly be the high half, and we have to bias one way.
8408         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8409                                                        ArrayRef<int> Inputs) {
8410           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8411           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8412                                          PinnedIdx ^ 1) != Inputs.end();
8413           // Determine whether the free index is in the flipped dword or the
8414           // unflipped dword based on where the pinned index is. We use this bit
8415           // in an xor to conditionally select the adjacent dword.
8416           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8417           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8418                                              FixFreeIdx) != Inputs.end();
8419           if (IsFixIdxInput == IsFixFreeIdxInput)
8420             FixFreeIdx += 1;
8421           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8422                                         FixFreeIdx) != Inputs.end();
8423           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8424                  "We need to be changing the number of flipped inputs!");
8425           int PSHUFHalfMask[] = {0, 1, 2, 3};
8426           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8427           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8428                           MVT::v8i16, V,
8429                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8430
8431           for (int &M : Mask)
8432             if (M != -1 && M == FixIdx)
8433               M = FixFreeIdx;
8434             else if (M != -1 && M == FixFreeIdx)
8435               M = FixIdx;
8436         };
8437         if (NumFlippedBToBInputs != 0) {
8438           int BPinnedIdx =
8439               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8440           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8441         } else {
8442           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8443           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8444           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8445         }
8446       }
8447     }
8448
8449     int PSHUFDMask[] = {0, 1, 2, 3};
8450     PSHUFDMask[ADWord] = BDWord;
8451     PSHUFDMask[BDWord] = ADWord;
8452     V = DAG.getBitcast(
8453         VT,
8454         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8455                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8456
8457     // Adjust the mask to match the new locations of A and B.
8458     for (int &M : Mask)
8459       if (M != -1 && M/2 == ADWord)
8460         M = 2 * BDWord + M % 2;
8461       else if (M != -1 && M/2 == BDWord)
8462         M = 2 * ADWord + M % 2;
8463
8464     // Recurse back into this routine to re-compute state now that this isn't
8465     // a 3 and 1 problem.
8466     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8467                                                      DAG);
8468   };
8469   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8470     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8471   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8472     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8473
8474   // At this point there are at most two inputs to the low and high halves from
8475   // each half. That means the inputs can always be grouped into dwords and
8476   // those dwords can then be moved to the correct half with a dword shuffle.
8477   // We use at most one low and one high word shuffle to collect these paired
8478   // inputs into dwords, and finally a dword shuffle to place them.
8479   int PSHUFLMask[4] = {-1, -1, -1, -1};
8480   int PSHUFHMask[4] = {-1, -1, -1, -1};
8481   int PSHUFDMask[4] = {-1, -1, -1, -1};
8482
8483   // First fix the masks for all the inputs that are staying in their
8484   // original halves. This will then dictate the targets of the cross-half
8485   // shuffles.
8486   auto fixInPlaceInputs =
8487       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8488                     MutableArrayRef<int> SourceHalfMask,
8489                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8490     if (InPlaceInputs.empty())
8491       return;
8492     if (InPlaceInputs.size() == 1) {
8493       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8494           InPlaceInputs[0] - HalfOffset;
8495       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8496       return;
8497     }
8498     if (IncomingInputs.empty()) {
8499       // Just fix all of the in place inputs.
8500       for (int Input : InPlaceInputs) {
8501         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8502         PSHUFDMask[Input / 2] = Input / 2;
8503       }
8504       return;
8505     }
8506
8507     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8508     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8509         InPlaceInputs[0] - HalfOffset;
8510     // Put the second input next to the first so that they are packed into
8511     // a dword. We find the adjacent index by toggling the low bit.
8512     int AdjIndex = InPlaceInputs[0] ^ 1;
8513     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8514     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8515     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8516   };
8517   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8518   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8519
8520   // Now gather the cross-half inputs and place them into a free dword of
8521   // their target half.
8522   // FIXME: This operation could almost certainly be simplified dramatically to
8523   // look more like the 3-1 fixing operation.
8524   auto moveInputsToRightHalf = [&PSHUFDMask](
8525       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8526       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8527       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8528       int DestOffset) {
8529     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8530       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8531     };
8532     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8533                                                int Word) {
8534       int LowWord = Word & ~1;
8535       int HighWord = Word | 1;
8536       return isWordClobbered(SourceHalfMask, LowWord) ||
8537              isWordClobbered(SourceHalfMask, HighWord);
8538     };
8539
8540     if (IncomingInputs.empty())
8541       return;
8542
8543     if (ExistingInputs.empty()) {
8544       // Map any dwords with inputs from them into the right half.
8545       for (int Input : IncomingInputs) {
8546         // If the source half mask maps over the inputs, turn those into
8547         // swaps and use the swapped lane.
8548         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8549           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8550             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8551                 Input - SourceOffset;
8552             // We have to swap the uses in our half mask in one sweep.
8553             for (int &M : HalfMask)
8554               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8555                 M = Input;
8556               else if (M == Input)
8557                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8558           } else {
8559             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8560                        Input - SourceOffset &&
8561                    "Previous placement doesn't match!");
8562           }
8563           // Note that this correctly re-maps both when we do a swap and when
8564           // we observe the other side of the swap above. We rely on that to
8565           // avoid swapping the members of the input list directly.
8566           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8567         }
8568
8569         // Map the input's dword into the correct half.
8570         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8571           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8572         else
8573           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8574                      Input / 2 &&
8575                  "Previous placement doesn't match!");
8576       }
8577
8578       // And just directly shift any other-half mask elements to be same-half
8579       // as we will have mirrored the dword containing the element into the
8580       // same position within that half.
8581       for (int &M : HalfMask)
8582         if (M >= SourceOffset && M < SourceOffset + 4) {
8583           M = M - SourceOffset + DestOffset;
8584           assert(M >= 0 && "This should never wrap below zero!");
8585         }
8586       return;
8587     }
8588
8589     // Ensure we have the input in a viable dword of its current half. This
8590     // is particularly tricky because the original position may be clobbered
8591     // by inputs being moved and *staying* in that half.
8592     if (IncomingInputs.size() == 1) {
8593       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8594         int InputFixed = std::find(std::begin(SourceHalfMask),
8595                                    std::end(SourceHalfMask), -1) -
8596                          std::begin(SourceHalfMask) + SourceOffset;
8597         SourceHalfMask[InputFixed - SourceOffset] =
8598             IncomingInputs[0] - SourceOffset;
8599         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8600                      InputFixed);
8601         IncomingInputs[0] = InputFixed;
8602       }
8603     } else if (IncomingInputs.size() == 2) {
8604       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8605           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8606         // We have two non-adjacent or clobbered inputs we need to extract from
8607         // the source half. To do this, we need to map them into some adjacent
8608         // dword slot in the source mask.
8609         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8610                               IncomingInputs[1] - SourceOffset};
8611
8612         // If there is a free slot in the source half mask adjacent to one of
8613         // the inputs, place the other input in it. We use (Index XOR 1) to
8614         // compute an adjacent index.
8615         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8616             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8617           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8618           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8619           InputsFixed[1] = InputsFixed[0] ^ 1;
8620         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8621                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8622           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8623           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8624           InputsFixed[0] = InputsFixed[1] ^ 1;
8625         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8626                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8627           // The two inputs are in the same DWord but it is clobbered and the
8628           // adjacent DWord isn't used at all. Move both inputs to the free
8629           // slot.
8630           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8631           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8632           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8633           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8634         } else {
8635           // The only way we hit this point is if there is no clobbering
8636           // (because there are no off-half inputs to this half) and there is no
8637           // free slot adjacent to one of the inputs. In this case, we have to
8638           // swap an input with a non-input.
8639           for (int i = 0; i < 4; ++i)
8640             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8641                    "We can't handle any clobbers here!");
8642           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8643                  "Cannot have adjacent inputs here!");
8644
8645           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8646           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8647
8648           // We also have to update the final source mask in this case because
8649           // it may need to undo the above swap.
8650           for (int &M : FinalSourceHalfMask)
8651             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8652               M = InputsFixed[1] + SourceOffset;
8653             else if (M == InputsFixed[1] + SourceOffset)
8654               M = (InputsFixed[0] ^ 1) + SourceOffset;
8655
8656           InputsFixed[1] = InputsFixed[0] ^ 1;
8657         }
8658
8659         // Point everything at the fixed inputs.
8660         for (int &M : HalfMask)
8661           if (M == IncomingInputs[0])
8662             M = InputsFixed[0] + SourceOffset;
8663           else if (M == IncomingInputs[1])
8664             M = InputsFixed[1] + SourceOffset;
8665
8666         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8667         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8668       }
8669     } else {
8670       llvm_unreachable("Unhandled input size!");
8671     }
8672
8673     // Now hoist the DWord down to the right half.
8674     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8675     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8676     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8677     for (int &M : HalfMask)
8678       for (int Input : IncomingInputs)
8679         if (M == Input)
8680           M = FreeDWord * 2 + Input % 2;
8681   };
8682   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8683                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8684   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8685                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8686
8687   // Now enact all the shuffles we've computed to move the inputs into their
8688   // target half.
8689   if (!isNoopShuffleMask(PSHUFLMask))
8690     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8691                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8692   if (!isNoopShuffleMask(PSHUFHMask))
8693     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8694                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8695   if (!isNoopShuffleMask(PSHUFDMask))
8696     V = DAG.getBitcast(
8697         VT,
8698         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8699                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8700
8701   // At this point, each half should contain all its inputs, and we can then
8702   // just shuffle them into their final position.
8703   assert(std::count_if(LoMask.begin(), LoMask.end(),
8704                        [](int M) { return M >= 4; }) == 0 &&
8705          "Failed to lift all the high half inputs to the low mask!");
8706   assert(std::count_if(HiMask.begin(), HiMask.end(),
8707                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8708          "Failed to lift all the low half inputs to the high mask!");
8709
8710   // Do a half shuffle for the low mask.
8711   if (!isNoopShuffleMask(LoMask))
8712     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8713                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8714
8715   // Do a half shuffle with the high mask after shifting its values down.
8716   for (int &M : HiMask)
8717     if (M >= 0)
8718       M -= 4;
8719   if (!isNoopShuffleMask(HiMask))
8720     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8721                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8722
8723   return V;
8724 }
8725
8726 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8727 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8728                                           SDValue V2, ArrayRef<int> Mask,
8729                                           SelectionDAG &DAG, bool &V1InUse,
8730                                           bool &V2InUse) {
8731   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8732   SDValue V1Mask[16];
8733   SDValue V2Mask[16];
8734   V1InUse = false;
8735   V2InUse = false;
8736
8737   int Size = Mask.size();
8738   int Scale = 16 / Size;
8739   for (int i = 0; i < 16; ++i) {
8740     if (Mask[i / Scale] == -1) {
8741       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8742     } else {
8743       const int ZeroMask = 0x80;
8744       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8745                                           : ZeroMask;
8746       int V2Idx = Mask[i / Scale] < Size
8747                       ? ZeroMask
8748                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8749       if (Zeroable[i / Scale])
8750         V1Idx = V2Idx = ZeroMask;
8751       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8752       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8753       V1InUse |= (ZeroMask != V1Idx);
8754       V2InUse |= (ZeroMask != V2Idx);
8755     }
8756   }
8757
8758   if (V1InUse)
8759     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8760                      DAG.getBitcast(MVT::v16i8, V1),
8761                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8762   if (V2InUse)
8763     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8764                      DAG.getBitcast(MVT::v16i8, V2),
8765                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8766
8767   // If we need shuffled inputs from both, blend the two.
8768   SDValue V;
8769   if (V1InUse && V2InUse)
8770     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8771   else
8772     V = V1InUse ? V1 : V2;
8773
8774   // Cast the result back to the correct type.
8775   return DAG.getBitcast(VT, V);
8776 }
8777
8778 /// \brief Generic lowering of 8-lane i16 shuffles.
8779 ///
8780 /// This handles both single-input shuffles and combined shuffle/blends with
8781 /// two inputs. The single input shuffles are immediately delegated to
8782 /// a dedicated lowering routine.
8783 ///
8784 /// The blends are lowered in one of three fundamental ways. If there are few
8785 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8786 /// of the input is significantly cheaper when lowered as an interleaving of
8787 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8788 /// halves of the inputs separately (making them have relatively few inputs)
8789 /// and then concatenate them.
8790 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8791                                        const X86Subtarget *Subtarget,
8792                                        SelectionDAG &DAG) {
8793   SDLoc DL(Op);
8794   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8795   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8796   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8798   ArrayRef<int> OrigMask = SVOp->getMask();
8799   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8800                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8801   MutableArrayRef<int> Mask(MaskStorage);
8802
8803   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8804
8805   // Whenever we can lower this as a zext, that instruction is strictly faster
8806   // than any alternative.
8807   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8808           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8809     return ZExt;
8810
8811   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8812   (void)isV1;
8813   auto isV2 = [](int M) { return M >= 8; };
8814
8815   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8816
8817   if (NumV2Inputs == 0) {
8818     // Check for being able to broadcast a single element.
8819     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8820                                                           Mask, Subtarget, DAG))
8821       return Broadcast;
8822
8823     // Try to use shift instructions.
8824     if (SDValue Shift =
8825             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8826       return Shift;
8827
8828     // Use dedicated unpack instructions for masks that match their pattern.
8829     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8830       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8831     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8832       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8833
8834     // Try to use byte rotation instructions.
8835     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8836                                                         Mask, Subtarget, DAG))
8837       return Rotate;
8838
8839     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8840                                                      Subtarget, DAG);
8841   }
8842
8843   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8844          "All single-input shuffles should be canonicalized to be V1-input "
8845          "shuffles.");
8846
8847   // Try to use shift instructions.
8848   if (SDValue Shift =
8849           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8850     return Shift;
8851
8852   // See if we can use SSE4A Extraction / Insertion.
8853   if (Subtarget->hasSSE4A())
8854     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8855       return V;
8856
8857   // There are special ways we can lower some single-element blends.
8858   if (NumV2Inputs == 1)
8859     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8860                                                          Mask, Subtarget, DAG))
8861       return V;
8862
8863   // We have different paths for blend lowering, but they all must use the
8864   // *exact* same predicate.
8865   bool IsBlendSupported = Subtarget->hasSSE41();
8866   if (IsBlendSupported)
8867     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8868                                                   Subtarget, DAG))
8869       return Blend;
8870
8871   if (SDValue Masked =
8872           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8873     return Masked;
8874
8875   // Use dedicated unpack instructions for masks that match their pattern.
8876   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8877     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8878   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8879     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8880
8881   // Try to use byte rotation instructions.
8882   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8883           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8884     return Rotate;
8885
8886   if (SDValue BitBlend =
8887           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8888     return BitBlend;
8889
8890   if (SDValue Unpack =
8891           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8892     return Unpack;
8893
8894   // If we can't directly blend but can use PSHUFB, that will be better as it
8895   // can both shuffle and set up the inefficient blend.
8896   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8897     bool V1InUse, V2InUse;
8898     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8899                                       V1InUse, V2InUse);
8900   }
8901
8902   // We can always bit-blend if we have to so the fallback strategy is to
8903   // decompose into single-input permutes and blends.
8904   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8905                                                       Mask, DAG);
8906 }
8907
8908 /// \brief Check whether a compaction lowering can be done by dropping even
8909 /// elements and compute how many times even elements must be dropped.
8910 ///
8911 /// This handles shuffles which take every Nth element where N is a power of
8912 /// two. Example shuffle masks:
8913 ///
8914 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8915 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8916 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8917 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8918 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8919 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8920 ///
8921 /// Any of these lanes can of course be undef.
8922 ///
8923 /// This routine only supports N <= 3.
8924 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8925 /// for larger N.
8926 ///
8927 /// \returns N above, or the number of times even elements must be dropped if
8928 /// there is such a number. Otherwise returns zero.
8929 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8930   // Figure out whether we're looping over two inputs or just one.
8931   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8932
8933   // The modulus for the shuffle vector entries is based on whether this is
8934   // a single input or not.
8935   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8936   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8937          "We should only be called with masks with a power-of-2 size!");
8938
8939   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8940
8941   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8942   // and 2^3 simultaneously. This is because we may have ambiguity with
8943   // partially undef inputs.
8944   bool ViableForN[3] = {true, true, true};
8945
8946   for (int i = 0, e = Mask.size(); i < e; ++i) {
8947     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8948     // want.
8949     if (Mask[i] == -1)
8950       continue;
8951
8952     bool IsAnyViable = false;
8953     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8954       if (ViableForN[j]) {
8955         uint64_t N = j + 1;
8956
8957         // The shuffle mask must be equal to (i * 2^N) % M.
8958         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8959           IsAnyViable = true;
8960         else
8961           ViableForN[j] = false;
8962       }
8963     // Early exit if we exhaust the possible powers of two.
8964     if (!IsAnyViable)
8965       break;
8966   }
8967
8968   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8969     if (ViableForN[j])
8970       return j + 1;
8971
8972   // Return 0 as there is no viable power of two.
8973   return 0;
8974 }
8975
8976 /// \brief Generic lowering of v16i8 shuffles.
8977 ///
8978 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8979 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8980 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8981 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8982 /// back together.
8983 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8984                                        const X86Subtarget *Subtarget,
8985                                        SelectionDAG &DAG) {
8986   SDLoc DL(Op);
8987   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8988   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8989   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8991   ArrayRef<int> Mask = SVOp->getMask();
8992   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8993
8994   // Try to use shift instructions.
8995   if (SDValue Shift =
8996           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8997     return Shift;
8998
8999   // Try to use byte rotation instructions.
9000   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9001           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9002     return Rotate;
9003
9004   // Try to use a zext lowering.
9005   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9006           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9007     return ZExt;
9008
9009   // See if we can use SSE4A Extraction / Insertion.
9010   if (Subtarget->hasSSE4A())
9011     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9012       return V;
9013
9014   int NumV2Elements =
9015       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9016
9017   // For single-input shuffles, there are some nicer lowering tricks we can use.
9018   if (NumV2Elements == 0) {
9019     // Check for being able to broadcast a single element.
9020     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9021                                                           Mask, Subtarget, DAG))
9022       return Broadcast;
9023
9024     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9025     // Notably, this handles splat and partial-splat shuffles more efficiently.
9026     // However, it only makes sense if the pre-duplication shuffle simplifies
9027     // things significantly. Currently, this means we need to be able to
9028     // express the pre-duplication shuffle as an i16 shuffle.
9029     //
9030     // FIXME: We should check for other patterns which can be widened into an
9031     // i16 shuffle as well.
9032     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9033       for (int i = 0; i < 16; i += 2)
9034         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9035           return false;
9036
9037       return true;
9038     };
9039     auto tryToWidenViaDuplication = [&]() -> SDValue {
9040       if (!canWidenViaDuplication(Mask))
9041         return SDValue();
9042       SmallVector<int, 4> LoInputs;
9043       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9044                    [](int M) { return M >= 0 && M < 8; });
9045       std::sort(LoInputs.begin(), LoInputs.end());
9046       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9047                      LoInputs.end());
9048       SmallVector<int, 4> HiInputs;
9049       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9050                    [](int M) { return M >= 8; });
9051       std::sort(HiInputs.begin(), HiInputs.end());
9052       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9053                      HiInputs.end());
9054
9055       bool TargetLo = LoInputs.size() >= HiInputs.size();
9056       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9057       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9058
9059       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9060       SmallDenseMap<int, int, 8> LaneMap;
9061       for (int I : InPlaceInputs) {
9062         PreDupI16Shuffle[I/2] = I/2;
9063         LaneMap[I] = I;
9064       }
9065       int j = TargetLo ? 0 : 4, je = j + 4;
9066       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9067         // Check if j is already a shuffle of this input. This happens when
9068         // there are two adjacent bytes after we move the low one.
9069         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9070           // If we haven't yet mapped the input, search for a slot into which
9071           // we can map it.
9072           while (j < je && PreDupI16Shuffle[j] != -1)
9073             ++j;
9074
9075           if (j == je)
9076             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9077             return SDValue();
9078
9079           // Map this input with the i16 shuffle.
9080           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9081         }
9082
9083         // Update the lane map based on the mapping we ended up with.
9084         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9085       }
9086       V1 = DAG.getBitcast(
9087           MVT::v16i8,
9088           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9089                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9090
9091       // Unpack the bytes to form the i16s that will be shuffled into place.
9092       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9093                        MVT::v16i8, V1, V1);
9094
9095       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9096       for (int i = 0; i < 16; ++i)
9097         if (Mask[i] != -1) {
9098           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9099           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9100           if (PostDupI16Shuffle[i / 2] == -1)
9101             PostDupI16Shuffle[i / 2] = MappedMask;
9102           else
9103             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9104                    "Conflicting entrties in the original shuffle!");
9105         }
9106       return DAG.getBitcast(
9107           MVT::v16i8,
9108           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9109                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9110     };
9111     if (SDValue V = tryToWidenViaDuplication())
9112       return V;
9113   }
9114
9115   if (SDValue Masked =
9116           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9117     return Masked;
9118
9119   // Use dedicated unpack instructions for masks that match their pattern.
9120   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9121                                          0, 16, 1, 17, 2, 18, 3, 19,
9122                                          // High half.
9123                                          4, 20, 5, 21, 6, 22, 7, 23}))
9124     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9125   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9126                                          8, 24, 9, 25, 10, 26, 11, 27,
9127                                          // High half.
9128                                          12, 28, 13, 29, 14, 30, 15, 31}))
9129     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9130
9131   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9132   // with PSHUFB. It is important to do this before we attempt to generate any
9133   // blends but after all of the single-input lowerings. If the single input
9134   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9135   // want to preserve that and we can DAG combine any longer sequences into
9136   // a PSHUFB in the end. But once we start blending from multiple inputs,
9137   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9138   // and there are *very* few patterns that would actually be faster than the
9139   // PSHUFB approach because of its ability to zero lanes.
9140   //
9141   // FIXME: The only exceptions to the above are blends which are exact
9142   // interleavings with direct instructions supporting them. We currently don't
9143   // handle those well here.
9144   if (Subtarget->hasSSSE3()) {
9145     bool V1InUse = false;
9146     bool V2InUse = false;
9147
9148     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9149                                                 DAG, V1InUse, V2InUse);
9150
9151     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9152     // do so. This avoids using them to handle blends-with-zero which is
9153     // important as a single pshufb is significantly faster for that.
9154     if (V1InUse && V2InUse) {
9155       if (Subtarget->hasSSE41())
9156         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9157                                                       Mask, Subtarget, DAG))
9158           return Blend;
9159
9160       // We can use an unpack to do the blending rather than an or in some
9161       // cases. Even though the or may be (very minorly) more efficient, we
9162       // preference this lowering because there are common cases where part of
9163       // the complexity of the shuffles goes away when we do the final blend as
9164       // an unpack.
9165       // FIXME: It might be worth trying to detect if the unpack-feeding
9166       // shuffles will both be pshufb, in which case we shouldn't bother with
9167       // this.
9168       if (SDValue Unpack =
9169               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9170         return Unpack;
9171     }
9172
9173     return PSHUFB;
9174   }
9175
9176   // There are special ways we can lower some single-element blends.
9177   if (NumV2Elements == 1)
9178     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9179                                                          Mask, Subtarget, DAG))
9180       return V;
9181
9182   if (SDValue BitBlend =
9183           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9184     return BitBlend;
9185
9186   // Check whether a compaction lowering can be done. This handles shuffles
9187   // which take every Nth element for some even N. See the helper function for
9188   // details.
9189   //
9190   // We special case these as they can be particularly efficiently handled with
9191   // the PACKUSB instruction on x86 and they show up in common patterns of
9192   // rearranging bytes to truncate wide elements.
9193   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9194     // NumEvenDrops is the power of two stride of the elements. Another way of
9195     // thinking about it is that we need to drop the even elements this many
9196     // times to get the original input.
9197     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9198
9199     // First we need to zero all the dropped bytes.
9200     assert(NumEvenDrops <= 3 &&
9201            "No support for dropping even elements more than 3 times.");
9202     // We use the mask type to pick which bytes are preserved based on how many
9203     // elements are dropped.
9204     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9205     SDValue ByteClearMask = DAG.getBitcast(
9206         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9207     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9208     if (!IsSingleInput)
9209       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9210
9211     // Now pack things back together.
9212     V1 = DAG.getBitcast(MVT::v8i16, V1);
9213     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9214     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9215     for (int i = 1; i < NumEvenDrops; ++i) {
9216       Result = DAG.getBitcast(MVT::v8i16, Result);
9217       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9218     }
9219
9220     return Result;
9221   }
9222
9223   // Handle multi-input cases by blending single-input shuffles.
9224   if (NumV2Elements > 0)
9225     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9226                                                       Mask, DAG);
9227
9228   // The fallback path for single-input shuffles widens this into two v8i16
9229   // vectors with unpacks, shuffles those, and then pulls them back together
9230   // with a pack.
9231   SDValue V = V1;
9232
9233   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9234   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9235   for (int i = 0; i < 16; ++i)
9236     if (Mask[i] >= 0)
9237       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9238
9239   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9240
9241   SDValue VLoHalf, VHiHalf;
9242   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9243   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9244   // i16s.
9245   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9246                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9247       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9248                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9249     // Use a mask to drop the high bytes.
9250     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9251     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9252                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9253
9254     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9255     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9256
9257     // Squash the masks to point directly into VLoHalf.
9258     for (int &M : LoBlendMask)
9259       if (M >= 0)
9260         M /= 2;
9261     for (int &M : HiBlendMask)
9262       if (M >= 0)
9263         M /= 2;
9264   } else {
9265     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9266     // VHiHalf so that we can blend them as i16s.
9267     VLoHalf = DAG.getBitcast(
9268         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9269     VHiHalf = DAG.getBitcast(
9270         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9271   }
9272
9273   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9274   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9275
9276   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9277 }
9278
9279 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9280 ///
9281 /// This routine breaks down the specific type of 128-bit shuffle and
9282 /// dispatches to the lowering routines accordingly.
9283 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9284                                         MVT VT, const X86Subtarget *Subtarget,
9285                                         SelectionDAG &DAG) {
9286   switch (VT.SimpleTy) {
9287   case MVT::v2i64:
9288     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9289   case MVT::v2f64:
9290     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9291   case MVT::v4i32:
9292     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9293   case MVT::v4f32:
9294     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9295   case MVT::v8i16:
9296     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9297   case MVT::v16i8:
9298     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9299
9300   default:
9301     llvm_unreachable("Unimplemented!");
9302   }
9303 }
9304
9305 /// \brief Helper function to test whether a shuffle mask could be
9306 /// simplified by widening the elements being shuffled.
9307 ///
9308 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9309 /// leaves it in an unspecified state.
9310 ///
9311 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9312 /// shuffle masks. The latter have the special property of a '-2' representing
9313 /// a zero-ed lane of a vector.
9314 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9315                                     SmallVectorImpl<int> &WidenedMask) {
9316   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9317     // If both elements are undef, its trivial.
9318     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9319       WidenedMask.push_back(SM_SentinelUndef);
9320       continue;
9321     }
9322
9323     // Check for an undef mask and a mask value properly aligned to fit with
9324     // a pair of values. If we find such a case, use the non-undef mask's value.
9325     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9326       WidenedMask.push_back(Mask[i + 1] / 2);
9327       continue;
9328     }
9329     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9330       WidenedMask.push_back(Mask[i] / 2);
9331       continue;
9332     }
9333
9334     // When zeroing, we need to spread the zeroing across both lanes to widen.
9335     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9336       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9337           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9338         WidenedMask.push_back(SM_SentinelZero);
9339         continue;
9340       }
9341       return false;
9342     }
9343
9344     // Finally check if the two mask values are adjacent and aligned with
9345     // a pair.
9346     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9347       WidenedMask.push_back(Mask[i] / 2);
9348       continue;
9349     }
9350
9351     // Otherwise we can't safely widen the elements used in this shuffle.
9352     return false;
9353   }
9354   assert(WidenedMask.size() == Mask.size() / 2 &&
9355          "Incorrect size of mask after widening the elements!");
9356
9357   return true;
9358 }
9359
9360 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9361 ///
9362 /// This routine just extracts two subvectors, shuffles them independently, and
9363 /// then concatenates them back together. This should work effectively with all
9364 /// AVX vector shuffle types.
9365 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9366                                           SDValue V2, ArrayRef<int> Mask,
9367                                           SelectionDAG &DAG) {
9368   assert(VT.getSizeInBits() >= 256 &&
9369          "Only for 256-bit or wider vector shuffles!");
9370   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9371   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9372
9373   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9374   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9375
9376   int NumElements = VT.getVectorNumElements();
9377   int SplitNumElements = NumElements / 2;
9378   MVT ScalarVT = VT.getScalarType();
9379   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9380
9381   // Rather than splitting build-vectors, just build two narrower build
9382   // vectors. This helps shuffling with splats and zeros.
9383   auto SplitVector = [&](SDValue V) {
9384     while (V.getOpcode() == ISD::BITCAST)
9385       V = V->getOperand(0);
9386
9387     MVT OrigVT = V.getSimpleValueType();
9388     int OrigNumElements = OrigVT.getVectorNumElements();
9389     int OrigSplitNumElements = OrigNumElements / 2;
9390     MVT OrigScalarVT = OrigVT.getScalarType();
9391     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9392
9393     SDValue LoV, HiV;
9394
9395     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9396     if (!BV) {
9397       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9398                         DAG.getIntPtrConstant(0, DL));
9399       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9400                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9401     } else {
9402
9403       SmallVector<SDValue, 16> LoOps, HiOps;
9404       for (int i = 0; i < OrigSplitNumElements; ++i) {
9405         LoOps.push_back(BV->getOperand(i));
9406         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9407       }
9408       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9409       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9410     }
9411     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9412                           DAG.getBitcast(SplitVT, HiV));
9413   };
9414
9415   SDValue LoV1, HiV1, LoV2, HiV2;
9416   std::tie(LoV1, HiV1) = SplitVector(V1);
9417   std::tie(LoV2, HiV2) = SplitVector(V2);
9418
9419   // Now create two 4-way blends of these half-width vectors.
9420   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9421     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9422     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9423     for (int i = 0; i < SplitNumElements; ++i) {
9424       int M = HalfMask[i];
9425       if (M >= NumElements) {
9426         if (M >= NumElements + SplitNumElements)
9427           UseHiV2 = true;
9428         else
9429           UseLoV2 = true;
9430         V2BlendMask.push_back(M - NumElements);
9431         V1BlendMask.push_back(-1);
9432         BlendMask.push_back(SplitNumElements + i);
9433       } else if (M >= 0) {
9434         if (M >= SplitNumElements)
9435           UseHiV1 = true;
9436         else
9437           UseLoV1 = true;
9438         V2BlendMask.push_back(-1);
9439         V1BlendMask.push_back(M);
9440         BlendMask.push_back(i);
9441       } else {
9442         V2BlendMask.push_back(-1);
9443         V1BlendMask.push_back(-1);
9444         BlendMask.push_back(-1);
9445       }
9446     }
9447
9448     // Because the lowering happens after all combining takes place, we need to
9449     // manually combine these blend masks as much as possible so that we create
9450     // a minimal number of high-level vector shuffle nodes.
9451
9452     // First try just blending the halves of V1 or V2.
9453     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9454       return DAG.getUNDEF(SplitVT);
9455     if (!UseLoV2 && !UseHiV2)
9456       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9457     if (!UseLoV1 && !UseHiV1)
9458       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9459
9460     SDValue V1Blend, V2Blend;
9461     if (UseLoV1 && UseHiV1) {
9462       V1Blend =
9463         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9464     } else {
9465       // We only use half of V1 so map the usage down into the final blend mask.
9466       V1Blend = UseLoV1 ? LoV1 : HiV1;
9467       for (int i = 0; i < SplitNumElements; ++i)
9468         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9469           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9470     }
9471     if (UseLoV2 && UseHiV2) {
9472       V2Blend =
9473         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9474     } else {
9475       // We only use half of V2 so map the usage down into the final blend mask.
9476       V2Blend = UseLoV2 ? LoV2 : HiV2;
9477       for (int i = 0; i < SplitNumElements; ++i)
9478         if (BlendMask[i] >= SplitNumElements)
9479           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9480     }
9481     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9482   };
9483   SDValue Lo = HalfBlend(LoMask);
9484   SDValue Hi = HalfBlend(HiMask);
9485   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9486 }
9487
9488 /// \brief Either split a vector in halves or decompose the shuffles and the
9489 /// blend.
9490 ///
9491 /// This is provided as a good fallback for many lowerings of non-single-input
9492 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9493 /// between splitting the shuffle into 128-bit components and stitching those
9494 /// back together vs. extracting the single-input shuffles and blending those
9495 /// results.
9496 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9497                                                 SDValue V2, ArrayRef<int> Mask,
9498                                                 SelectionDAG &DAG) {
9499   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9500                                             "lower single-input shuffles as it "
9501                                             "could then recurse on itself.");
9502   int Size = Mask.size();
9503
9504   // If this can be modeled as a broadcast of two elements followed by a blend,
9505   // prefer that lowering. This is especially important because broadcasts can
9506   // often fold with memory operands.
9507   auto DoBothBroadcast = [&] {
9508     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9509     for (int M : Mask)
9510       if (M >= Size) {
9511         if (V2BroadcastIdx == -1)
9512           V2BroadcastIdx = M - Size;
9513         else if (M - Size != V2BroadcastIdx)
9514           return false;
9515       } else if (M >= 0) {
9516         if (V1BroadcastIdx == -1)
9517           V1BroadcastIdx = M;
9518         else if (M != V1BroadcastIdx)
9519           return false;
9520       }
9521     return true;
9522   };
9523   if (DoBothBroadcast())
9524     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9525                                                       DAG);
9526
9527   // If the inputs all stem from a single 128-bit lane of each input, then we
9528   // split them rather than blending because the split will decompose to
9529   // unusually few instructions.
9530   int LaneCount = VT.getSizeInBits() / 128;
9531   int LaneSize = Size / LaneCount;
9532   SmallBitVector LaneInputs[2];
9533   LaneInputs[0].resize(LaneCount, false);
9534   LaneInputs[1].resize(LaneCount, false);
9535   for (int i = 0; i < Size; ++i)
9536     if (Mask[i] >= 0)
9537       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9538   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9539     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9540
9541   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9542   // that the decomposed single-input shuffles don't end up here.
9543   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9544 }
9545
9546 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9547 /// a permutation and blend of those lanes.
9548 ///
9549 /// This essentially blends the out-of-lane inputs to each lane into the lane
9550 /// from a permuted copy of the vector. This lowering strategy results in four
9551 /// instructions in the worst case for a single-input cross lane shuffle which
9552 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9553 /// of. Special cases for each particular shuffle pattern should be handled
9554 /// prior to trying this lowering.
9555 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9556                                                        SDValue V1, SDValue V2,
9557                                                        ArrayRef<int> Mask,
9558                                                        SelectionDAG &DAG) {
9559   // FIXME: This should probably be generalized for 512-bit vectors as well.
9560   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9561   int LaneSize = Mask.size() / 2;
9562
9563   // If there are only inputs from one 128-bit lane, splitting will in fact be
9564   // less expensive. The flags track whether the given lane contains an element
9565   // that crosses to another lane.
9566   bool LaneCrossing[2] = {false, false};
9567   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9568     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9569       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9570   if (!LaneCrossing[0] || !LaneCrossing[1])
9571     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9572
9573   if (isSingleInputShuffleMask(Mask)) {
9574     SmallVector<int, 32> FlippedBlendMask;
9575     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9576       FlippedBlendMask.push_back(
9577           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9578                                   ? Mask[i]
9579                                   : Mask[i] % LaneSize +
9580                                         (i / LaneSize) * LaneSize + Size));
9581
9582     // Flip the vector, and blend the results which should now be in-lane. The
9583     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9584     // 5 for the high source. The value 3 selects the high half of source 2 and
9585     // the value 2 selects the low half of source 2. We only use source 2 to
9586     // allow folding it into a memory operand.
9587     unsigned PERMMask = 3 | 2 << 4;
9588     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9589                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9590     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9591   }
9592
9593   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9594   // will be handled by the above logic and a blend of the results, much like
9595   // other patterns in AVX.
9596   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9597 }
9598
9599 /// \brief Handle lowering 2-lane 128-bit shuffles.
9600 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9601                                         SDValue V2, ArrayRef<int> Mask,
9602                                         const X86Subtarget *Subtarget,
9603                                         SelectionDAG &DAG) {
9604   // TODO: If minimizing size and one of the inputs is a zero vector and the
9605   // the zero vector has only one use, we could use a VPERM2X128 to save the
9606   // instruction bytes needed to explicitly generate the zero vector.
9607
9608   // Blends are faster and handle all the non-lane-crossing cases.
9609   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9610                                                 Subtarget, DAG))
9611     return Blend;
9612
9613   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9614   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9615
9616   // If either input operand is a zero vector, use VPERM2X128 because its mask
9617   // allows us to replace the zero input with an implicit zero.
9618   if (!IsV1Zero && !IsV2Zero) {
9619     // Check for patterns which can be matched with a single insert of a 128-bit
9620     // subvector.
9621     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9622     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9623       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9624                                    VT.getVectorNumElements() / 2);
9625       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9626                                 DAG.getIntPtrConstant(0, DL));
9627       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9628                                 OnlyUsesV1 ? V1 : V2,
9629                                 DAG.getIntPtrConstant(0, DL));
9630       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9631     }
9632   }
9633
9634   // Otherwise form a 128-bit permutation. After accounting for undefs,
9635   // convert the 64-bit shuffle mask selection values into 128-bit
9636   // selection bits by dividing the indexes by 2 and shifting into positions
9637   // defined by a vperm2*128 instruction's immediate control byte.
9638
9639   // The immediate permute control byte looks like this:
9640   //    [1:0] - select 128 bits from sources for low half of destination
9641   //    [2]   - ignore
9642   //    [3]   - zero low half of destination
9643   //    [5:4] - select 128 bits from sources for high half of destination
9644   //    [6]   - ignore
9645   //    [7]   - zero high half of destination
9646
9647   int MaskLO = Mask[0];
9648   if (MaskLO == SM_SentinelUndef)
9649     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9650
9651   int MaskHI = Mask[2];
9652   if (MaskHI == SM_SentinelUndef)
9653     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9654
9655   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9656
9657   // If either input is a zero vector, replace it with an undef input.
9658   // Shuffle mask values <  4 are selecting elements of V1.
9659   // Shuffle mask values >= 4 are selecting elements of V2.
9660   // Adjust each half of the permute mask by clearing the half that was
9661   // selecting the zero vector and setting the zero mask bit.
9662   if (IsV1Zero) {
9663     V1 = DAG.getUNDEF(VT);
9664     if (MaskLO < 4)
9665       PermMask = (PermMask & 0xf0) | 0x08;
9666     if (MaskHI < 4)
9667       PermMask = (PermMask & 0x0f) | 0x80;
9668   }
9669   if (IsV2Zero) {
9670     V2 = DAG.getUNDEF(VT);
9671     if (MaskLO >= 4)
9672       PermMask = (PermMask & 0xf0) | 0x08;
9673     if (MaskHI >= 4)
9674       PermMask = (PermMask & 0x0f) | 0x80;
9675   }
9676
9677   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9678                      DAG.getConstant(PermMask, DL, MVT::i8));
9679 }
9680
9681 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9682 /// shuffling each lane.
9683 ///
9684 /// This will only succeed when the result of fixing the 128-bit lanes results
9685 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9686 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9687 /// the lane crosses early and then use simpler shuffles within each lane.
9688 ///
9689 /// FIXME: It might be worthwhile at some point to support this without
9690 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9691 /// in x86 only floating point has interesting non-repeating shuffles, and even
9692 /// those are still *marginally* more expensive.
9693 static SDValue lowerVectorShuffleByMerging128BitLanes(
9694     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9695     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9696   assert(!isSingleInputShuffleMask(Mask) &&
9697          "This is only useful with multiple inputs.");
9698
9699   int Size = Mask.size();
9700   int LaneSize = 128 / VT.getScalarSizeInBits();
9701   int NumLanes = Size / LaneSize;
9702   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9703
9704   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9705   // check whether the in-128-bit lane shuffles share a repeating pattern.
9706   SmallVector<int, 4> Lanes;
9707   Lanes.resize(NumLanes, -1);
9708   SmallVector<int, 4> InLaneMask;
9709   InLaneMask.resize(LaneSize, -1);
9710   for (int i = 0; i < Size; ++i) {
9711     if (Mask[i] < 0)
9712       continue;
9713
9714     int j = i / LaneSize;
9715
9716     if (Lanes[j] < 0) {
9717       // First entry we've seen for this lane.
9718       Lanes[j] = Mask[i] / LaneSize;
9719     } else if (Lanes[j] != Mask[i] / LaneSize) {
9720       // This doesn't match the lane selected previously!
9721       return SDValue();
9722     }
9723
9724     // Check that within each lane we have a consistent shuffle mask.
9725     int k = i % LaneSize;
9726     if (InLaneMask[k] < 0) {
9727       InLaneMask[k] = Mask[i] % LaneSize;
9728     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9729       // This doesn't fit a repeating in-lane mask.
9730       return SDValue();
9731     }
9732   }
9733
9734   // First shuffle the lanes into place.
9735   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9736                                 VT.getSizeInBits() / 64);
9737   SmallVector<int, 8> LaneMask;
9738   LaneMask.resize(NumLanes * 2, -1);
9739   for (int i = 0; i < NumLanes; ++i)
9740     if (Lanes[i] >= 0) {
9741       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9742       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9743     }
9744
9745   V1 = DAG.getBitcast(LaneVT, V1);
9746   V2 = DAG.getBitcast(LaneVT, V2);
9747   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9748
9749   // Cast it back to the type we actually want.
9750   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9751
9752   // Now do a simple shuffle that isn't lane crossing.
9753   SmallVector<int, 8> NewMask;
9754   NewMask.resize(Size, -1);
9755   for (int i = 0; i < Size; ++i)
9756     if (Mask[i] >= 0)
9757       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9758   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9759          "Must not introduce lane crosses at this point!");
9760
9761   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9762 }
9763
9764 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9765 /// given mask.
9766 ///
9767 /// This returns true if the elements from a particular input are already in the
9768 /// slot required by the given mask and require no permutation.
9769 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9770   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9771   int Size = Mask.size();
9772   for (int i = 0; i < Size; ++i)
9773     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9774       return false;
9775
9776   return true;
9777 }
9778
9779 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9780                                             ArrayRef<int> Mask, SDValue V1,
9781                                             SDValue V2, SelectionDAG &DAG) {
9782
9783   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9784   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9785   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9786   int NumElts = VT.getVectorNumElements();
9787   bool ShufpdMask = true;
9788   bool CommutableMask = true;
9789   unsigned Immediate = 0;
9790   for (int i = 0; i < NumElts; ++i) {
9791     if (Mask[i] < 0)
9792       continue;
9793     int Val = (i & 6) + NumElts * (i & 1);
9794     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9795     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9796       ShufpdMask = false;
9797     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9798       CommutableMask = false;
9799     Immediate |= (Mask[i] % 2) << i;
9800   }
9801   if (ShufpdMask)
9802     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9803                        DAG.getConstant(Immediate, DL, MVT::i8));
9804   if (CommutableMask)
9805     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9806                        DAG.getConstant(Immediate, DL, MVT::i8));
9807   return SDValue();
9808 }
9809
9810 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9811 ///
9812 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9813 /// isn't available.
9814 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9815                                        const X86Subtarget *Subtarget,
9816                                        SelectionDAG &DAG) {
9817   SDLoc DL(Op);
9818   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9819   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9821   ArrayRef<int> Mask = SVOp->getMask();
9822   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9823
9824   SmallVector<int, 4> WidenedMask;
9825   if (canWidenShuffleElements(Mask, WidenedMask))
9826     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9827                                     DAG);
9828
9829   if (isSingleInputShuffleMask(Mask)) {
9830     // Check for being able to broadcast a single element.
9831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9832                                                           Mask, Subtarget, DAG))
9833       return Broadcast;
9834
9835     // Use low duplicate instructions for masks that match their pattern.
9836     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9837       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9838
9839     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9840       // Non-half-crossing single input shuffles can be lowerid with an
9841       // interleaved permutation.
9842       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9843                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9844       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9845                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9846     }
9847
9848     // With AVX2 we have direct support for this permutation.
9849     if (Subtarget->hasAVX2())
9850       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9851                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9852
9853     // Otherwise, fall back.
9854     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9855                                                    DAG);
9856   }
9857
9858   // X86 has dedicated unpack instructions that can handle specific blend
9859   // operations: UNPCKH and UNPCKL.
9860   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9861     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9862   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9863     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9864   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9865     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9866   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9867     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9868
9869   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9870                                                 Subtarget, DAG))
9871     return Blend;
9872
9873   // Check if the blend happens to exactly fit that of SHUFPD.
9874   if (SDValue Op =
9875       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9876     return Op;
9877
9878   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9879   // shuffle. However, if we have AVX2 and either inputs are already in place,
9880   // we will be able to shuffle even across lanes the other input in a single
9881   // instruction so skip this pattern.
9882   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9883                                  isShuffleMaskInputInPlace(1, Mask))))
9884     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9885             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9886       return Result;
9887
9888   // If we have AVX2 then we always want to lower with a blend because an v4 we
9889   // can fully permute the elements.
9890   if (Subtarget->hasAVX2())
9891     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9892                                                       Mask, DAG);
9893
9894   // Otherwise fall back on generic lowering.
9895   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9896 }
9897
9898 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9899 ///
9900 /// This routine is only called when we have AVX2 and thus a reasonable
9901 /// instruction set for v4i64 shuffling..
9902 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9903                                        const X86Subtarget *Subtarget,
9904                                        SelectionDAG &DAG) {
9905   SDLoc DL(Op);
9906   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9907   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9908   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9909   ArrayRef<int> Mask = SVOp->getMask();
9910   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9911   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9912
9913   SmallVector<int, 4> WidenedMask;
9914   if (canWidenShuffleElements(Mask, WidenedMask))
9915     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9916                                     DAG);
9917
9918   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9919                                                 Subtarget, DAG))
9920     return Blend;
9921
9922   // Check for being able to broadcast a single element.
9923   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9924                                                         Mask, Subtarget, DAG))
9925     return Broadcast;
9926
9927   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9928   // use lower latency instructions that will operate on both 128-bit lanes.
9929   SmallVector<int, 2> RepeatedMask;
9930   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9931     if (isSingleInputShuffleMask(Mask)) {
9932       int PSHUFDMask[] = {-1, -1, -1, -1};
9933       for (int i = 0; i < 2; ++i)
9934         if (RepeatedMask[i] >= 0) {
9935           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9936           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9937         }
9938       return DAG.getBitcast(
9939           MVT::v4i64,
9940           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9941                       DAG.getBitcast(MVT::v8i32, V1),
9942                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9943     }
9944   }
9945
9946   // AVX2 provides a direct instruction for permuting a single input across
9947   // lanes.
9948   if (isSingleInputShuffleMask(Mask))
9949     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9950                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9951
9952   // Try to use shift instructions.
9953   if (SDValue Shift =
9954           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9955     return Shift;
9956
9957   // Use dedicated unpack instructions for masks that match their pattern.
9958   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9959     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9960   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9961     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9962   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9963     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9964   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9965     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9966
9967   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9968   // shuffle. However, if we have AVX2 and either inputs are already in place,
9969   // we will be able to shuffle even across lanes the other input in a single
9970   // instruction so skip this pattern.
9971   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9972                                  isShuffleMaskInputInPlace(1, Mask))))
9973     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9974             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9975       return Result;
9976
9977   // Otherwise fall back on generic blend lowering.
9978   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9979                                                     Mask, DAG);
9980 }
9981
9982 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9983 ///
9984 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9985 /// isn't available.
9986 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9987                                        const X86Subtarget *Subtarget,
9988                                        SelectionDAG &DAG) {
9989   SDLoc DL(Op);
9990   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9991   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9992   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9993   ArrayRef<int> Mask = SVOp->getMask();
9994   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9995
9996   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9997                                                 Subtarget, DAG))
9998     return Blend;
9999
10000   // Check for being able to broadcast a single element.
10001   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10002                                                         Mask, Subtarget, DAG))
10003     return Broadcast;
10004
10005   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10006   // options to efficiently lower the shuffle.
10007   SmallVector<int, 4> RepeatedMask;
10008   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10009     assert(RepeatedMask.size() == 4 &&
10010            "Repeated masks must be half the mask width!");
10011
10012     // Use even/odd duplicate instructions for masks that match their pattern.
10013     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10014       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10015     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10016       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10017
10018     if (isSingleInputShuffleMask(Mask))
10019       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10020                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10021
10022     // Use dedicated unpack instructions for masks that match their pattern.
10023     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10024       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10025     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10026       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10027     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10028       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10029     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10030       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10031
10032     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10033     // have already handled any direct blends. We also need to squash the
10034     // repeated mask into a simulated v4f32 mask.
10035     for (int i = 0; i < 4; ++i)
10036       if (RepeatedMask[i] >= 8)
10037         RepeatedMask[i] -= 4;
10038     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10039   }
10040
10041   // If we have a single input shuffle with different shuffle patterns in the
10042   // two 128-bit lanes use the variable mask to VPERMILPS.
10043   if (isSingleInputShuffleMask(Mask)) {
10044     SDValue VPermMask[8];
10045     for (int i = 0; i < 8; ++i)
10046       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10047                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10048     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10049       return DAG.getNode(
10050           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10051           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10052
10053     if (Subtarget->hasAVX2())
10054       return DAG.getNode(
10055           X86ISD::VPERMV, DL, MVT::v8f32,
10056           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10057                                                  MVT::v8i32, VPermMask)),
10058           V1);
10059
10060     // Otherwise, fall back.
10061     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10062                                                    DAG);
10063   }
10064
10065   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10066   // shuffle.
10067   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10068           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10069     return Result;
10070
10071   // If we have AVX2 then we always want to lower with a blend because at v8 we
10072   // can fully permute the elements.
10073   if (Subtarget->hasAVX2())
10074     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10075                                                       Mask, DAG);
10076
10077   // Otherwise fall back on generic lowering.
10078   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10079 }
10080
10081 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10082 ///
10083 /// This routine is only called when we have AVX2 and thus a reasonable
10084 /// instruction set for v8i32 shuffling..
10085 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10086                                        const X86Subtarget *Subtarget,
10087                                        SelectionDAG &DAG) {
10088   SDLoc DL(Op);
10089   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10090   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10091   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10092   ArrayRef<int> Mask = SVOp->getMask();
10093   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10094   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10095
10096   // Whenever we can lower this as a zext, that instruction is strictly faster
10097   // than any alternative. It also allows us to fold memory operands into the
10098   // shuffle in many cases.
10099   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10100                                                          Mask, Subtarget, DAG))
10101     return ZExt;
10102
10103   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10104                                                 Subtarget, DAG))
10105     return Blend;
10106
10107   // Check for being able to broadcast a single element.
10108   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10109                                                         Mask, Subtarget, DAG))
10110     return Broadcast;
10111
10112   // If the shuffle mask is repeated in each 128-bit lane we can use more
10113   // efficient instructions that mirror the shuffles across the two 128-bit
10114   // lanes.
10115   SmallVector<int, 4> RepeatedMask;
10116   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10117     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10118     if (isSingleInputShuffleMask(Mask))
10119       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10120                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10121
10122     // Use dedicated unpack instructions for masks that match their pattern.
10123     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10124       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10125     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10126       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10127     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10128       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10129     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10130       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10131   }
10132
10133   // Try to use shift instructions.
10134   if (SDValue Shift =
10135           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10136     return Shift;
10137
10138   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10139           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10140     return Rotate;
10141
10142   // If the shuffle patterns aren't repeated but it is a single input, directly
10143   // generate a cross-lane VPERMD instruction.
10144   if (isSingleInputShuffleMask(Mask)) {
10145     SDValue VPermMask[8];
10146     for (int i = 0; i < 8; ++i)
10147       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10148                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10149     return DAG.getNode(
10150         X86ISD::VPERMV, DL, MVT::v8i32,
10151         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10152   }
10153
10154   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10155   // shuffle.
10156   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10157           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10158     return Result;
10159
10160   // Otherwise fall back on generic blend lowering.
10161   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10162                                                     Mask, DAG);
10163 }
10164
10165 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10166 ///
10167 /// This routine is only called when we have AVX2 and thus a reasonable
10168 /// instruction set for v16i16 shuffling..
10169 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10170                                         const X86Subtarget *Subtarget,
10171                                         SelectionDAG &DAG) {
10172   SDLoc DL(Op);
10173   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10174   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10176   ArrayRef<int> Mask = SVOp->getMask();
10177   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10178   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10179
10180   // Whenever we can lower this as a zext, that instruction is strictly faster
10181   // than any alternative. It also allows us to fold memory operands into the
10182   // shuffle in many cases.
10183   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10184                                                          Mask, Subtarget, DAG))
10185     return ZExt;
10186
10187   // Check for being able to broadcast a single element.
10188   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10189                                                         Mask, Subtarget, DAG))
10190     return Broadcast;
10191
10192   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10193                                                 Subtarget, DAG))
10194     return Blend;
10195
10196   // Use dedicated unpack instructions for masks that match their pattern.
10197   if (isShuffleEquivalent(V1, V2, Mask,
10198                           {// First 128-bit lane:
10199                            0, 16, 1, 17, 2, 18, 3, 19,
10200                            // Second 128-bit lane:
10201                            8, 24, 9, 25, 10, 26, 11, 27}))
10202     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10203   if (isShuffleEquivalent(V1, V2, Mask,
10204                           {// First 128-bit lane:
10205                            4, 20, 5, 21, 6, 22, 7, 23,
10206                            // Second 128-bit lane:
10207                            12, 28, 13, 29, 14, 30, 15, 31}))
10208     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10209
10210   // Try to use shift instructions.
10211   if (SDValue Shift =
10212           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10213     return Shift;
10214
10215   // Try to use byte rotation instructions.
10216   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10217           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10218     return Rotate;
10219
10220   if (isSingleInputShuffleMask(Mask)) {
10221     // There are no generalized cross-lane shuffle operations available on i16
10222     // element types.
10223     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10224       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10225                                                      Mask, DAG);
10226
10227     SmallVector<int, 8> RepeatedMask;
10228     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10229       // As this is a single-input shuffle, the repeated mask should be
10230       // a strictly valid v8i16 mask that we can pass through to the v8i16
10231       // lowering to handle even the v16 case.
10232       return lowerV8I16GeneralSingleInputVectorShuffle(
10233           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10234     }
10235
10236     SDValue PSHUFBMask[32];
10237     for (int i = 0; i < 16; ++i) {
10238       if (Mask[i] == -1) {
10239         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10240         continue;
10241       }
10242
10243       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10244       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10245       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10246       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10247     }
10248     return DAG.getBitcast(MVT::v16i16,
10249                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10250                                       DAG.getBitcast(MVT::v32i8, V1),
10251                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10252                                                   MVT::v32i8, PSHUFBMask)));
10253   }
10254
10255   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10256   // shuffle.
10257   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10258           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10259     return Result;
10260
10261   // Otherwise fall back on generic lowering.
10262   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10263 }
10264
10265 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10266 ///
10267 /// This routine is only called when we have AVX2 and thus a reasonable
10268 /// instruction set for v32i8 shuffling..
10269 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10270                                        const X86Subtarget *Subtarget,
10271                                        SelectionDAG &DAG) {
10272   SDLoc DL(Op);
10273   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10274   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10275   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10276   ArrayRef<int> Mask = SVOp->getMask();
10277   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10278   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10279
10280   // Whenever we can lower this as a zext, that instruction is strictly faster
10281   // than any alternative. It also allows us to fold memory operands into the
10282   // shuffle in many cases.
10283   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10284                                                          Mask, Subtarget, DAG))
10285     return ZExt;
10286
10287   // Check for being able to broadcast a single element.
10288   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10289                                                         Mask, Subtarget, DAG))
10290     return Broadcast;
10291
10292   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10293                                                 Subtarget, DAG))
10294     return Blend;
10295
10296   // Use dedicated unpack instructions for masks that match their pattern.
10297   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10298   // 256-bit lanes.
10299   if (isShuffleEquivalent(
10300           V1, V2, Mask,
10301           {// First 128-bit lane:
10302            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10303            // Second 128-bit lane:
10304            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10305     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10306   if (isShuffleEquivalent(
10307           V1, V2, Mask,
10308           {// First 128-bit lane:
10309            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10310            // Second 128-bit lane:
10311            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10312     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10313
10314   // Try to use shift instructions.
10315   if (SDValue Shift =
10316           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10317     return Shift;
10318
10319   // Try to use byte rotation instructions.
10320   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10321           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10322     return Rotate;
10323
10324   if (isSingleInputShuffleMask(Mask)) {
10325     // There are no generalized cross-lane shuffle operations available on i8
10326     // element types.
10327     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10328       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10329                                                      Mask, DAG);
10330
10331     SDValue PSHUFBMask[32];
10332     for (int i = 0; i < 32; ++i)
10333       PSHUFBMask[i] =
10334           Mask[i] < 0
10335               ? DAG.getUNDEF(MVT::i8)
10336               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10337                                 MVT::i8);
10338
10339     return DAG.getNode(
10340         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10341         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10342   }
10343
10344   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10345   // shuffle.
10346   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10347           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10348     return Result;
10349
10350   // Otherwise fall back on generic lowering.
10351   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10352 }
10353
10354 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10355 ///
10356 /// This routine either breaks down the specific type of a 256-bit x86 vector
10357 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10358 /// together based on the available instructions.
10359 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360                                         MVT VT, const X86Subtarget *Subtarget,
10361                                         SelectionDAG &DAG) {
10362   SDLoc DL(Op);
10363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10364   ArrayRef<int> Mask = SVOp->getMask();
10365
10366   // If we have a single input to the zero element, insert that into V1 if we
10367   // can do so cheaply.
10368   int NumElts = VT.getVectorNumElements();
10369   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10370     return M >= NumElts;
10371   });
10372
10373   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10374     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10375                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10376       return Insertion;
10377
10378   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10379   // check for those subtargets here and avoid much of the subtarget querying in
10380   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10381   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10382   // floating point types there eventually, just immediately cast everything to
10383   // a float and operate entirely in that domain.
10384   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10385     int ElementBits = VT.getScalarSizeInBits();
10386     if (ElementBits < 32)
10387       // No floating point type available, decompose into 128-bit vectors.
10388       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10389
10390     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10391                                 VT.getVectorNumElements());
10392     V1 = DAG.getBitcast(FpVT, V1);
10393     V2 = DAG.getBitcast(FpVT, V2);
10394     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10395   }
10396
10397   switch (VT.SimpleTy) {
10398   case MVT::v4f64:
10399     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10400   case MVT::v4i64:
10401     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10402   case MVT::v8f32:
10403     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10404   case MVT::v8i32:
10405     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10406   case MVT::v16i16:
10407     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10408   case MVT::v32i8:
10409     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10410
10411   default:
10412     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10413   }
10414 }
10415
10416 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10417 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10418                                        const X86Subtarget *Subtarget,
10419                                        SelectionDAG &DAG) {
10420   SDLoc DL(Op);
10421   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10422   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10424   ArrayRef<int> Mask = SVOp->getMask();
10425   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10426
10427   // X86 has dedicated unpack instructions that can handle specific blend
10428   // operations: UNPCKH and UNPCKL.
10429   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10430     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10431   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10432     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10433
10434   // FIXME: Implement direct support for this type!
10435   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10436 }
10437
10438 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10439 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10440                                        const X86Subtarget *Subtarget,
10441                                        SelectionDAG &DAG) {
10442   SDLoc DL(Op);
10443   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10444   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10446   ArrayRef<int> Mask = SVOp->getMask();
10447   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10448
10449   // Use dedicated unpack instructions for masks that match their pattern.
10450   if (isShuffleEquivalent(V1, V2, Mask,
10451                           {// First 128-bit lane.
10452                            0, 16, 1, 17, 4, 20, 5, 21,
10453                            // Second 128-bit lane.
10454                            8, 24, 9, 25, 12, 28, 13, 29}))
10455     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10456   if (isShuffleEquivalent(V1, V2, Mask,
10457                           {// First 128-bit lane.
10458                            2, 18, 3, 19, 6, 22, 7, 23,
10459                            // Second 128-bit lane.
10460                            10, 26, 11, 27, 14, 30, 15, 31}))
10461     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10462
10463   // FIXME: Implement direct support for this type!
10464   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10465 }
10466
10467 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10468 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10469                                        const X86Subtarget *Subtarget,
10470                                        SelectionDAG &DAG) {
10471   SDLoc DL(Op);
10472   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10473   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10475   ArrayRef<int> Mask = SVOp->getMask();
10476   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10477
10478   // X86 has dedicated unpack instructions that can handle specific blend
10479   // operations: UNPCKH and UNPCKL.
10480   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10481     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10482   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10483     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10484
10485   // FIXME: Implement direct support for this type!
10486   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10487 }
10488
10489 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10490 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491                                        const X86Subtarget *Subtarget,
10492                                        SelectionDAG &DAG) {
10493   SDLoc DL(Op);
10494   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10495   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497   ArrayRef<int> Mask = SVOp->getMask();
10498   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10499
10500   // Use dedicated unpack instructions for masks that match their pattern.
10501   if (isShuffleEquivalent(V1, V2, Mask,
10502                           {// First 128-bit lane.
10503                            0, 16, 1, 17, 4, 20, 5, 21,
10504                            // Second 128-bit lane.
10505                            8, 24, 9, 25, 12, 28, 13, 29}))
10506     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10507   if (isShuffleEquivalent(V1, V2, Mask,
10508                           {// First 128-bit lane.
10509                            2, 18, 3, 19, 6, 22, 7, 23,
10510                            // Second 128-bit lane.
10511                            10, 26, 11, 27, 14, 30, 15, 31}))
10512     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10513
10514   // FIXME: Implement direct support for this type!
10515   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10516 }
10517
10518 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10519 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10520                                         const X86Subtarget *Subtarget,
10521                                         SelectionDAG &DAG) {
10522   SDLoc DL(Op);
10523   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10524   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10526   ArrayRef<int> Mask = SVOp->getMask();
10527   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10528   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10529
10530   // FIXME: Implement direct support for this type!
10531   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10532 }
10533
10534 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10535 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10536                                        const X86Subtarget *Subtarget,
10537                                        SelectionDAG &DAG) {
10538   SDLoc DL(Op);
10539   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10540   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10541   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10542   ArrayRef<int> Mask = SVOp->getMask();
10543   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10544   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10545
10546   // FIXME: Implement direct support for this type!
10547   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10548 }
10549
10550 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10551 ///
10552 /// This routine either breaks down the specific type of a 512-bit x86 vector
10553 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10554 /// together based on the available instructions.
10555 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10556                                         MVT VT, const X86Subtarget *Subtarget,
10557                                         SelectionDAG &DAG) {
10558   SDLoc DL(Op);
10559   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10560   ArrayRef<int> Mask = SVOp->getMask();
10561   assert(Subtarget->hasAVX512() &&
10562          "Cannot lower 512-bit vectors w/ basic ISA!");
10563
10564   // Check for being able to broadcast a single element.
10565   if (SDValue Broadcast =
10566           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10567     return Broadcast;
10568
10569   // Dispatch to each element type for lowering. If we don't have supprot for
10570   // specific element type shuffles at 512 bits, immediately split them and
10571   // lower them. Each lowering routine of a given type is allowed to assume that
10572   // the requisite ISA extensions for that element type are available.
10573   switch (VT.SimpleTy) {
10574   case MVT::v8f64:
10575     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10576   case MVT::v16f32:
10577     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10578   case MVT::v8i64:
10579     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10580   case MVT::v16i32:
10581     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10582   case MVT::v32i16:
10583     if (Subtarget->hasBWI())
10584       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10585     break;
10586   case MVT::v64i8:
10587     if (Subtarget->hasBWI())
10588       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10589     break;
10590
10591   default:
10592     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10593   }
10594
10595   // Otherwise fall back on splitting.
10596   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10597 }
10598
10599 /// \brief Top-level lowering for x86 vector shuffles.
10600 ///
10601 /// This handles decomposition, canonicalization, and lowering of all x86
10602 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10603 /// above in helper routines. The canonicalization attempts to widen shuffles
10604 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10605 /// s.t. only one of the two inputs needs to be tested, etc.
10606 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10607                                   SelectionDAG &DAG) {
10608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10609   ArrayRef<int> Mask = SVOp->getMask();
10610   SDValue V1 = Op.getOperand(0);
10611   SDValue V2 = Op.getOperand(1);
10612   MVT VT = Op.getSimpleValueType();
10613   int NumElements = VT.getVectorNumElements();
10614   SDLoc dl(Op);
10615
10616   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10617
10618   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10619   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10620   if (V1IsUndef && V2IsUndef)
10621     return DAG.getUNDEF(VT);
10622
10623   // When we create a shuffle node we put the UNDEF node to second operand,
10624   // but in some cases the first operand may be transformed to UNDEF.
10625   // In this case we should just commute the node.
10626   if (V1IsUndef)
10627     return DAG.getCommutedVectorShuffle(*SVOp);
10628
10629   // Check for non-undef masks pointing at an undef vector and make the masks
10630   // undef as well. This makes it easier to match the shuffle based solely on
10631   // the mask.
10632   if (V2IsUndef)
10633     for (int M : Mask)
10634       if (M >= NumElements) {
10635         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10636         for (int &M : NewMask)
10637           if (M >= NumElements)
10638             M = -1;
10639         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10640       }
10641
10642   // We actually see shuffles that are entirely re-arrangements of a set of
10643   // zero inputs. This mostly happens while decomposing complex shuffles into
10644   // simple ones. Directly lower these as a buildvector of zeros.
10645   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10646   if (Zeroable.all())
10647     return getZeroVector(VT, Subtarget, DAG, dl);
10648
10649   // Try to collapse shuffles into using a vector type with fewer elements but
10650   // wider element types. We cap this to not form integers or floating point
10651   // elements wider than 64 bits, but it might be interesting to form i128
10652   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10653   SmallVector<int, 16> WidenedMask;
10654   if (VT.getScalarSizeInBits() < 64 &&
10655       canWidenShuffleElements(Mask, WidenedMask)) {
10656     MVT NewEltVT = VT.isFloatingPoint()
10657                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10658                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10659     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10660     // Make sure that the new vector type is legal. For example, v2f64 isn't
10661     // legal on SSE1.
10662     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10663       V1 = DAG.getBitcast(NewVT, V1);
10664       V2 = DAG.getBitcast(NewVT, V2);
10665       return DAG.getBitcast(
10666           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10667     }
10668   }
10669
10670   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10671   for (int M : SVOp->getMask())
10672     if (M < 0)
10673       ++NumUndefElements;
10674     else if (M < NumElements)
10675       ++NumV1Elements;
10676     else
10677       ++NumV2Elements;
10678
10679   // Commute the shuffle as needed such that more elements come from V1 than
10680   // V2. This allows us to match the shuffle pattern strictly on how many
10681   // elements come from V1 without handling the symmetric cases.
10682   if (NumV2Elements > NumV1Elements)
10683     return DAG.getCommutedVectorShuffle(*SVOp);
10684
10685   // When the number of V1 and V2 elements are the same, try to minimize the
10686   // number of uses of V2 in the low half of the vector. When that is tied,
10687   // ensure that the sum of indices for V1 is equal to or lower than the sum
10688   // indices for V2. When those are equal, try to ensure that the number of odd
10689   // indices for V1 is lower than the number of odd indices for V2.
10690   if (NumV1Elements == NumV2Elements) {
10691     int LowV1Elements = 0, LowV2Elements = 0;
10692     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10693       if (M >= NumElements)
10694         ++LowV2Elements;
10695       else if (M >= 0)
10696         ++LowV1Elements;
10697     if (LowV2Elements > LowV1Elements) {
10698       return DAG.getCommutedVectorShuffle(*SVOp);
10699     } else if (LowV2Elements == LowV1Elements) {
10700       int SumV1Indices = 0, SumV2Indices = 0;
10701       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10702         if (SVOp->getMask()[i] >= NumElements)
10703           SumV2Indices += i;
10704         else if (SVOp->getMask()[i] >= 0)
10705           SumV1Indices += i;
10706       if (SumV2Indices < SumV1Indices) {
10707         return DAG.getCommutedVectorShuffle(*SVOp);
10708       } else if (SumV2Indices == SumV1Indices) {
10709         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10710         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10711           if (SVOp->getMask()[i] >= NumElements)
10712             NumV2OddIndices += i % 2;
10713           else if (SVOp->getMask()[i] >= 0)
10714             NumV1OddIndices += i % 2;
10715         if (NumV2OddIndices < NumV1OddIndices)
10716           return DAG.getCommutedVectorShuffle(*SVOp);
10717       }
10718     }
10719   }
10720
10721   // For each vector width, delegate to a specialized lowering routine.
10722   if (VT.getSizeInBits() == 128)
10723     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10724
10725   if (VT.getSizeInBits() == 256)
10726     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10727
10728   // Force AVX-512 vectors to be scalarized for now.
10729   // FIXME: Implement AVX-512 support!
10730   if (VT.getSizeInBits() == 512)
10731     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10732
10733   llvm_unreachable("Unimplemented!");
10734 }
10735
10736 // This function assumes its argument is a BUILD_VECTOR of constants or
10737 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10738 // true.
10739 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10740                                     unsigned &MaskValue) {
10741   MaskValue = 0;
10742   unsigned NumElems = BuildVector->getNumOperands();
10743   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10744   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10745   unsigned NumElemsInLane = NumElems / NumLanes;
10746
10747   // Blend for v16i16 should be symmetric for the both lanes.
10748   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10749     SDValue EltCond = BuildVector->getOperand(i);
10750     SDValue SndLaneEltCond =
10751         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10752
10753     int Lane1Cond = -1, Lane2Cond = -1;
10754     if (isa<ConstantSDNode>(EltCond))
10755       Lane1Cond = !isZero(EltCond);
10756     if (isa<ConstantSDNode>(SndLaneEltCond))
10757       Lane2Cond = !isZero(SndLaneEltCond);
10758
10759     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10760       // Lane1Cond != 0, means we want the first argument.
10761       // Lane1Cond == 0, means we want the second argument.
10762       // The encoding of this argument is 0 for the first argument, 1
10763       // for the second. Therefore, invert the condition.
10764       MaskValue |= !Lane1Cond << i;
10765     else if (Lane1Cond < 0)
10766       MaskValue |= !Lane2Cond << i;
10767     else
10768       return false;
10769   }
10770   return true;
10771 }
10772
10773 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10774 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10775                                            const X86Subtarget *Subtarget,
10776                                            SelectionDAG &DAG) {
10777   SDValue Cond = Op.getOperand(0);
10778   SDValue LHS = Op.getOperand(1);
10779   SDValue RHS = Op.getOperand(2);
10780   SDLoc dl(Op);
10781   MVT VT = Op.getSimpleValueType();
10782
10783   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10784     return SDValue();
10785   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10786
10787   // Only non-legal VSELECTs reach this lowering, convert those into generic
10788   // shuffles and re-use the shuffle lowering path for blends.
10789   SmallVector<int, 32> Mask;
10790   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10791     SDValue CondElt = CondBV->getOperand(i);
10792     Mask.push_back(
10793         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10794   }
10795   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10796 }
10797
10798 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10799   // A vselect where all conditions and data are constants can be optimized into
10800   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10801   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10802       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10803       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10804     return SDValue();
10805
10806   // Try to lower this to a blend-style vector shuffle. This can handle all
10807   // constant condition cases.
10808   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10809     return BlendOp;
10810
10811   // Variable blends are only legal from SSE4.1 onward.
10812   if (!Subtarget->hasSSE41())
10813     return SDValue();
10814
10815   // Only some types will be legal on some subtargets. If we can emit a legal
10816   // VSELECT-matching blend, return Op, and but if we need to expand, return
10817   // a null value.
10818   switch (Op.getSimpleValueType().SimpleTy) {
10819   default:
10820     // Most of the vector types have blends past SSE4.1.
10821     return Op;
10822
10823   case MVT::v32i8:
10824     // The byte blends for AVX vectors were introduced only in AVX2.
10825     if (Subtarget->hasAVX2())
10826       return Op;
10827
10828     return SDValue();
10829
10830   case MVT::v8i16:
10831   case MVT::v16i16:
10832     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10833     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10834       return Op;
10835
10836     // FIXME: We should custom lower this by fixing the condition and using i8
10837     // blends.
10838     return SDValue();
10839   }
10840 }
10841
10842 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10843   MVT VT = Op.getSimpleValueType();
10844   SDLoc dl(Op);
10845
10846   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10847     return SDValue();
10848
10849   if (VT.getSizeInBits() == 8) {
10850     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10851                                   Op.getOperand(0), Op.getOperand(1));
10852     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10853                                   DAG.getValueType(VT));
10854     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10855   }
10856
10857   if (VT.getSizeInBits() == 16) {
10858     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10859     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10860     if (Idx == 0)
10861       return DAG.getNode(
10862           ISD::TRUNCATE, dl, MVT::i16,
10863           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10864                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10865                       Op.getOperand(1)));
10866     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10867                                   Op.getOperand(0), Op.getOperand(1));
10868     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10869                                   DAG.getValueType(VT));
10870     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10871   }
10872
10873   if (VT == MVT::f32) {
10874     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10875     // the result back to FR32 register. It's only worth matching if the
10876     // result has a single use which is a store or a bitcast to i32.  And in
10877     // the case of a store, it's not worth it if the index is a constant 0,
10878     // because a MOVSSmr can be used instead, which is smaller and faster.
10879     if (!Op.hasOneUse())
10880       return SDValue();
10881     SDNode *User = *Op.getNode()->use_begin();
10882     if ((User->getOpcode() != ISD::STORE ||
10883          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10884           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10885         (User->getOpcode() != ISD::BITCAST ||
10886          User->getValueType(0) != MVT::i32))
10887       return SDValue();
10888     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10889                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10890                                   Op.getOperand(1));
10891     return DAG.getBitcast(MVT::f32, Extract);
10892   }
10893
10894   if (VT == MVT::i32 || VT == MVT::i64) {
10895     // ExtractPS/pextrq works with constant index.
10896     if (isa<ConstantSDNode>(Op.getOperand(1)))
10897       return Op;
10898   }
10899   return SDValue();
10900 }
10901
10902 /// Extract one bit from mask vector, like v16i1 or v8i1.
10903 /// AVX-512 feature.
10904 SDValue
10905 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10906   SDValue Vec = Op.getOperand(0);
10907   SDLoc dl(Vec);
10908   MVT VecVT = Vec.getSimpleValueType();
10909   SDValue Idx = Op.getOperand(1);
10910   MVT EltVT = Op.getSimpleValueType();
10911
10912   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10913   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10914          "Unexpected vector type in ExtractBitFromMaskVector");
10915
10916   // variable index can't be handled in mask registers,
10917   // extend vector to VR512
10918   if (!isa<ConstantSDNode>(Idx)) {
10919     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10920     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10921     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10922                               ExtVT.getVectorElementType(), Ext, Idx);
10923     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10924   }
10925
10926   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10927   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10928   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10929     rc = getRegClassFor(MVT::v16i1);
10930   unsigned MaxSift = rc->getSize()*8 - 1;
10931   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10932                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10933   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10934                     DAG.getConstant(MaxSift, dl, MVT::i8));
10935   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10936                        DAG.getIntPtrConstant(0, dl));
10937 }
10938
10939 SDValue
10940 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10941                                            SelectionDAG &DAG) const {
10942   SDLoc dl(Op);
10943   SDValue Vec = Op.getOperand(0);
10944   MVT VecVT = Vec.getSimpleValueType();
10945   SDValue Idx = Op.getOperand(1);
10946
10947   if (Op.getSimpleValueType() == MVT::i1)
10948     return ExtractBitFromMaskVector(Op, DAG);
10949
10950   if (!isa<ConstantSDNode>(Idx)) {
10951     if (VecVT.is512BitVector() ||
10952         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10953          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10954
10955       MVT MaskEltVT =
10956         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10957       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10958                                     MaskEltVT.getSizeInBits());
10959
10960       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10961       auto PtrVT = getPointerTy(DAG.getDataLayout());
10962       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10963                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10964                                  DAG.getConstant(0, dl, PtrVT));
10965       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10966       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10967                          DAG.getConstant(0, dl, PtrVT));
10968     }
10969     return SDValue();
10970   }
10971
10972   // If this is a 256-bit vector result, first extract the 128-bit vector and
10973   // then extract the element from the 128-bit vector.
10974   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10975
10976     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10977     // Get the 128-bit vector.
10978     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10979     MVT EltVT = VecVT.getVectorElementType();
10980
10981     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10982
10983     //if (IdxVal >= NumElems/2)
10984     //  IdxVal -= NumElems/2;
10985     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10986     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10987                        DAG.getConstant(IdxVal, dl, MVT::i32));
10988   }
10989
10990   assert(VecVT.is128BitVector() && "Unexpected vector length");
10991
10992   if (Subtarget->hasSSE41())
10993     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10994       return Res;
10995
10996   MVT VT = Op.getSimpleValueType();
10997   // TODO: handle v16i8.
10998   if (VT.getSizeInBits() == 16) {
10999     SDValue Vec = Op.getOperand(0);
11000     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11001     if (Idx == 0)
11002       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11003                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11004                                      DAG.getBitcast(MVT::v4i32, Vec),
11005                                      Op.getOperand(1)));
11006     // Transform it so it match pextrw which produces a 32-bit result.
11007     MVT EltVT = MVT::i32;
11008     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11009                                   Op.getOperand(0), Op.getOperand(1));
11010     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11011                                   DAG.getValueType(VT));
11012     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11013   }
11014
11015   if (VT.getSizeInBits() == 32) {
11016     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11017     if (Idx == 0)
11018       return Op;
11019
11020     // SHUFPS the element to the lowest double word, then movss.
11021     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11022     MVT VVT = Op.getOperand(0).getSimpleValueType();
11023     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11024                                        DAG.getUNDEF(VVT), Mask);
11025     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11026                        DAG.getIntPtrConstant(0, dl));
11027   }
11028
11029   if (VT.getSizeInBits() == 64) {
11030     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11031     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11032     //        to match extract_elt for f64.
11033     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11034     if (Idx == 0)
11035       return Op;
11036
11037     // UNPCKHPD the element to the lowest double word, then movsd.
11038     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11039     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11040     int Mask[2] = { 1, -1 };
11041     MVT VVT = Op.getOperand(0).getSimpleValueType();
11042     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11043                                        DAG.getUNDEF(VVT), Mask);
11044     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11045                        DAG.getIntPtrConstant(0, dl));
11046   }
11047
11048   return SDValue();
11049 }
11050
11051 /// Insert one bit to mask vector, like v16i1 or v8i1.
11052 /// AVX-512 feature.
11053 SDValue
11054 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11055   SDLoc dl(Op);
11056   SDValue Vec = Op.getOperand(0);
11057   SDValue Elt = Op.getOperand(1);
11058   SDValue Idx = Op.getOperand(2);
11059   MVT VecVT = Vec.getSimpleValueType();
11060
11061   if (!isa<ConstantSDNode>(Idx)) {
11062     // Non constant index. Extend source and destination,
11063     // insert element and then truncate the result.
11064     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11065     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11066     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11067       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11068       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11069     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11070   }
11071
11072   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11073   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11074   if (IdxVal)
11075     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11076                            DAG.getConstant(IdxVal, dl, MVT::i8));
11077   if (Vec.getOpcode() == ISD::UNDEF)
11078     return EltInVec;
11079   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11080 }
11081
11082 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11083                                                   SelectionDAG &DAG) const {
11084   MVT VT = Op.getSimpleValueType();
11085   MVT EltVT = VT.getVectorElementType();
11086
11087   if (EltVT == MVT::i1)
11088     return InsertBitToMaskVector(Op, DAG);
11089
11090   SDLoc dl(Op);
11091   SDValue N0 = Op.getOperand(0);
11092   SDValue N1 = Op.getOperand(1);
11093   SDValue N2 = Op.getOperand(2);
11094   if (!isa<ConstantSDNode>(N2))
11095     return SDValue();
11096   auto *N2C = cast<ConstantSDNode>(N2);
11097   unsigned IdxVal = N2C->getZExtValue();
11098
11099   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11100   // into that, and then insert the subvector back into the result.
11101   if (VT.is256BitVector() || VT.is512BitVector()) {
11102     // With a 256-bit vector, we can insert into the zero element efficiently
11103     // using a blend if we have AVX or AVX2 and the right data type.
11104     if (VT.is256BitVector() && IdxVal == 0) {
11105       // TODO: It is worthwhile to cast integer to floating point and back
11106       // and incur a domain crossing penalty if that's what we'll end up
11107       // doing anyway after extracting to a 128-bit vector.
11108       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11109           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11110         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11111         N2 = DAG.getIntPtrConstant(1, dl);
11112         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11113       }
11114     }
11115
11116     // Get the desired 128-bit vector chunk.
11117     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11118
11119     // Insert the element into the desired chunk.
11120     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11121     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11122
11123     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11124                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11125
11126     // Insert the changed part back into the bigger vector
11127     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11128   }
11129   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11130
11131   if (Subtarget->hasSSE41()) {
11132     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11133       unsigned Opc;
11134       if (VT == MVT::v8i16) {
11135         Opc = X86ISD::PINSRW;
11136       } else {
11137         assert(VT == MVT::v16i8);
11138         Opc = X86ISD::PINSRB;
11139       }
11140
11141       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11142       // argument.
11143       if (N1.getValueType() != MVT::i32)
11144         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11145       if (N2.getValueType() != MVT::i32)
11146         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11147       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11148     }
11149
11150     if (EltVT == MVT::f32) {
11151       // Bits [7:6] of the constant are the source select. This will always be
11152       //   zero here. The DAG Combiner may combine an extract_elt index into
11153       //   these bits. For example (insert (extract, 3), 2) could be matched by
11154       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11155       // Bits [5:4] of the constant are the destination select. This is the
11156       //   value of the incoming immediate.
11157       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11158       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11159
11160       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11161       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11162         // If this is an insertion of 32-bits into the low 32-bits of
11163         // a vector, we prefer to generate a blend with immediate rather
11164         // than an insertps. Blends are simpler operations in hardware and so
11165         // will always have equal or better performance than insertps.
11166         // But if optimizing for size and there's a load folding opportunity,
11167         // generate insertps because blendps does not have a 32-bit memory
11168         // operand form.
11169         N2 = DAG.getIntPtrConstant(1, dl);
11170         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11171         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11172       }
11173       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11174       // Create this as a scalar to vector..
11175       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11176       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11177     }
11178
11179     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11180       // PINSR* works with constant index.
11181       return Op;
11182     }
11183   }
11184
11185   if (EltVT == MVT::i8)
11186     return SDValue();
11187
11188   if (EltVT.getSizeInBits() == 16) {
11189     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11190     // as its second argument.
11191     if (N1.getValueType() != MVT::i32)
11192       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11193     if (N2.getValueType() != MVT::i32)
11194       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11195     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11196   }
11197   return SDValue();
11198 }
11199
11200 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11201   SDLoc dl(Op);
11202   MVT OpVT = Op.getSimpleValueType();
11203
11204   // If this is a 256-bit vector result, first insert into a 128-bit
11205   // vector and then insert into the 256-bit vector.
11206   if (!OpVT.is128BitVector()) {
11207     // Insert into a 128-bit vector.
11208     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11209     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11210                                  OpVT.getVectorNumElements() / SizeFactor);
11211
11212     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11213
11214     // Insert the 128-bit vector.
11215     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11216   }
11217
11218   if (OpVT == MVT::v1i64 &&
11219       Op.getOperand(0).getValueType() == MVT::i64)
11220     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11221
11222   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11223   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11224   return DAG.getBitcast(
11225       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11226 }
11227
11228 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11229 // a simple subregister reference or explicit instructions to grab
11230 // upper bits of a vector.
11231 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11232                                       SelectionDAG &DAG) {
11233   SDLoc dl(Op);
11234   SDValue In =  Op.getOperand(0);
11235   SDValue Idx = Op.getOperand(1);
11236   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11237   MVT ResVT   = Op.getSimpleValueType();
11238   MVT InVT    = In.getSimpleValueType();
11239
11240   if (Subtarget->hasFp256()) {
11241     if (ResVT.is128BitVector() &&
11242         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11243         isa<ConstantSDNode>(Idx)) {
11244       return Extract128BitVector(In, IdxVal, DAG, dl);
11245     }
11246     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11247         isa<ConstantSDNode>(Idx)) {
11248       return Extract256BitVector(In, IdxVal, DAG, dl);
11249     }
11250   }
11251   return SDValue();
11252 }
11253
11254 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11255 // simple superregister reference or explicit instructions to insert
11256 // the upper bits of a vector.
11257 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11258                                      SelectionDAG &DAG) {
11259   if (!Subtarget->hasAVX())
11260     return SDValue();
11261
11262   SDLoc dl(Op);
11263   SDValue Vec = Op.getOperand(0);
11264   SDValue SubVec = Op.getOperand(1);
11265   SDValue Idx = Op.getOperand(2);
11266
11267   if (!isa<ConstantSDNode>(Idx))
11268     return SDValue();
11269
11270   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11271   MVT OpVT = Op.getSimpleValueType();
11272   MVT SubVecVT = SubVec.getSimpleValueType();
11273
11274   // Fold two 16-byte subvector loads into one 32-byte load:
11275   // (insert_subvector (insert_subvector undef, (load addr), 0),
11276   //                   (load addr + 16), Elts/2)
11277   // --> load32 addr
11278   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11279       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11280       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11281     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11282     if (Idx2 && Idx2->getZExtValue() == 0) {
11283       SDValue SubVec2 = Vec.getOperand(1);
11284       // If needed, look through a bitcast to get to the load.
11285       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11286         SubVec2 = SubVec2.getOperand(0);
11287       
11288       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11289         bool Fast;
11290         unsigned Alignment = FirstLd->getAlignment();
11291         unsigned AS = FirstLd->getAddressSpace();
11292         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11293         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11294                                     OpVT, AS, Alignment, &Fast) && Fast) {
11295           SDValue Ops[] = { SubVec2, SubVec };
11296           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11297             return Ld;
11298         }
11299       }
11300     }
11301   }
11302
11303   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11304       SubVecVT.is128BitVector())
11305     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11306
11307   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11308     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11309
11310   if (OpVT.getVectorElementType() == MVT::i1) {
11311     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11312       return Op;
11313     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11314     SDValue Undef = DAG.getUNDEF(OpVT);
11315     unsigned NumElems = OpVT.getVectorNumElements();
11316     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11317
11318     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11319       // Zero upper bits of the Vec
11320       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11321       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11322
11323       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11324                                  SubVec, ZeroIdx);
11325       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11326       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11327     }
11328     if (IdxVal == 0) {
11329       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11330                                  SubVec, ZeroIdx);
11331       // Zero upper bits of the Vec2
11332       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11333       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11334       // Zero lower bits of the Vec
11335       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11336       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11337       // Merge them together
11338       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11339     }
11340   }
11341   return SDValue();
11342 }
11343
11344 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11345 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11346 // one of the above mentioned nodes. It has to be wrapped because otherwise
11347 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11348 // be used to form addressing mode. These wrapped nodes will be selected
11349 // into MOV32ri.
11350 SDValue
11351 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11352   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11353
11354   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11355   // global base reg.
11356   unsigned char OpFlag = 0;
11357   unsigned WrapperKind = X86ISD::Wrapper;
11358   CodeModel::Model M = DAG.getTarget().getCodeModel();
11359
11360   if (Subtarget->isPICStyleRIPRel() &&
11361       (M == CodeModel::Small || M == CodeModel::Kernel))
11362     WrapperKind = X86ISD::WrapperRIP;
11363   else if (Subtarget->isPICStyleGOT())
11364     OpFlag = X86II::MO_GOTOFF;
11365   else if (Subtarget->isPICStyleStubPIC())
11366     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11367
11368   auto PtrVT = getPointerTy(DAG.getDataLayout());
11369   SDValue Result = DAG.getTargetConstantPool(
11370       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11371   SDLoc DL(CP);
11372   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11373   // With PIC, the address is actually $g + Offset.
11374   if (OpFlag) {
11375     Result =
11376         DAG.getNode(ISD::ADD, DL, PtrVT,
11377                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11378   }
11379
11380   return Result;
11381 }
11382
11383 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11384   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11385
11386   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11387   // global base reg.
11388   unsigned char OpFlag = 0;
11389   unsigned WrapperKind = X86ISD::Wrapper;
11390   CodeModel::Model M = DAG.getTarget().getCodeModel();
11391
11392   if (Subtarget->isPICStyleRIPRel() &&
11393       (M == CodeModel::Small || M == CodeModel::Kernel))
11394     WrapperKind = X86ISD::WrapperRIP;
11395   else if (Subtarget->isPICStyleGOT())
11396     OpFlag = X86II::MO_GOTOFF;
11397   else if (Subtarget->isPICStyleStubPIC())
11398     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11399
11400   auto PtrVT = getPointerTy(DAG.getDataLayout());
11401   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11402   SDLoc DL(JT);
11403   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11404
11405   // With PIC, the address is actually $g + Offset.
11406   if (OpFlag)
11407     Result =
11408         DAG.getNode(ISD::ADD, DL, PtrVT,
11409                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11410
11411   return Result;
11412 }
11413
11414 SDValue
11415 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11416   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11417
11418   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11419   // global base reg.
11420   unsigned char OpFlag = 0;
11421   unsigned WrapperKind = X86ISD::Wrapper;
11422   CodeModel::Model M = DAG.getTarget().getCodeModel();
11423
11424   if (Subtarget->isPICStyleRIPRel() &&
11425       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11426     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11427       OpFlag = X86II::MO_GOTPCREL;
11428     WrapperKind = X86ISD::WrapperRIP;
11429   } else if (Subtarget->isPICStyleGOT()) {
11430     OpFlag = X86II::MO_GOT;
11431   } else if (Subtarget->isPICStyleStubPIC()) {
11432     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11433   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11434     OpFlag = X86II::MO_DARWIN_NONLAZY;
11435   }
11436
11437   auto PtrVT = getPointerTy(DAG.getDataLayout());
11438   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11439
11440   SDLoc DL(Op);
11441   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11442
11443   // With PIC, the address is actually $g + Offset.
11444   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11445       !Subtarget->is64Bit()) {
11446     Result =
11447         DAG.getNode(ISD::ADD, DL, PtrVT,
11448                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11449   }
11450
11451   // For symbols that require a load from a stub to get the address, emit the
11452   // load.
11453   if (isGlobalStubReference(OpFlag))
11454     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11455                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11456                          false, false, false, 0);
11457
11458   return Result;
11459 }
11460
11461 SDValue
11462 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11463   // Create the TargetBlockAddressAddress node.
11464   unsigned char OpFlags =
11465     Subtarget->ClassifyBlockAddressReference();
11466   CodeModel::Model M = DAG.getTarget().getCodeModel();
11467   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11468   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11469   SDLoc dl(Op);
11470   auto PtrVT = getPointerTy(DAG.getDataLayout());
11471   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11472
11473   if (Subtarget->isPICStyleRIPRel() &&
11474       (M == CodeModel::Small || M == CodeModel::Kernel))
11475     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11476   else
11477     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11478
11479   // With PIC, the address is actually $g + Offset.
11480   if (isGlobalRelativeToPICBase(OpFlags)) {
11481     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11482                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11483   }
11484
11485   return Result;
11486 }
11487
11488 SDValue
11489 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11490                                       int64_t Offset, SelectionDAG &DAG) const {
11491   // Create the TargetGlobalAddress node, folding in the constant
11492   // offset if it is legal.
11493   unsigned char OpFlags =
11494       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11495   CodeModel::Model M = DAG.getTarget().getCodeModel();
11496   auto PtrVT = getPointerTy(DAG.getDataLayout());
11497   SDValue Result;
11498   if (OpFlags == X86II::MO_NO_FLAG &&
11499       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11500     // A direct static reference to a global.
11501     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11502     Offset = 0;
11503   } else {
11504     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11505   }
11506
11507   if (Subtarget->isPICStyleRIPRel() &&
11508       (M == CodeModel::Small || M == CodeModel::Kernel))
11509     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11510   else
11511     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11512
11513   // With PIC, the address is actually $g + Offset.
11514   if (isGlobalRelativeToPICBase(OpFlags)) {
11515     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11516                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11517   }
11518
11519   // For globals that require a load from a stub to get the address, emit the
11520   // load.
11521   if (isGlobalStubReference(OpFlags))
11522     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11523                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11524                          false, false, false, 0);
11525
11526   // If there was a non-zero offset that we didn't fold, create an explicit
11527   // addition for it.
11528   if (Offset != 0)
11529     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11530                          DAG.getConstant(Offset, dl, PtrVT));
11531
11532   return Result;
11533 }
11534
11535 SDValue
11536 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11537   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11538   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11539   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11540 }
11541
11542 static SDValue
11543 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11544            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11545            unsigned char OperandFlags, bool LocalDynamic = false) {
11546   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11547   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11548   SDLoc dl(GA);
11549   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11550                                            GA->getValueType(0),
11551                                            GA->getOffset(),
11552                                            OperandFlags);
11553
11554   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11555                                            : X86ISD::TLSADDR;
11556
11557   if (InFlag) {
11558     SDValue Ops[] = { Chain,  TGA, *InFlag };
11559     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11560   } else {
11561     SDValue Ops[]  = { Chain, TGA };
11562     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11563   }
11564
11565   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11566   MFI->setAdjustsStack(true);
11567   MFI->setHasCalls(true);
11568
11569   SDValue Flag = Chain.getValue(1);
11570   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11571 }
11572
11573 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11574 static SDValue
11575 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11576                                 const EVT PtrVT) {
11577   SDValue InFlag;
11578   SDLoc dl(GA);  // ? function entry point might be better
11579   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11580                                    DAG.getNode(X86ISD::GlobalBaseReg,
11581                                                SDLoc(), PtrVT), InFlag);
11582   InFlag = Chain.getValue(1);
11583
11584   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11585 }
11586
11587 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11588 static SDValue
11589 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11590                                 const EVT PtrVT) {
11591   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11592                     X86::RAX, X86II::MO_TLSGD);
11593 }
11594
11595 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11596                                            SelectionDAG &DAG,
11597                                            const EVT PtrVT,
11598                                            bool is64Bit) {
11599   SDLoc dl(GA);
11600
11601   // Get the start address of the TLS block for this module.
11602   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11603       .getInfo<X86MachineFunctionInfo>();
11604   MFI->incNumLocalDynamicTLSAccesses();
11605
11606   SDValue Base;
11607   if (is64Bit) {
11608     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11609                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11610   } else {
11611     SDValue InFlag;
11612     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11613         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11614     InFlag = Chain.getValue(1);
11615     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11616                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11617   }
11618
11619   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11620   // of Base.
11621
11622   // Build x@dtpoff.
11623   unsigned char OperandFlags = X86II::MO_DTPOFF;
11624   unsigned WrapperKind = X86ISD::Wrapper;
11625   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11626                                            GA->getValueType(0),
11627                                            GA->getOffset(), OperandFlags);
11628   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11629
11630   // Add x@dtpoff with the base.
11631   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11632 }
11633
11634 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11635 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11636                                    const EVT PtrVT, TLSModel::Model model,
11637                                    bool is64Bit, bool isPIC) {
11638   SDLoc dl(GA);
11639
11640   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11641   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11642                                                          is64Bit ? 257 : 256));
11643
11644   SDValue ThreadPointer =
11645       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11646                   MachinePointerInfo(Ptr), false, false, false, 0);
11647
11648   unsigned char OperandFlags = 0;
11649   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11650   // initialexec.
11651   unsigned WrapperKind = X86ISD::Wrapper;
11652   if (model == TLSModel::LocalExec) {
11653     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11654   } else if (model == TLSModel::InitialExec) {
11655     if (is64Bit) {
11656       OperandFlags = X86II::MO_GOTTPOFF;
11657       WrapperKind = X86ISD::WrapperRIP;
11658     } else {
11659       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11660     }
11661   } else {
11662     llvm_unreachable("Unexpected model");
11663   }
11664
11665   // emit "addl x@ntpoff,%eax" (local exec)
11666   // or "addl x@indntpoff,%eax" (initial exec)
11667   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11668   SDValue TGA =
11669       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11670                                  GA->getOffset(), OperandFlags);
11671   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11672
11673   if (model == TLSModel::InitialExec) {
11674     if (isPIC && !is64Bit) {
11675       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11676                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11677                            Offset);
11678     }
11679
11680     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11681                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11682                          false, false, false, 0);
11683   }
11684
11685   // The address of the thread local variable is the add of the thread
11686   // pointer with the offset of the variable.
11687   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11688 }
11689
11690 SDValue
11691 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11692
11693   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11694   const GlobalValue *GV = GA->getGlobal();
11695   auto PtrVT = getPointerTy(DAG.getDataLayout());
11696
11697   if (Subtarget->isTargetELF()) {
11698     if (DAG.getTarget().Options.EmulatedTLS)
11699       return LowerToTLSEmulatedModel(GA, DAG);
11700     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11701     switch (model) {
11702       case TLSModel::GeneralDynamic:
11703         if (Subtarget->is64Bit())
11704           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11705         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11706       case TLSModel::LocalDynamic:
11707         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11708                                            Subtarget->is64Bit());
11709       case TLSModel::InitialExec:
11710       case TLSModel::LocalExec:
11711         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11712                                    DAG.getTarget().getRelocationModel() ==
11713                                        Reloc::PIC_);
11714     }
11715     llvm_unreachable("Unknown TLS model.");
11716   }
11717
11718   if (Subtarget->isTargetDarwin()) {
11719     // Darwin only has one model of TLS.  Lower to that.
11720     unsigned char OpFlag = 0;
11721     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11722                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11723
11724     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11725     // global base reg.
11726     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11727                  !Subtarget->is64Bit();
11728     if (PIC32)
11729       OpFlag = X86II::MO_TLVP_PIC_BASE;
11730     else
11731       OpFlag = X86II::MO_TLVP;
11732     SDLoc DL(Op);
11733     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11734                                                 GA->getValueType(0),
11735                                                 GA->getOffset(), OpFlag);
11736     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11737
11738     // With PIC32, the address is actually $g + Offset.
11739     if (PIC32)
11740       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11741                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11742                            Offset);
11743
11744     // Lowering the machine isd will make sure everything is in the right
11745     // location.
11746     SDValue Chain = DAG.getEntryNode();
11747     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11748     SDValue Args[] = { Chain, Offset };
11749     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11750
11751     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11752     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11753     MFI->setAdjustsStack(true);
11754
11755     // And our return value (tls address) is in the standard call return value
11756     // location.
11757     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11758     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11759   }
11760
11761   if (Subtarget->isTargetKnownWindowsMSVC() ||
11762       Subtarget->isTargetWindowsGNU()) {
11763     // Just use the implicit TLS architecture
11764     // Need to generate someting similar to:
11765     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11766     //                                  ; from TEB
11767     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11768     //   mov     rcx, qword [rdx+rcx*8]
11769     //   mov     eax, .tls$:tlsvar
11770     //   [rax+rcx] contains the address
11771     // Windows 64bit: gs:0x58
11772     // Windows 32bit: fs:__tls_array
11773
11774     SDLoc dl(GA);
11775     SDValue Chain = DAG.getEntryNode();
11776
11777     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11778     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11779     // use its literal value of 0x2C.
11780     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11781                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11782                                                              256)
11783                                         : Type::getInt32PtrTy(*DAG.getContext(),
11784                                                               257));
11785
11786     SDValue TlsArray = Subtarget->is64Bit()
11787                            ? DAG.getIntPtrConstant(0x58, dl)
11788                            : (Subtarget->isTargetWindowsGNU()
11789                                   ? DAG.getIntPtrConstant(0x2C, dl)
11790                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11791
11792     SDValue ThreadPointer =
11793         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11794                     false, false, 0);
11795
11796     SDValue res;
11797     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11798       res = ThreadPointer;
11799     } else {
11800       // Load the _tls_index variable
11801       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11802       if (Subtarget->is64Bit())
11803         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11804                              MachinePointerInfo(), MVT::i32, false, false,
11805                              false, 0);
11806       else
11807         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11808                           false, false, 0);
11809
11810       auto &DL = DAG.getDataLayout();
11811       SDValue Scale =
11812           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11813       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11814
11815       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11816     }
11817
11818     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11819                       false, 0);
11820
11821     // Get the offset of start of .tls section
11822     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11823                                              GA->getValueType(0),
11824                                              GA->getOffset(), X86II::MO_SECREL);
11825     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11826
11827     // The address of the thread local variable is the add of the thread
11828     // pointer with the offset of the variable.
11829     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11830   }
11831
11832   llvm_unreachable("TLS not implemented for this target.");
11833 }
11834
11835 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11836 /// and take a 2 x i32 value to shift plus a shift amount.
11837 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11838   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11839   MVT VT = Op.getSimpleValueType();
11840   unsigned VTBits = VT.getSizeInBits();
11841   SDLoc dl(Op);
11842   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11843   SDValue ShOpLo = Op.getOperand(0);
11844   SDValue ShOpHi = Op.getOperand(1);
11845   SDValue ShAmt  = Op.getOperand(2);
11846   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11847   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11848   // during isel.
11849   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11850                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11851   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11852                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11853                        : DAG.getConstant(0, dl, VT);
11854
11855   SDValue Tmp2, Tmp3;
11856   if (Op.getOpcode() == ISD::SHL_PARTS) {
11857     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11858     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11859   } else {
11860     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11861     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11862   }
11863
11864   // If the shift amount is larger or equal than the width of a part we can't
11865   // rely on the results of shld/shrd. Insert a test and select the appropriate
11866   // values for large shift amounts.
11867   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11868                                 DAG.getConstant(VTBits, dl, MVT::i8));
11869   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11870                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11871
11872   SDValue Hi, Lo;
11873   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11874   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11875   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11876
11877   if (Op.getOpcode() == ISD::SHL_PARTS) {
11878     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11879     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11880   } else {
11881     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11883   }
11884
11885   SDValue Ops[2] = { Lo, Hi };
11886   return DAG.getMergeValues(Ops, dl);
11887 }
11888
11889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11890                                            SelectionDAG &DAG) const {
11891   SDValue Src = Op.getOperand(0);
11892   MVT SrcVT = Src.getSimpleValueType();
11893   MVT VT = Op.getSimpleValueType();
11894   SDLoc dl(Op);
11895
11896   if (SrcVT.isVector()) {
11897     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11898       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11899                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11900                          DAG.getUNDEF(SrcVT)));
11901     }
11902     if (SrcVT.getVectorElementType() == MVT::i1) {
11903       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11904       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11905                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11906     }
11907     return SDValue();
11908   }
11909
11910   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11911          "Unknown SINT_TO_FP to lower!");
11912
11913   // These are really Legal; return the operand so the caller accepts it as
11914   // Legal.
11915   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11916     return Op;
11917   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11918       Subtarget->is64Bit()) {
11919     return Op;
11920   }
11921
11922   unsigned Size = SrcVT.getSizeInBits()/8;
11923   MachineFunction &MF = DAG.getMachineFunction();
11924   auto PtrVT = getPointerTy(MF.getDataLayout());
11925   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11926   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11927   SDValue Chain = DAG.getStore(
11928       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11929       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11930       false, 0);
11931   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11932 }
11933
11934 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11935                                      SDValue StackSlot,
11936                                      SelectionDAG &DAG) const {
11937   // Build the FILD
11938   SDLoc DL(Op);
11939   SDVTList Tys;
11940   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11941   if (useSSE)
11942     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11943   else
11944     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11945
11946   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11947
11948   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11949   MachineMemOperand *MMO;
11950   if (FI) {
11951     int SSFI = FI->getIndex();
11952     MMO = DAG.getMachineFunction().getMachineMemOperand(
11953         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11954         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11955   } else {
11956     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11957     StackSlot = StackSlot.getOperand(1);
11958   }
11959   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11960   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11961                                            X86ISD::FILD, DL,
11962                                            Tys, Ops, SrcVT, MMO);
11963
11964   if (useSSE) {
11965     Chain = Result.getValue(1);
11966     SDValue InFlag = Result.getValue(2);
11967
11968     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11969     // shouldn't be necessary except that RFP cannot be live across
11970     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11971     MachineFunction &MF = DAG.getMachineFunction();
11972     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11973     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11974     auto PtrVT = getPointerTy(MF.getDataLayout());
11975     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11976     Tys = DAG.getVTList(MVT::Other);
11977     SDValue Ops[] = {
11978       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11979     };
11980     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11981         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11982         MachineMemOperand::MOStore, SSFISize, SSFISize);
11983
11984     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11985                                     Ops, Op.getValueType(), MMO);
11986     Result = DAG.getLoad(
11987         Op.getValueType(), DL, Chain, StackSlot,
11988         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11989         false, false, false, 0);
11990   }
11991
11992   return Result;
11993 }
11994
11995 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11996 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11997                                                SelectionDAG &DAG) const {
11998   // This algorithm is not obvious. Here it is what we're trying to output:
11999   /*
12000      movq       %rax,  %xmm0
12001      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12002      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12003      #ifdef __SSE3__
12004        haddpd   %xmm0, %xmm0
12005      #else
12006        pshufd   $0x4e, %xmm0, %xmm1
12007        addpd    %xmm1, %xmm0
12008      #endif
12009   */
12010
12011   SDLoc dl(Op);
12012   LLVMContext *Context = DAG.getContext();
12013
12014   // Build some magic constants.
12015   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12016   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12017   auto PtrVT = getPointerTy(DAG.getDataLayout());
12018   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12019
12020   SmallVector<Constant*,2> CV1;
12021   CV1.push_back(
12022     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12023                                       APInt(64, 0x4330000000000000ULL))));
12024   CV1.push_back(
12025     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12026                                       APInt(64, 0x4530000000000000ULL))));
12027   Constant *C1 = ConstantVector::get(CV1);
12028   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12029
12030   // Load the 64-bit value into an XMM register.
12031   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12032                             Op.getOperand(0));
12033   SDValue CLod0 =
12034       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12035                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12036                   false, false, false, 16);
12037   SDValue Unpck1 =
12038       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12039
12040   SDValue CLod1 =
12041       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12042                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12043                   false, false, false, 16);
12044   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12045   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12046   SDValue Result;
12047
12048   if (Subtarget->hasSSE3()) {
12049     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12050     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12051   } else {
12052     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12053     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12054                                            S2F, 0x4E, DAG);
12055     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12056                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12057   }
12058
12059   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12060                      DAG.getIntPtrConstant(0, dl));
12061 }
12062
12063 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12064 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12065                                                SelectionDAG &DAG) const {
12066   SDLoc dl(Op);
12067   // FP constant to bias correct the final result.
12068   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12069                                    MVT::f64);
12070
12071   // Load the 32-bit value into an XMM register.
12072   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12073                              Op.getOperand(0));
12074
12075   // Zero out the upper parts of the register.
12076   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12077
12078   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12079                      DAG.getBitcast(MVT::v2f64, Load),
12080                      DAG.getIntPtrConstant(0, dl));
12081
12082   // Or the load with the bias.
12083   SDValue Or = DAG.getNode(
12084       ISD::OR, dl, MVT::v2i64,
12085       DAG.getBitcast(MVT::v2i64,
12086                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12087       DAG.getBitcast(MVT::v2i64,
12088                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12089   Or =
12090       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12091                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12092
12093   // Subtract the bias.
12094   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12095
12096   // Handle final rounding.
12097   EVT DestVT = Op.getValueType();
12098
12099   if (DestVT.bitsLT(MVT::f64))
12100     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12101                        DAG.getIntPtrConstant(0, dl));
12102   if (DestVT.bitsGT(MVT::f64))
12103     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12104
12105   // Handle final rounding.
12106   return Sub;
12107 }
12108
12109 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12110                                      const X86Subtarget &Subtarget) {
12111   // The algorithm is the following:
12112   // #ifdef __SSE4_1__
12113   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12114   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12115   //                                 (uint4) 0x53000000, 0xaa);
12116   // #else
12117   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12118   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12119   // #endif
12120   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12121   //     return (float4) lo + fhi;
12122
12123   SDLoc DL(Op);
12124   SDValue V = Op->getOperand(0);
12125   EVT VecIntVT = V.getValueType();
12126   bool Is128 = VecIntVT == MVT::v4i32;
12127   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12128   // If we convert to something else than the supported type, e.g., to v4f64,
12129   // abort early.
12130   if (VecFloatVT != Op->getValueType(0))
12131     return SDValue();
12132
12133   unsigned NumElts = VecIntVT.getVectorNumElements();
12134   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12135          "Unsupported custom type");
12136   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12137
12138   // In the #idef/#else code, we have in common:
12139   // - The vector of constants:
12140   // -- 0x4b000000
12141   // -- 0x53000000
12142   // - A shift:
12143   // -- v >> 16
12144
12145   // Create the splat vector for 0x4b000000.
12146   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12147   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12148                            CstLow, CstLow, CstLow, CstLow};
12149   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12150                                   makeArrayRef(&CstLowArray[0], NumElts));
12151   // Create the splat vector for 0x53000000.
12152   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12153   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12154                             CstHigh, CstHigh, CstHigh, CstHigh};
12155   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12156                                    makeArrayRef(&CstHighArray[0], NumElts));
12157
12158   // Create the right shift.
12159   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12160   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12161                              CstShift, CstShift, CstShift, CstShift};
12162   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12163                                     makeArrayRef(&CstShiftArray[0], NumElts));
12164   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12165
12166   SDValue Low, High;
12167   if (Subtarget.hasSSE41()) {
12168     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12169     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12170     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12171     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12172     // Low will be bitcasted right away, so do not bother bitcasting back to its
12173     // original type.
12174     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12175                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12176     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12177     //                                 (uint4) 0x53000000, 0xaa);
12178     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12179     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12180     // High will be bitcasted right away, so do not bother bitcasting back to
12181     // its original type.
12182     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12183                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12184   } else {
12185     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12186     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12187                                      CstMask, CstMask, CstMask);
12188     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12189     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12190     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12191
12192     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12193     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12194   }
12195
12196   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12197   SDValue CstFAdd = DAG.getConstantFP(
12198       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12199   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12200                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12201   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12202                                    makeArrayRef(&CstFAddArray[0], NumElts));
12203
12204   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12205   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12206   SDValue FHigh =
12207       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12208   //     return (float4) lo + fhi;
12209   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12210   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12211 }
12212
12213 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12214                                                SelectionDAG &DAG) const {
12215   SDValue N0 = Op.getOperand(0);
12216   MVT SVT = N0.getSimpleValueType();
12217   SDLoc dl(Op);
12218
12219   switch (SVT.SimpleTy) {
12220   default:
12221     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12222   case MVT::v4i8:
12223   case MVT::v4i16:
12224   case MVT::v8i8:
12225   case MVT::v8i16: {
12226     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12227     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12228                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12229   }
12230   case MVT::v4i32:
12231   case MVT::v8i32:
12232     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12233   case MVT::v16i8:
12234   case MVT::v16i16:
12235     if (Subtarget->hasAVX512())
12236       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12237                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12238   }
12239   llvm_unreachable(nullptr);
12240 }
12241
12242 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12243                                            SelectionDAG &DAG) const {
12244   SDValue N0 = Op.getOperand(0);
12245   SDLoc dl(Op);
12246   auto PtrVT = getPointerTy(DAG.getDataLayout());
12247
12248   if (Op.getValueType().isVector())
12249     return lowerUINT_TO_FP_vec(Op, DAG);
12250
12251   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12252   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12253   // the optimization here.
12254   if (DAG.SignBitIsZero(N0))
12255     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12256
12257   MVT SrcVT = N0.getSimpleValueType();
12258   MVT DstVT = Op.getSimpleValueType();
12259   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12260     return LowerUINT_TO_FP_i64(Op, DAG);
12261   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12262     return LowerUINT_TO_FP_i32(Op, DAG);
12263   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12264     return SDValue();
12265
12266   // Make a 64-bit buffer, and use it to build an FILD.
12267   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12268   if (SrcVT == MVT::i32) {
12269     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12270     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12271     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12272                                   StackSlot, MachinePointerInfo(),
12273                                   false, false, 0);
12274     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12275                                   OffsetSlot, MachinePointerInfo(),
12276                                   false, false, 0);
12277     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12278     return Fild;
12279   }
12280
12281   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12282   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12283                                StackSlot, MachinePointerInfo(),
12284                                false, false, 0);
12285   // For i64 source, we need to add the appropriate power of 2 if the input
12286   // was negative.  This is the same as the optimization in
12287   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12288   // we must be careful to do the computation in x87 extended precision, not
12289   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12290   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12291   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12292       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12293       MachineMemOperand::MOLoad, 8, 8);
12294
12295   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12296   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12297   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12298                                          MVT::i64, MMO);
12299
12300   APInt FF(32, 0x5F800000ULL);
12301
12302   // Check whether the sign bit is set.
12303   SDValue SignSet = DAG.getSetCC(
12304       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12305       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12306
12307   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12308   SDValue FudgePtr = DAG.getConstantPool(
12309       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12310
12311   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12312   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12313   SDValue Four = DAG.getIntPtrConstant(4, dl);
12314   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12315                                Zero, Four);
12316   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12317
12318   // Load the value out, extending it from f32 to f80.
12319   // FIXME: Avoid the extend by constructing the right constant pool?
12320   SDValue Fudge = DAG.getExtLoad(
12321       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12322       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12323       false, false, false, 4);
12324   // Extend everything to 80 bits to force it to be done on x87.
12325   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12326   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12327                      DAG.getIntPtrConstant(0, dl));
12328 }
12329
12330 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12331 // is legal, or has an f16 source (which needs to be promoted to f32),
12332 // just return an <SDValue(), SDValue()> pair.
12333 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12334 // to i16, i32 or i64, and we lower it to a legal sequence.
12335 // If lowered to the final integer result we return a <result, SDValue()> pair.
12336 // Otherwise we lower it to a sequence ending with a FIST, return a
12337 // <FIST, StackSlot> pair, and the caller is responsible for loading
12338 // the final integer result from StackSlot.
12339 std::pair<SDValue,SDValue>
12340 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12341                                    bool IsSigned, bool IsReplace) const {
12342   SDLoc DL(Op);
12343
12344   EVT DstTy = Op.getValueType();
12345   EVT TheVT = Op.getOperand(0).getValueType();
12346   auto PtrVT = getPointerTy(DAG.getDataLayout());
12347
12348   if (TheVT == MVT::f16)
12349     // We need to promote the f16 to f32 before using the lowering
12350     // in this routine.
12351     return std::make_pair(SDValue(), SDValue());
12352
12353   assert((TheVT == MVT::f32 ||
12354           TheVT == MVT::f64 ||
12355           TheVT == MVT::f80) &&
12356          "Unexpected FP operand type in FP_TO_INTHelper");
12357
12358   // If using FIST to compute an unsigned i64, we'll need some fixup
12359   // to handle values above the maximum signed i64.  A FIST is always
12360   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12361   bool UnsignedFixup = !IsSigned &&
12362                        DstTy == MVT::i64 &&
12363                        (!Subtarget->is64Bit() ||
12364                         !isScalarFPTypeInSSEReg(TheVT));
12365
12366   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12367     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12368     // The low 32 bits of the fist result will have the correct uint32 result.
12369     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12370     DstTy = MVT::i64;
12371   }
12372
12373   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12374          DstTy.getSimpleVT() >= MVT::i16 &&
12375          "Unknown FP_TO_INT to lower!");
12376
12377   // These are really Legal.
12378   if (DstTy == MVT::i32 &&
12379       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12380     return std::make_pair(SDValue(), SDValue());
12381   if (Subtarget->is64Bit() &&
12382       DstTy == MVT::i64 &&
12383       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12384     return std::make_pair(SDValue(), SDValue());
12385
12386   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12387   // stack slot.
12388   MachineFunction &MF = DAG.getMachineFunction();
12389   unsigned MemSize = DstTy.getSizeInBits()/8;
12390   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12391   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12392
12393   unsigned Opc;
12394   switch (DstTy.getSimpleVT().SimpleTy) {
12395   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12396   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12397   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12398   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12399   }
12400
12401   SDValue Chain = DAG.getEntryNode();
12402   SDValue Value = Op.getOperand(0);
12403   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12404
12405   if (UnsignedFixup) {
12406     //
12407     // Conversion to unsigned i64 is implemented with a select,
12408     // depending on whether the source value fits in the range
12409     // of a signed i64.  Let Thresh be the FP equivalent of
12410     // 0x8000000000000000ULL.
12411     //
12412     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12413     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12414     //  Fist-to-mem64 FistSrc
12415     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12416     //  to XOR'ing the high 32 bits with Adjust.
12417     //
12418     // Being a power of 2, Thresh is exactly representable in all FP formats.
12419     // For X87 we'd like to use the smallest FP type for this constant, but
12420     // for DAG type consistency we have to match the FP operand type.
12421
12422     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12423     APFloat::opStatus Status = APFloat::opOK;
12424     bool LosesInfo = false;
12425     if (TheVT == MVT::f64)
12426       // The rounding mode is irrelevant as the conversion should be exact.
12427       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12428                               &LosesInfo);
12429     else if (TheVT == MVT::f80)
12430       Status = Thresh.convert(APFloat::x87DoubleExtended,
12431                               APFloat::rmNearestTiesToEven, &LosesInfo);
12432
12433     assert(Status == APFloat::opOK && !LosesInfo &&
12434            "FP conversion should have been exact");
12435
12436     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12437
12438     SDValue Cmp = DAG.getSetCC(DL,
12439                                getSetCCResultType(DAG.getDataLayout(),
12440                                                   *DAG.getContext(), TheVT),
12441                                Value, ThreshVal, ISD::SETLT);
12442     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12443                            DAG.getConstant(0, DL, MVT::i32),
12444                            DAG.getConstant(0x80000000, DL, MVT::i32));
12445     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12446     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12447                                               *DAG.getContext(), TheVT),
12448                        Value, ThreshVal, ISD::SETLT);
12449     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12450   }
12451
12452   // FIXME This causes a redundant load/store if the SSE-class value is already
12453   // in memory, such as if it is on the callstack.
12454   if (isScalarFPTypeInSSEReg(TheVT)) {
12455     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12456     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12457                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12458                          false, 0);
12459     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12460     SDValue Ops[] = {
12461       Chain, StackSlot, DAG.getValueType(TheVT)
12462     };
12463
12464     MachineMemOperand *MMO =
12465         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12466                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12467     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12468     Chain = Value.getValue(1);
12469     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12470     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12471   }
12472
12473   MachineMemOperand *MMO =
12474       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12475                               MachineMemOperand::MOStore, MemSize, MemSize);
12476
12477   if (UnsignedFixup) {
12478
12479     // Insert the FIST, load its result as two i32's,
12480     // and XOR the high i32 with Adjust.
12481
12482     SDValue FistOps[] = { Chain, Value, StackSlot };
12483     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12484                                            FistOps, DstTy, MMO);
12485
12486     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12487                                 MachinePointerInfo(),
12488                                 false, false, false, 0);
12489     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12490                                    DAG.getConstant(4, DL, PtrVT));
12491
12492     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12493                                  MachinePointerInfo(),
12494                                  false, false, false, 0);
12495     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12496
12497     if (Subtarget->is64Bit()) {
12498       // Join High32 and Low32 into a 64-bit result.
12499       // (High32 << 32) | Low32
12500       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12501       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12502       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12503                            DAG.getConstant(32, DL, MVT::i8));
12504       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12505       return std::make_pair(Result, SDValue());
12506     }
12507
12508     SDValue ResultOps[] = { Low32, High32 };
12509
12510     SDValue pair = IsReplace
12511       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12512       : DAG.getMergeValues(ResultOps, DL);
12513     return std::make_pair(pair, SDValue());
12514   } else {
12515     // Build the FP_TO_INT*_IN_MEM
12516     SDValue Ops[] = { Chain, Value, StackSlot };
12517     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12518                                            Ops, DstTy, MMO);
12519     return std::make_pair(FIST, StackSlot);
12520   }
12521 }
12522
12523 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12524                               const X86Subtarget *Subtarget) {
12525   MVT VT = Op->getSimpleValueType(0);
12526   SDValue In = Op->getOperand(0);
12527   MVT InVT = In.getSimpleValueType();
12528   SDLoc dl(Op);
12529
12530   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12531     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12532
12533   // Optimize vectors in AVX mode:
12534   //
12535   //   v8i16 -> v8i32
12536   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12537   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12538   //   Concat upper and lower parts.
12539   //
12540   //   v4i32 -> v4i64
12541   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12542   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12543   //   Concat upper and lower parts.
12544   //
12545
12546   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12547       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12548       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12549     return SDValue();
12550
12551   if (Subtarget->hasInt256())
12552     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12553
12554   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12555   SDValue Undef = DAG.getUNDEF(InVT);
12556   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12557   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12558   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12559
12560   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12561                              VT.getVectorNumElements()/2);
12562
12563   OpLo = DAG.getBitcast(HVT, OpLo);
12564   OpHi = DAG.getBitcast(HVT, OpHi);
12565
12566   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12567 }
12568
12569 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12570                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12571   MVT VT = Op->getSimpleValueType(0);
12572   SDValue In = Op->getOperand(0);
12573   MVT InVT = In.getSimpleValueType();
12574   SDLoc DL(Op);
12575   unsigned int NumElts = VT.getVectorNumElements();
12576   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12577     return SDValue();
12578
12579   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12580     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12581
12582   assert(InVT.getVectorElementType() == MVT::i1);
12583   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12584   SDValue One =
12585    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12586   SDValue Zero =
12587    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12588
12589   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12590   if (VT.is512BitVector())
12591     return V;
12592   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12593 }
12594
12595 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12596                                SelectionDAG &DAG) {
12597   if (Subtarget->hasFp256())
12598     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12599       return Res;
12600
12601   return SDValue();
12602 }
12603
12604 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12605                                 SelectionDAG &DAG) {
12606   SDLoc DL(Op);
12607   MVT VT = Op.getSimpleValueType();
12608   SDValue In = Op.getOperand(0);
12609   MVT SVT = In.getSimpleValueType();
12610
12611   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12612     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12613
12614   if (Subtarget->hasFp256())
12615     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12616       return Res;
12617
12618   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12619          VT.getVectorNumElements() != SVT.getVectorNumElements());
12620   return SDValue();
12621 }
12622
12623 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12624   SDLoc DL(Op);
12625   MVT VT = Op.getSimpleValueType();
12626   SDValue In = Op.getOperand(0);
12627   MVT InVT = In.getSimpleValueType();
12628
12629   if (VT == MVT::i1) {
12630     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12631            "Invalid scalar TRUNCATE operation");
12632     if (InVT.getSizeInBits() >= 32)
12633       return SDValue();
12634     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12635     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12636   }
12637   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12638          "Invalid TRUNCATE operation");
12639
12640   // move vector to mask - truncate solution for SKX
12641   if (VT.getVectorElementType() == MVT::i1) {
12642     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12643         Subtarget->hasBWI())
12644       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12645     if ((InVT.is256BitVector() || InVT.is128BitVector())
12646         && InVT.getScalarSizeInBits() <= 16 &&
12647         Subtarget->hasBWI() && Subtarget->hasVLX())
12648       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12649     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12650         Subtarget->hasDQI())
12651       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12652     if ((InVT.is256BitVector() || InVT.is128BitVector())
12653         && InVT.getScalarSizeInBits() >= 32 &&
12654         Subtarget->hasDQI() && Subtarget->hasVLX())
12655       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12656   }
12657
12658   if (VT.getVectorElementType() == MVT::i1) {
12659     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12660     unsigned NumElts = InVT.getVectorNumElements();
12661     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12662     if (InVT.getSizeInBits() < 512) {
12663       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12664       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12665       InVT = ExtVT;
12666     }
12667
12668     SDValue OneV =
12669      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12670     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12671     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12672   }
12673
12674   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12675   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12676       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12677     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12678
12679   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12680     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12681     if (Subtarget->hasInt256()) {
12682       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12683       In = DAG.getBitcast(MVT::v8i32, In);
12684       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12685                                 ShufMask);
12686       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12687                          DAG.getIntPtrConstant(0, DL));
12688     }
12689
12690     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12691                                DAG.getIntPtrConstant(0, DL));
12692     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12693                                DAG.getIntPtrConstant(2, DL));
12694     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12695     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12696     static const int ShufMask[] = {0, 2, 4, 6};
12697     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12698   }
12699
12700   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12701     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12702     if (Subtarget->hasInt256()) {
12703       In = DAG.getBitcast(MVT::v32i8, In);
12704
12705       SmallVector<SDValue,32> pshufbMask;
12706       for (unsigned i = 0; i < 2; ++i) {
12707         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12708         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12709         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12710         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12711         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12712         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12713         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12714         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12715         for (unsigned j = 0; j < 8; ++j)
12716           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12717       }
12718       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12719       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12720       In = DAG.getBitcast(MVT::v4i64, In);
12721
12722       static const int ShufMask[] = {0,  2,  -1,  -1};
12723       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12724                                 &ShufMask[0]);
12725       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12726                        DAG.getIntPtrConstant(0, DL));
12727       return DAG.getBitcast(VT, In);
12728     }
12729
12730     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12731                                DAG.getIntPtrConstant(0, DL));
12732
12733     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12734                                DAG.getIntPtrConstant(4, DL));
12735
12736     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12737     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12738
12739     // The PSHUFB mask:
12740     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12741                                    -1, -1, -1, -1, -1, -1, -1, -1};
12742
12743     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12744     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12745     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12746
12747     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12748     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12749
12750     // The MOVLHPS Mask:
12751     static const int ShufMask2[] = {0, 1, 4, 5};
12752     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12753     return DAG.getBitcast(MVT::v8i16, res);
12754   }
12755
12756   // Handle truncation of V256 to V128 using shuffles.
12757   if (!VT.is128BitVector() || !InVT.is256BitVector())
12758     return SDValue();
12759
12760   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12761
12762   unsigned NumElems = VT.getVectorNumElements();
12763   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12764
12765   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12766   // Prepare truncation shuffle mask
12767   for (unsigned i = 0; i != NumElems; ++i)
12768     MaskVec[i] = i * 2;
12769   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12770                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12771   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12772                      DAG.getIntPtrConstant(0, DL));
12773 }
12774
12775 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12776                                            SelectionDAG &DAG) const {
12777   assert(!Op.getSimpleValueType().isVector());
12778
12779   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12780     /*IsSigned=*/ true, /*IsReplace=*/ false);
12781   SDValue FIST = Vals.first, StackSlot = Vals.second;
12782   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12783   if (!FIST.getNode())
12784     return Op;
12785
12786   if (StackSlot.getNode())
12787     // Load the result.
12788     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12789                        FIST, StackSlot, MachinePointerInfo(),
12790                        false, false, false, 0);
12791
12792   // The node is the result.
12793   return FIST;
12794 }
12795
12796 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12797                                            SelectionDAG &DAG) const {
12798   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12799     /*IsSigned=*/ false, /*IsReplace=*/ false);
12800   SDValue FIST = Vals.first, StackSlot = Vals.second;
12801   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12802   if (!FIST.getNode())
12803     return Op;
12804
12805   if (StackSlot.getNode())
12806     // Load the result.
12807     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12808                        FIST, StackSlot, MachinePointerInfo(),
12809                        false, false, false, 0);
12810
12811   // The node is the result.
12812   return FIST;
12813 }
12814
12815 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12816   SDLoc DL(Op);
12817   MVT VT = Op.getSimpleValueType();
12818   SDValue In = Op.getOperand(0);
12819   MVT SVT = In.getSimpleValueType();
12820
12821   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12822
12823   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12824                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12825                                  In, DAG.getUNDEF(SVT)));
12826 }
12827
12828 /// The only differences between FABS and FNEG are the mask and the logic op.
12829 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12830 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12831   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12832          "Wrong opcode for lowering FABS or FNEG.");
12833
12834   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12835
12836   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12837   // into an FNABS. We'll lower the FABS after that if it is still in use.
12838   if (IsFABS)
12839     for (SDNode *User : Op->uses())
12840       if (User->getOpcode() == ISD::FNEG)
12841         return Op;
12842
12843   SDLoc dl(Op);
12844   MVT VT = Op.getSimpleValueType();
12845
12846   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12847   // decide if we should generate a 16-byte constant mask when we only need 4 or
12848   // 8 bytes for the scalar case.
12849
12850   MVT LogicVT;
12851   MVT EltVT;
12852   unsigned NumElts;
12853
12854   if (VT.isVector()) {
12855     LogicVT = VT;
12856     EltVT = VT.getVectorElementType();
12857     NumElts = VT.getVectorNumElements();
12858   } else {
12859     // There are no scalar bitwise logical SSE/AVX instructions, so we
12860     // generate a 16-byte vector constant and logic op even for the scalar case.
12861     // Using a 16-byte mask allows folding the load of the mask with
12862     // the logic op, so it can save (~4 bytes) on code size.
12863     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12864     EltVT = VT;
12865     NumElts = (VT == MVT::f64) ? 2 : 4;
12866   }
12867
12868   unsigned EltBits = EltVT.getSizeInBits();
12869   LLVMContext *Context = DAG.getContext();
12870   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12871   APInt MaskElt =
12872     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12873   Constant *C = ConstantInt::get(*Context, MaskElt);
12874   C = ConstantVector::getSplat(NumElts, C);
12875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12876   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12877   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12878   SDValue Mask =
12879       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12880                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12881                   false, false, false, Alignment);
12882
12883   SDValue Op0 = Op.getOperand(0);
12884   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12885   unsigned LogicOp =
12886     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12887   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12888
12889   if (VT.isVector())
12890     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12891
12892   // For the scalar case extend to a 128-bit vector, perform the logic op,
12893   // and extract the scalar result back out.
12894   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12895   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12896   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12897                      DAG.getIntPtrConstant(0, dl));
12898 }
12899
12900 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12902   LLVMContext *Context = DAG.getContext();
12903   SDValue Op0 = Op.getOperand(0);
12904   SDValue Op1 = Op.getOperand(1);
12905   SDLoc dl(Op);
12906   MVT VT = Op.getSimpleValueType();
12907   MVT SrcVT = Op1.getSimpleValueType();
12908
12909   // If second operand is smaller, extend it first.
12910   if (SrcVT.bitsLT(VT)) {
12911     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12912     SrcVT = VT;
12913   }
12914   // And if it is bigger, shrink it first.
12915   if (SrcVT.bitsGT(VT)) {
12916     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12917     SrcVT = VT;
12918   }
12919
12920   // At this point the operands and the result should have the same
12921   // type, and that won't be f80 since that is not custom lowered.
12922
12923   const fltSemantics &Sem =
12924       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12925   const unsigned SizeInBits = VT.getSizeInBits();
12926
12927   SmallVector<Constant *, 4> CV(
12928       VT == MVT::f64 ? 2 : 4,
12929       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12930
12931   // First, clear all bits but the sign bit from the second operand (sign).
12932   CV[0] = ConstantFP::get(*Context,
12933                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12934   Constant *C = ConstantVector::get(CV);
12935   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12936   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12937
12938   // Perform all logic operations as 16-byte vectors because there are no
12939   // scalar FP logic instructions in SSE. This allows load folding of the
12940   // constants into the logic instructions.
12941   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12942   SDValue Mask1 =
12943       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12944                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12945                   false, false, false, 16);
12946   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12947   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12948
12949   // Next, clear the sign bit from the first operand (magnitude).
12950   // If it's a constant, we can clear it here.
12951   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12952     APFloat APF = Op0CN->getValueAPF();
12953     // If the magnitude is a positive zero, the sign bit alone is enough.
12954     if (APF.isPosZero())
12955       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12956                          DAG.getIntPtrConstant(0, dl));
12957     APF.clearSign();
12958     CV[0] = ConstantFP::get(*Context, APF);
12959   } else {
12960     CV[0] = ConstantFP::get(
12961         *Context,
12962         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12963   }
12964   C = ConstantVector::get(CV);
12965   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12966   SDValue Val =
12967       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12968                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12969                   false, false, false, 16);
12970   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12971   if (!isa<ConstantFPSDNode>(Op0)) {
12972     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12973     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12974   }
12975   // OR the magnitude value with the sign bit.
12976   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12977   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12978                      DAG.getIntPtrConstant(0, dl));
12979 }
12980
12981 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12982   SDValue N0 = Op.getOperand(0);
12983   SDLoc dl(Op);
12984   MVT VT = Op.getSimpleValueType();
12985
12986   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12987   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12988                                   DAG.getConstant(1, dl, VT));
12989   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12990 }
12991
12992 // Check whether an OR'd tree is PTEST-able.
12993 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12994                                       SelectionDAG &DAG) {
12995   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12996
12997   if (!Subtarget->hasSSE41())
12998     return SDValue();
12999
13000   if (!Op->hasOneUse())
13001     return SDValue();
13002
13003   SDNode *N = Op.getNode();
13004   SDLoc DL(N);
13005
13006   SmallVector<SDValue, 8> Opnds;
13007   DenseMap<SDValue, unsigned> VecInMap;
13008   SmallVector<SDValue, 8> VecIns;
13009   EVT VT = MVT::Other;
13010
13011   // Recognize a special case where a vector is casted into wide integer to
13012   // test all 0s.
13013   Opnds.push_back(N->getOperand(0));
13014   Opnds.push_back(N->getOperand(1));
13015
13016   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13017     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13018     // BFS traverse all OR'd operands.
13019     if (I->getOpcode() == ISD::OR) {
13020       Opnds.push_back(I->getOperand(0));
13021       Opnds.push_back(I->getOperand(1));
13022       // Re-evaluate the number of nodes to be traversed.
13023       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13024       continue;
13025     }
13026
13027     // Quit if a non-EXTRACT_VECTOR_ELT
13028     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13029       return SDValue();
13030
13031     // Quit if without a constant index.
13032     SDValue Idx = I->getOperand(1);
13033     if (!isa<ConstantSDNode>(Idx))
13034       return SDValue();
13035
13036     SDValue ExtractedFromVec = I->getOperand(0);
13037     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13038     if (M == VecInMap.end()) {
13039       VT = ExtractedFromVec.getValueType();
13040       // Quit if not 128/256-bit vector.
13041       if (!VT.is128BitVector() && !VT.is256BitVector())
13042         return SDValue();
13043       // Quit if not the same type.
13044       if (VecInMap.begin() != VecInMap.end() &&
13045           VT != VecInMap.begin()->first.getValueType())
13046         return SDValue();
13047       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13048       VecIns.push_back(ExtractedFromVec);
13049     }
13050     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13051   }
13052
13053   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13054          "Not extracted from 128-/256-bit vector.");
13055
13056   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13057
13058   for (DenseMap<SDValue, unsigned>::const_iterator
13059         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13060     // Quit if not all elements are used.
13061     if (I->second != FullMask)
13062       return SDValue();
13063   }
13064
13065   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13066
13067   // Cast all vectors into TestVT for PTEST.
13068   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13069     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13070
13071   // If more than one full vectors are evaluated, OR them first before PTEST.
13072   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13073     // Each iteration will OR 2 nodes and append the result until there is only
13074     // 1 node left, i.e. the final OR'd value of all vectors.
13075     SDValue LHS = VecIns[Slot];
13076     SDValue RHS = VecIns[Slot + 1];
13077     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13078   }
13079
13080   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13081                      VecIns.back(), VecIns.back());
13082 }
13083
13084 /// \brief return true if \c Op has a use that doesn't just read flags.
13085 static bool hasNonFlagsUse(SDValue Op) {
13086   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13087        ++UI) {
13088     SDNode *User = *UI;
13089     unsigned UOpNo = UI.getOperandNo();
13090     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13091       // Look pass truncate.
13092       UOpNo = User->use_begin().getOperandNo();
13093       User = *User->use_begin();
13094     }
13095
13096     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13097         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13098       return true;
13099   }
13100   return false;
13101 }
13102
13103 /// Emit nodes that will be selected as "test Op0,Op0", or something
13104 /// equivalent.
13105 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13106                                     SelectionDAG &DAG) const {
13107   if (Op.getValueType() == MVT::i1) {
13108     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13109     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13110                        DAG.getConstant(0, dl, MVT::i8));
13111   }
13112   // CF and OF aren't always set the way we want. Determine which
13113   // of these we need.
13114   bool NeedCF = false;
13115   bool NeedOF = false;
13116   switch (X86CC) {
13117   default: break;
13118   case X86::COND_A: case X86::COND_AE:
13119   case X86::COND_B: case X86::COND_BE:
13120     NeedCF = true;
13121     break;
13122   case X86::COND_G: case X86::COND_GE:
13123   case X86::COND_L: case X86::COND_LE:
13124   case X86::COND_O: case X86::COND_NO: {
13125     // Check if we really need to set the
13126     // Overflow flag. If NoSignedWrap is present
13127     // that is not actually needed.
13128     switch (Op->getOpcode()) {
13129     case ISD::ADD:
13130     case ISD::SUB:
13131     case ISD::MUL:
13132     case ISD::SHL: {
13133       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13134       if (BinNode->Flags.hasNoSignedWrap())
13135         break;
13136     }
13137     default:
13138       NeedOF = true;
13139       break;
13140     }
13141     break;
13142   }
13143   }
13144   // See if we can use the EFLAGS value from the operand instead of
13145   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13146   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13147   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13148     // Emit a CMP with 0, which is the TEST pattern.
13149     //if (Op.getValueType() == MVT::i1)
13150     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13151     //                     DAG.getConstant(0, MVT::i1));
13152     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13153                        DAG.getConstant(0, dl, Op.getValueType()));
13154   }
13155   unsigned Opcode = 0;
13156   unsigned NumOperands = 0;
13157
13158   // Truncate operations may prevent the merge of the SETCC instruction
13159   // and the arithmetic instruction before it. Attempt to truncate the operands
13160   // of the arithmetic instruction and use a reduced bit-width instruction.
13161   bool NeedTruncation = false;
13162   SDValue ArithOp = Op;
13163   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13164     SDValue Arith = Op->getOperand(0);
13165     // Both the trunc and the arithmetic op need to have one user each.
13166     if (Arith->hasOneUse())
13167       switch (Arith.getOpcode()) {
13168         default: break;
13169         case ISD::ADD:
13170         case ISD::SUB:
13171         case ISD::AND:
13172         case ISD::OR:
13173         case ISD::XOR: {
13174           NeedTruncation = true;
13175           ArithOp = Arith;
13176         }
13177       }
13178   }
13179
13180   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13181   // which may be the result of a CAST.  We use the variable 'Op', which is the
13182   // non-casted variable when we check for possible users.
13183   switch (ArithOp.getOpcode()) {
13184   case ISD::ADD:
13185     // Due to an isel shortcoming, be conservative if this add is likely to be
13186     // selected as part of a load-modify-store instruction. When the root node
13187     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13188     // uses of other nodes in the match, such as the ADD in this case. This
13189     // leads to the ADD being left around and reselected, with the result being
13190     // two adds in the output.  Alas, even if none our users are stores, that
13191     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13192     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13193     // climbing the DAG back to the root, and it doesn't seem to be worth the
13194     // effort.
13195     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13196          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13197       if (UI->getOpcode() != ISD::CopyToReg &&
13198           UI->getOpcode() != ISD::SETCC &&
13199           UI->getOpcode() != ISD::STORE)
13200         goto default_case;
13201
13202     if (ConstantSDNode *C =
13203         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13204       // An add of one will be selected as an INC.
13205       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13206         Opcode = X86ISD::INC;
13207         NumOperands = 1;
13208         break;
13209       }
13210
13211       // An add of negative one (subtract of one) will be selected as a DEC.
13212       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13213         Opcode = X86ISD::DEC;
13214         NumOperands = 1;
13215         break;
13216       }
13217     }
13218
13219     // Otherwise use a regular EFLAGS-setting add.
13220     Opcode = X86ISD::ADD;
13221     NumOperands = 2;
13222     break;
13223   case ISD::SHL:
13224   case ISD::SRL:
13225     // If we have a constant logical shift that's only used in a comparison
13226     // against zero turn it into an equivalent AND. This allows turning it into
13227     // a TEST instruction later.
13228     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13229         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13230       EVT VT = Op.getValueType();
13231       unsigned BitWidth = VT.getSizeInBits();
13232       unsigned ShAmt = Op->getConstantOperandVal(1);
13233       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13234         break;
13235       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13236                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13237                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13238       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13239         break;
13240       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13241                                 DAG.getConstant(Mask, dl, VT));
13242       DAG.ReplaceAllUsesWith(Op, New);
13243       Op = New;
13244     }
13245     break;
13246
13247   case ISD::AND:
13248     // If the primary and result isn't used, don't bother using X86ISD::AND,
13249     // because a TEST instruction will be better.
13250     if (!hasNonFlagsUse(Op))
13251       break;
13252     // FALL THROUGH
13253   case ISD::SUB:
13254   case ISD::OR:
13255   case ISD::XOR:
13256     // Due to the ISEL shortcoming noted above, be conservative if this op is
13257     // likely to be selected as part of a load-modify-store instruction.
13258     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13259            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13260       if (UI->getOpcode() == ISD::STORE)
13261         goto default_case;
13262
13263     // Otherwise use a regular EFLAGS-setting instruction.
13264     switch (ArithOp.getOpcode()) {
13265     default: llvm_unreachable("unexpected operator!");
13266     case ISD::SUB: Opcode = X86ISD::SUB; break;
13267     case ISD::XOR: Opcode = X86ISD::XOR; break;
13268     case ISD::AND: Opcode = X86ISD::AND; break;
13269     case ISD::OR: {
13270       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13271         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13272         if (EFLAGS.getNode())
13273           return EFLAGS;
13274       }
13275       Opcode = X86ISD::OR;
13276       break;
13277     }
13278     }
13279
13280     NumOperands = 2;
13281     break;
13282   case X86ISD::ADD:
13283   case X86ISD::SUB:
13284   case X86ISD::INC:
13285   case X86ISD::DEC:
13286   case X86ISD::OR:
13287   case X86ISD::XOR:
13288   case X86ISD::AND:
13289     return SDValue(Op.getNode(), 1);
13290   default:
13291   default_case:
13292     break;
13293   }
13294
13295   // If we found that truncation is beneficial, perform the truncation and
13296   // update 'Op'.
13297   if (NeedTruncation) {
13298     EVT VT = Op.getValueType();
13299     SDValue WideVal = Op->getOperand(0);
13300     EVT WideVT = WideVal.getValueType();
13301     unsigned ConvertedOp = 0;
13302     // Use a target machine opcode to prevent further DAGCombine
13303     // optimizations that may separate the arithmetic operations
13304     // from the setcc node.
13305     switch (WideVal.getOpcode()) {
13306       default: break;
13307       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13308       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13309       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13310       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13311       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13312     }
13313
13314     if (ConvertedOp) {
13315       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13316       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13317         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13318         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13319         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13320       }
13321     }
13322   }
13323
13324   if (Opcode == 0)
13325     // Emit a CMP with 0, which is the TEST pattern.
13326     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13327                        DAG.getConstant(0, dl, Op.getValueType()));
13328
13329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13330   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13331
13332   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13333   DAG.ReplaceAllUsesWith(Op, New);
13334   return SDValue(New.getNode(), 1);
13335 }
13336
13337 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13338 /// equivalent.
13339 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13340                                    SDLoc dl, SelectionDAG &DAG) const {
13341   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13342     if (C->getAPIntValue() == 0)
13343       return EmitTest(Op0, X86CC, dl, DAG);
13344
13345      if (Op0.getValueType() == MVT::i1)
13346        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13347   }
13348
13349   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13350        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13351     // Do the comparison at i32 if it's smaller, besides the Atom case.
13352     // This avoids subregister aliasing issues. Keep the smaller reference
13353     // if we're optimizing for size, however, as that'll allow better folding
13354     // of memory operations.
13355     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13356         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13357         !Subtarget->isAtom()) {
13358       unsigned ExtendOp =
13359           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13360       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13361       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13362     }
13363     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13364     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13365     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13366                               Op0, Op1);
13367     return SDValue(Sub.getNode(), 1);
13368   }
13369   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13370 }
13371
13372 /// Convert a comparison if required by the subtarget.
13373 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13374                                                  SelectionDAG &DAG) const {
13375   // If the subtarget does not support the FUCOMI instruction, floating-point
13376   // comparisons have to be converted.
13377   if (Subtarget->hasCMov() ||
13378       Cmp.getOpcode() != X86ISD::CMP ||
13379       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13380       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13381     return Cmp;
13382
13383   // The instruction selector will select an FUCOM instruction instead of
13384   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13385   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13386   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13387   SDLoc dl(Cmp);
13388   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13389   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13390   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13391                             DAG.getConstant(8, dl, MVT::i8));
13392   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13393   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13394 }
13395
13396 /// The minimum architected relative accuracy is 2^-12. We need one
13397 /// Newton-Raphson step to have a good float result (24 bits of precision).
13398 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13399                                             DAGCombinerInfo &DCI,
13400                                             unsigned &RefinementSteps,
13401                                             bool &UseOneConstNR) const {
13402   EVT VT = Op.getValueType();
13403   const char *RecipOp;
13404
13405   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13406   // TODO: Add support for AVX512 (v16f32).
13407   // It is likely not profitable to do this for f64 because a double-precision
13408   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13409   // instructions: convert to single, rsqrtss, convert back to double, refine
13410   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13411   // along with FMA, this could be a throughput win.
13412   if (VT == MVT::f32 && Subtarget->hasSSE1())
13413     RecipOp = "sqrtf";
13414   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13415            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13416     RecipOp = "vec-sqrtf";
13417   else
13418     return SDValue();
13419
13420   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13421   if (!Recips.isEnabled(RecipOp))
13422     return SDValue();
13423
13424   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13425   UseOneConstNR = false;
13426   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13427 }
13428
13429 /// The minimum architected relative accuracy is 2^-12. We need one
13430 /// Newton-Raphson step to have a good float result (24 bits of precision).
13431 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13432                                             DAGCombinerInfo &DCI,
13433                                             unsigned &RefinementSteps) const {
13434   EVT VT = Op.getValueType();
13435   const char *RecipOp;
13436
13437   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13438   // TODO: Add support for AVX512 (v16f32).
13439   // It is likely not profitable to do this for f64 because a double-precision
13440   // reciprocal estimate with refinement on x86 prior to FMA requires
13441   // 15 instructions: convert to single, rcpss, convert back to double, refine
13442   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13443   // along with FMA, this could be a throughput win.
13444   if (VT == MVT::f32 && Subtarget->hasSSE1())
13445     RecipOp = "divf";
13446   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13447            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13448     RecipOp = "vec-divf";
13449   else
13450     return SDValue();
13451
13452   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13453   if (!Recips.isEnabled(RecipOp))
13454     return SDValue();
13455
13456   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13457   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13458 }
13459
13460 /// If we have at least two divisions that use the same divisor, convert to
13461 /// multplication by a reciprocal. This may need to be adjusted for a given
13462 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13463 /// This is because we still need one division to calculate the reciprocal and
13464 /// then we need two multiplies by that reciprocal as replacements for the
13465 /// original divisions.
13466 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13467   return 2;
13468 }
13469
13470 static bool isAllOnes(SDValue V) {
13471   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13472   return C && C->isAllOnesValue();
13473 }
13474
13475 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13476 /// if it's possible.
13477 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13478                                      SDLoc dl, SelectionDAG &DAG) const {
13479   SDValue Op0 = And.getOperand(0);
13480   SDValue Op1 = And.getOperand(1);
13481   if (Op0.getOpcode() == ISD::TRUNCATE)
13482     Op0 = Op0.getOperand(0);
13483   if (Op1.getOpcode() == ISD::TRUNCATE)
13484     Op1 = Op1.getOperand(0);
13485
13486   SDValue LHS, RHS;
13487   if (Op1.getOpcode() == ISD::SHL)
13488     std::swap(Op0, Op1);
13489   if (Op0.getOpcode() == ISD::SHL) {
13490     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13491       if (And00C->getZExtValue() == 1) {
13492         // If we looked past a truncate, check that it's only truncating away
13493         // known zeros.
13494         unsigned BitWidth = Op0.getValueSizeInBits();
13495         unsigned AndBitWidth = And.getValueSizeInBits();
13496         if (BitWidth > AndBitWidth) {
13497           APInt Zeros, Ones;
13498           DAG.computeKnownBits(Op0, Zeros, Ones);
13499           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13500             return SDValue();
13501         }
13502         LHS = Op1;
13503         RHS = Op0.getOperand(1);
13504       }
13505   } else if (Op1.getOpcode() == ISD::Constant) {
13506     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13507     uint64_t AndRHSVal = AndRHS->getZExtValue();
13508     SDValue AndLHS = Op0;
13509
13510     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13511       LHS = AndLHS.getOperand(0);
13512       RHS = AndLHS.getOperand(1);
13513     }
13514
13515     // Use BT if the immediate can't be encoded in a TEST instruction.
13516     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13517       LHS = AndLHS;
13518       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13519     }
13520   }
13521
13522   if (LHS.getNode()) {
13523     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13524     // instruction.  Since the shift amount is in-range-or-undefined, we know
13525     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13526     // the encoding for the i16 version is larger than the i32 version.
13527     // Also promote i16 to i32 for performance / code size reason.
13528     if (LHS.getValueType() == MVT::i8 ||
13529         LHS.getValueType() == MVT::i16)
13530       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13531
13532     // If the operand types disagree, extend the shift amount to match.  Since
13533     // BT ignores high bits (like shifts) we can use anyextend.
13534     if (LHS.getValueType() != RHS.getValueType())
13535       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13536
13537     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13538     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13539     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13540                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13541   }
13542
13543   return SDValue();
13544 }
13545
13546 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13547 /// mask CMPs.
13548 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13549                               SDValue &Op1) {
13550   unsigned SSECC;
13551   bool Swap = false;
13552
13553   // SSE Condition code mapping:
13554   //  0 - EQ
13555   //  1 - LT
13556   //  2 - LE
13557   //  3 - UNORD
13558   //  4 - NEQ
13559   //  5 - NLT
13560   //  6 - NLE
13561   //  7 - ORD
13562   switch (SetCCOpcode) {
13563   default: llvm_unreachable("Unexpected SETCC condition");
13564   case ISD::SETOEQ:
13565   case ISD::SETEQ:  SSECC = 0; break;
13566   case ISD::SETOGT:
13567   case ISD::SETGT:  Swap = true; // Fallthrough
13568   case ISD::SETLT:
13569   case ISD::SETOLT: SSECC = 1; break;
13570   case ISD::SETOGE:
13571   case ISD::SETGE:  Swap = true; // Fallthrough
13572   case ISD::SETLE:
13573   case ISD::SETOLE: SSECC = 2; break;
13574   case ISD::SETUO:  SSECC = 3; break;
13575   case ISD::SETUNE:
13576   case ISD::SETNE:  SSECC = 4; break;
13577   case ISD::SETULE: Swap = true; // Fallthrough
13578   case ISD::SETUGE: SSECC = 5; break;
13579   case ISD::SETULT: Swap = true; // Fallthrough
13580   case ISD::SETUGT: SSECC = 6; break;
13581   case ISD::SETO:   SSECC = 7; break;
13582   case ISD::SETUEQ:
13583   case ISD::SETONE: SSECC = 8; break;
13584   }
13585   if (Swap)
13586     std::swap(Op0, Op1);
13587
13588   return SSECC;
13589 }
13590
13591 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13592 // ones, and then concatenate the result back.
13593 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13594   MVT VT = Op.getSimpleValueType();
13595
13596   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13597          "Unsupported value type for operation");
13598
13599   unsigned NumElems = VT.getVectorNumElements();
13600   SDLoc dl(Op);
13601   SDValue CC = Op.getOperand(2);
13602
13603   // Extract the LHS vectors
13604   SDValue LHS = Op.getOperand(0);
13605   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13606   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13607
13608   // Extract the RHS vectors
13609   SDValue RHS = Op.getOperand(1);
13610   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13611   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13612
13613   // Issue the operation on the smaller types and concatenate the result back
13614   MVT EltVT = VT.getVectorElementType();
13615   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13616   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13617                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13618                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13619 }
13620
13621 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13622   SDValue Op0 = Op.getOperand(0);
13623   SDValue Op1 = Op.getOperand(1);
13624   SDValue CC = Op.getOperand(2);
13625   MVT VT = Op.getSimpleValueType();
13626   SDLoc dl(Op);
13627
13628   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13629          "Unexpected type for boolean compare operation");
13630   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13631   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13632                                DAG.getConstant(-1, dl, VT));
13633   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13634                                DAG.getConstant(-1, dl, VT));
13635   switch (SetCCOpcode) {
13636   default: llvm_unreachable("Unexpected SETCC condition");
13637   case ISD::SETEQ:
13638     // (x == y) -> ~(x ^ y)
13639     return DAG.getNode(ISD::XOR, dl, VT,
13640                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13641                        DAG.getConstant(-1, dl, VT));
13642   case ISD::SETNE:
13643     // (x != y) -> (x ^ y)
13644     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13645   case ISD::SETUGT:
13646   case ISD::SETGT:
13647     // (x > y) -> (x & ~y)
13648     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13649   case ISD::SETULT:
13650   case ISD::SETLT:
13651     // (x < y) -> (~x & y)
13652     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13653   case ISD::SETULE:
13654   case ISD::SETLE:
13655     // (x <= y) -> (~x | y)
13656     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13657   case ISD::SETUGE:
13658   case ISD::SETGE:
13659     // (x >=y) -> (x | ~y)
13660     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13661   }
13662 }
13663
13664 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13665                                      const X86Subtarget *Subtarget) {
13666   SDValue Op0 = Op.getOperand(0);
13667   SDValue Op1 = Op.getOperand(1);
13668   SDValue CC = Op.getOperand(2);
13669   MVT VT = Op.getSimpleValueType();
13670   SDLoc dl(Op);
13671
13672   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13673          Op.getValueType().getScalarType() == MVT::i1 &&
13674          "Cannot set masked compare for this operation");
13675
13676   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13677   unsigned  Opc = 0;
13678   bool Unsigned = false;
13679   bool Swap = false;
13680   unsigned SSECC;
13681   switch (SetCCOpcode) {
13682   default: llvm_unreachable("Unexpected SETCC condition");
13683   case ISD::SETNE:  SSECC = 4; break;
13684   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13685   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13686   case ISD::SETLT:  Swap = true; //fall-through
13687   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13688   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13689   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13690   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13691   case ISD::SETULE: Unsigned = true; //fall-through
13692   case ISD::SETLE:  SSECC = 2; break;
13693   }
13694
13695   if (Swap)
13696     std::swap(Op0, Op1);
13697   if (Opc)
13698     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13699   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13700   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13701                      DAG.getConstant(SSECC, dl, MVT::i8));
13702 }
13703
13704 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13705 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13706 /// return an empty value.
13707 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13708 {
13709   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13710   if (!BV)
13711     return SDValue();
13712
13713   MVT VT = Op1.getSimpleValueType();
13714   MVT EVT = VT.getVectorElementType();
13715   unsigned n = VT.getVectorNumElements();
13716   SmallVector<SDValue, 8> ULTOp1;
13717
13718   for (unsigned i = 0; i < n; ++i) {
13719     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13720     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13721       return SDValue();
13722
13723     // Avoid underflow.
13724     APInt Val = Elt->getAPIntValue();
13725     if (Val == 0)
13726       return SDValue();
13727
13728     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13729   }
13730
13731   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13732 }
13733
13734 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13735                            SelectionDAG &DAG) {
13736   SDValue Op0 = Op.getOperand(0);
13737   SDValue Op1 = Op.getOperand(1);
13738   SDValue CC = Op.getOperand(2);
13739   MVT VT = Op.getSimpleValueType();
13740   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13741   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13742   SDLoc dl(Op);
13743
13744   if (isFP) {
13745 #ifndef NDEBUG
13746     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13747     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13748 #endif
13749
13750     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13751     unsigned Opc = X86ISD::CMPP;
13752     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13753       assert(VT.getVectorNumElements() <= 16);
13754       Opc = X86ISD::CMPM;
13755     }
13756     // In the two special cases we can't handle, emit two comparisons.
13757     if (SSECC == 8) {
13758       unsigned CC0, CC1;
13759       unsigned CombineOpc;
13760       if (SetCCOpcode == ISD::SETUEQ) {
13761         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13762       } else {
13763         assert(SetCCOpcode == ISD::SETONE);
13764         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13765       }
13766
13767       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13768                                  DAG.getConstant(CC0, dl, MVT::i8));
13769       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13770                                  DAG.getConstant(CC1, dl, MVT::i8));
13771       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13772     }
13773     // Handle all other FP comparisons here.
13774     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13775                        DAG.getConstant(SSECC, dl, MVT::i8));
13776   }
13777
13778   // Break 256-bit integer vector compare into smaller ones.
13779   if (VT.is256BitVector() && !Subtarget->hasInt256())
13780     return Lower256IntVSETCC(Op, DAG);
13781
13782   EVT OpVT = Op1.getValueType();
13783   if (OpVT.getVectorElementType() == MVT::i1)
13784     return LowerBoolVSETCC_AVX512(Op, DAG);
13785
13786   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13787   if (Subtarget->hasAVX512()) {
13788     if (Op1.getValueType().is512BitVector() ||
13789         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13790         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13791       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13792
13793     // In AVX-512 architecture setcc returns mask with i1 elements,
13794     // But there is no compare instruction for i8 and i16 elements in KNL.
13795     // We are not talking about 512-bit operands in this case, these
13796     // types are illegal.
13797     if (MaskResult &&
13798         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13799          OpVT.getVectorElementType().getSizeInBits() >= 8))
13800       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13801                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13802   }
13803
13804   // We are handling one of the integer comparisons here.  Since SSE only has
13805   // GT and EQ comparisons for integer, swapping operands and multiple
13806   // operations may be required for some comparisons.
13807   unsigned Opc;
13808   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13809   bool Subus = false;
13810
13811   switch (SetCCOpcode) {
13812   default: llvm_unreachable("Unexpected SETCC condition");
13813   case ISD::SETNE:  Invert = true;
13814   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13815   case ISD::SETLT:  Swap = true;
13816   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13817   case ISD::SETGE:  Swap = true;
13818   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13819                     Invert = true; break;
13820   case ISD::SETULT: Swap = true;
13821   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13822                     FlipSigns = true; break;
13823   case ISD::SETUGE: Swap = true;
13824   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13825                     FlipSigns = true; Invert = true; break;
13826   }
13827
13828   // Special case: Use min/max operations for SETULE/SETUGE
13829   MVT VET = VT.getVectorElementType();
13830   bool hasMinMax =
13831        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13832     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13833
13834   if (hasMinMax) {
13835     switch (SetCCOpcode) {
13836     default: break;
13837     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13838     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13839     }
13840
13841     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13842   }
13843
13844   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13845   if (!MinMax && hasSubus) {
13846     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13847     // Op0 u<= Op1:
13848     //   t = psubus Op0, Op1
13849     //   pcmpeq t, <0..0>
13850     switch (SetCCOpcode) {
13851     default: break;
13852     case ISD::SETULT: {
13853       // If the comparison is against a constant we can turn this into a
13854       // setule.  With psubus, setule does not require a swap.  This is
13855       // beneficial because the constant in the register is no longer
13856       // destructed as the destination so it can be hoisted out of a loop.
13857       // Only do this pre-AVX since vpcmp* is no longer destructive.
13858       if (Subtarget->hasAVX())
13859         break;
13860       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13861       if (ULEOp1.getNode()) {
13862         Op1 = ULEOp1;
13863         Subus = true; Invert = false; Swap = false;
13864       }
13865       break;
13866     }
13867     // Psubus is better than flip-sign because it requires no inversion.
13868     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13869     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13870     }
13871
13872     if (Subus) {
13873       Opc = X86ISD::SUBUS;
13874       FlipSigns = false;
13875     }
13876   }
13877
13878   if (Swap)
13879     std::swap(Op0, Op1);
13880
13881   // Check that the operation in question is available (most are plain SSE2,
13882   // but PCMPGTQ and PCMPEQQ have different requirements).
13883   if (VT == MVT::v2i64) {
13884     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13885       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13886
13887       // First cast everything to the right type.
13888       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13889       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13890
13891       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13892       // bits of the inputs before performing those operations. The lower
13893       // compare is always unsigned.
13894       SDValue SB;
13895       if (FlipSigns) {
13896         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13897       } else {
13898         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13899         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13900         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13901                          Sign, Zero, Sign, Zero);
13902       }
13903       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13904       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13905
13906       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13907       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13908       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13909
13910       // Create masks for only the low parts/high parts of the 64 bit integers.
13911       static const int MaskHi[] = { 1, 1, 3, 3 };
13912       static const int MaskLo[] = { 0, 0, 2, 2 };
13913       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13914       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13915       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13916
13917       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13918       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13919
13920       if (Invert)
13921         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13922
13923       return DAG.getBitcast(VT, Result);
13924     }
13925
13926     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13927       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13928       // pcmpeqd + pshufd + pand.
13929       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13930
13931       // First cast everything to the right type.
13932       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13933       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13934
13935       // Do the compare.
13936       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13937
13938       // Make sure the lower and upper halves are both all-ones.
13939       static const int Mask[] = { 1, 0, 3, 2 };
13940       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13941       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13942
13943       if (Invert)
13944         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13945
13946       return DAG.getBitcast(VT, Result);
13947     }
13948   }
13949
13950   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13951   // bits of the inputs before performing those operations.
13952   if (FlipSigns) {
13953     EVT EltVT = VT.getVectorElementType();
13954     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13955                                  VT);
13956     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13957     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13958   }
13959
13960   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13961
13962   // If the logical-not of the result is required, perform that now.
13963   if (Invert)
13964     Result = DAG.getNOT(dl, Result, VT);
13965
13966   if (MinMax)
13967     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13968
13969   if (Subus)
13970     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13971                          getZeroVector(VT, Subtarget, DAG, dl));
13972
13973   return Result;
13974 }
13975
13976 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13977
13978   MVT VT = Op.getSimpleValueType();
13979
13980   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13981
13982   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13983          && "SetCC type must be 8-bit or 1-bit integer");
13984   SDValue Op0 = Op.getOperand(0);
13985   SDValue Op1 = Op.getOperand(1);
13986   SDLoc dl(Op);
13987   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13988
13989   // Optimize to BT if possible.
13990   // Lower (X & (1 << N)) == 0 to BT(X, N).
13991   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13992   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13993   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13994       Op1.getOpcode() == ISD::Constant &&
13995       cast<ConstantSDNode>(Op1)->isNullValue() &&
13996       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13997     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13998     if (NewSetCC.getNode()) {
13999       if (VT == MVT::i1)
14000         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14001       return NewSetCC;
14002     }
14003   }
14004
14005   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14006   // these.
14007   if (Op1.getOpcode() == ISD::Constant &&
14008       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14009        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14010       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14011
14012     // If the input is a setcc, then reuse the input setcc or use a new one with
14013     // the inverted condition.
14014     if (Op0.getOpcode() == X86ISD::SETCC) {
14015       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14016       bool Invert = (CC == ISD::SETNE) ^
14017         cast<ConstantSDNode>(Op1)->isNullValue();
14018       if (!Invert)
14019         return Op0;
14020
14021       CCode = X86::GetOppositeBranchCondition(CCode);
14022       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14023                                   DAG.getConstant(CCode, dl, MVT::i8),
14024                                   Op0.getOperand(1));
14025       if (VT == MVT::i1)
14026         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14027       return SetCC;
14028     }
14029   }
14030   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14031       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14032       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14033
14034     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14035     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14036   }
14037
14038   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14039   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14040   if (X86CC == X86::COND_INVALID)
14041     return SDValue();
14042
14043   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14044   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14045   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14046                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14047   if (VT == MVT::i1)
14048     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14049   return SetCC;
14050 }
14051
14052 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14053 static bool isX86LogicalCmp(SDValue Op) {
14054   unsigned Opc = Op.getNode()->getOpcode();
14055   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14056       Opc == X86ISD::SAHF)
14057     return true;
14058   if (Op.getResNo() == 1 &&
14059       (Opc == X86ISD::ADD ||
14060        Opc == X86ISD::SUB ||
14061        Opc == X86ISD::ADC ||
14062        Opc == X86ISD::SBB ||
14063        Opc == X86ISD::SMUL ||
14064        Opc == X86ISD::UMUL ||
14065        Opc == X86ISD::INC ||
14066        Opc == X86ISD::DEC ||
14067        Opc == X86ISD::OR ||
14068        Opc == X86ISD::XOR ||
14069        Opc == X86ISD::AND))
14070     return true;
14071
14072   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14073     return true;
14074
14075   return false;
14076 }
14077
14078 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14079   if (V.getOpcode() != ISD::TRUNCATE)
14080     return false;
14081
14082   SDValue VOp0 = V.getOperand(0);
14083   unsigned InBits = VOp0.getValueSizeInBits();
14084   unsigned Bits = V.getValueSizeInBits();
14085   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14086 }
14087
14088 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14089   bool addTest = true;
14090   SDValue Cond  = Op.getOperand(0);
14091   SDValue Op1 = Op.getOperand(1);
14092   SDValue Op2 = Op.getOperand(2);
14093   SDLoc DL(Op);
14094   EVT VT = Op1.getValueType();
14095   SDValue CC;
14096
14097   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14098   // are available or VBLENDV if AVX is available.
14099   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14100   if (Cond.getOpcode() == ISD::SETCC &&
14101       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14102        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14103       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14104     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14105     int SSECC = translateX86FSETCC(
14106         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14107
14108     if (SSECC != 8) {
14109       if (Subtarget->hasAVX512()) {
14110         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14111                                   DAG.getConstant(SSECC, DL, MVT::i8));
14112         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14113       }
14114
14115       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14116                                 DAG.getConstant(SSECC, DL, MVT::i8));
14117
14118       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14119       // of 3 logic instructions for size savings and potentially speed.
14120       // Unfortunately, there is no scalar form of VBLENDV.
14121
14122       // If either operand is a constant, don't try this. We can expect to
14123       // optimize away at least one of the logic instructions later in that
14124       // case, so that sequence would be faster than a variable blend.
14125
14126       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14127       // uses XMM0 as the selection register. That may need just as many
14128       // instructions as the AND/ANDN/OR sequence due to register moves, so
14129       // don't bother.
14130
14131       if (Subtarget->hasAVX() &&
14132           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14133
14134         // Convert to vectors, do a VSELECT, and convert back to scalar.
14135         // All of the conversions should be optimized away.
14136
14137         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14138         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14139         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14140         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14141
14142         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14143         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14144
14145         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14146
14147         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14148                            VSel, DAG.getIntPtrConstant(0, DL));
14149       }
14150       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14151       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14152       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14153     }
14154   }
14155
14156   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14157     SDValue Op1Scalar;
14158     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14159       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14160     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14161       Op1Scalar = Op1.getOperand(0);
14162     SDValue Op2Scalar;
14163     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14164       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14165     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14166       Op2Scalar = Op2.getOperand(0);
14167     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14168       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14169                                       Op1Scalar.getValueType(),
14170                                       Cond, Op1Scalar, Op2Scalar);
14171       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14172         return DAG.getBitcast(VT, newSelect);
14173       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14174       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14175                          DAG.getIntPtrConstant(0, DL));
14176     }
14177   }
14178
14179   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14180     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14181     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14182                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14183     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14184                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14185     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14186                                     Cond, Op1, Op2);
14187     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14188   }
14189
14190   if (Cond.getOpcode() == ISD::SETCC) {
14191     SDValue NewCond = LowerSETCC(Cond, DAG);
14192     if (NewCond.getNode())
14193       Cond = NewCond;
14194   }
14195
14196   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14197   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14198   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14199   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14200   if (Cond.getOpcode() == X86ISD::SETCC &&
14201       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14202       isZero(Cond.getOperand(1).getOperand(1))) {
14203     SDValue Cmp = Cond.getOperand(1);
14204
14205     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14206
14207     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14208         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14209       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14210
14211       SDValue CmpOp0 = Cmp.getOperand(0);
14212       // Apply further optimizations for special cases
14213       // (select (x != 0), -1, 0) -> neg & sbb
14214       // (select (x == 0), 0, -1) -> neg & sbb
14215       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14216         if (YC->isNullValue() &&
14217             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14218           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14219           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14220                                     DAG.getConstant(0, DL,
14221                                                     CmpOp0.getValueType()),
14222                                     CmpOp0);
14223           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14224                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14225                                     SDValue(Neg.getNode(), 1));
14226           return Res;
14227         }
14228
14229       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14230                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14231       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14232
14233       SDValue Res =   // Res = 0 or -1.
14234         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14235                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14236
14237       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14238         Res = DAG.getNOT(DL, Res, Res.getValueType());
14239
14240       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14241       if (!N2C || !N2C->isNullValue())
14242         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14243       return Res;
14244     }
14245   }
14246
14247   // Look past (and (setcc_carry (cmp ...)), 1).
14248   if (Cond.getOpcode() == ISD::AND &&
14249       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14250     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14251     if (C && C->getAPIntValue() == 1)
14252       Cond = Cond.getOperand(0);
14253   }
14254
14255   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14256   // setting operand in place of the X86ISD::SETCC.
14257   unsigned CondOpcode = Cond.getOpcode();
14258   if (CondOpcode == X86ISD::SETCC ||
14259       CondOpcode == X86ISD::SETCC_CARRY) {
14260     CC = Cond.getOperand(0);
14261
14262     SDValue Cmp = Cond.getOperand(1);
14263     unsigned Opc = Cmp.getOpcode();
14264     MVT VT = Op.getSimpleValueType();
14265
14266     bool IllegalFPCMov = false;
14267     if (VT.isFloatingPoint() && !VT.isVector() &&
14268         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14269       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14270
14271     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14272         Opc == X86ISD::BT) { // FIXME
14273       Cond = Cmp;
14274       addTest = false;
14275     }
14276   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14277              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14278              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14279               Cond.getOperand(0).getValueType() != MVT::i8)) {
14280     SDValue LHS = Cond.getOperand(0);
14281     SDValue RHS = Cond.getOperand(1);
14282     unsigned X86Opcode;
14283     unsigned X86Cond;
14284     SDVTList VTs;
14285     switch (CondOpcode) {
14286     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14287     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14288     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14289     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14290     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14291     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14292     default: llvm_unreachable("unexpected overflowing operator");
14293     }
14294     if (CondOpcode == ISD::UMULO)
14295       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14296                           MVT::i32);
14297     else
14298       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14299
14300     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14301
14302     if (CondOpcode == ISD::UMULO)
14303       Cond = X86Op.getValue(2);
14304     else
14305       Cond = X86Op.getValue(1);
14306
14307     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14308     addTest = false;
14309   }
14310
14311   if (addTest) {
14312     // Look past the truncate if the high bits are known zero.
14313     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14314       Cond = Cond.getOperand(0);
14315
14316     // We know the result of AND is compared against zero. Try to match
14317     // it to BT.
14318     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14319       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14320       if (NewSetCC.getNode()) {
14321         CC = NewSetCC.getOperand(0);
14322         Cond = NewSetCC.getOperand(1);
14323         addTest = false;
14324       }
14325     }
14326   }
14327
14328   if (addTest) {
14329     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14330     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14331   }
14332
14333   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14334   // a <  b ?  0 : -1 -> RES = setcc_carry
14335   // a >= b ? -1 :  0 -> RES = setcc_carry
14336   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14337   if (Cond.getOpcode() == X86ISD::SUB) {
14338     Cond = ConvertCmpIfNecessary(Cond, DAG);
14339     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14340
14341     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14342         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14343       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14344                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14345                                 Cond);
14346       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14347         return DAG.getNOT(DL, Res, Res.getValueType());
14348       return Res;
14349     }
14350   }
14351
14352   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14353   // widen the cmov and push the truncate through. This avoids introducing a new
14354   // branch during isel and doesn't add any extensions.
14355   if (Op.getValueType() == MVT::i8 &&
14356       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14357     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14358     if (T1.getValueType() == T2.getValueType() &&
14359         // Blacklist CopyFromReg to avoid partial register stalls.
14360         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14361       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14362       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14363       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14364     }
14365   }
14366
14367   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14368   // condition is true.
14369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14370   SDValue Ops[] = { Op2, Op1, CC, Cond };
14371   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14372 }
14373
14374 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14375                                        const X86Subtarget *Subtarget,
14376                                        SelectionDAG &DAG) {
14377   MVT VT = Op->getSimpleValueType(0);
14378   SDValue In = Op->getOperand(0);
14379   MVT InVT = In.getSimpleValueType();
14380   MVT VTElt = VT.getVectorElementType();
14381   MVT InVTElt = InVT.getVectorElementType();
14382   SDLoc dl(Op);
14383
14384   // SKX processor
14385   if ((InVTElt == MVT::i1) &&
14386       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14387         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14388
14389        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14390         VTElt.getSizeInBits() <= 16)) ||
14391
14392        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14393         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14394
14395        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14396         VTElt.getSizeInBits() >= 32))))
14397     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14398
14399   unsigned int NumElts = VT.getVectorNumElements();
14400
14401   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14402     return SDValue();
14403
14404   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14405     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14406       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14407     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14408   }
14409
14410   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14411   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14412   SDValue NegOne =
14413    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14414                    ExtVT);
14415   SDValue Zero =
14416    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14417
14418   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14419   if (VT.is512BitVector())
14420     return V;
14421   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14422 }
14423
14424 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14425                                              const X86Subtarget *Subtarget,
14426                                              SelectionDAG &DAG) {
14427   SDValue In = Op->getOperand(0);
14428   MVT VT = Op->getSimpleValueType(0);
14429   MVT InVT = In.getSimpleValueType();
14430   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14431
14432   MVT InSVT = InVT.getScalarType();
14433   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14434
14435   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14436     return SDValue();
14437   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14438     return SDValue();
14439
14440   SDLoc dl(Op);
14441
14442   // SSE41 targets can use the pmovsx* instructions directly.
14443   if (Subtarget->hasSSE41())
14444     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14445
14446   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14447   SDValue Curr = In;
14448   MVT CurrVT = InVT;
14449
14450   // As SRAI is only available on i16/i32 types, we expand only up to i32
14451   // and handle i64 separately.
14452   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14453     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14454     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14455     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14456     Curr = DAG.getBitcast(CurrVT, Curr);
14457   }
14458
14459   SDValue SignExt = Curr;
14460   if (CurrVT != InVT) {
14461     unsigned SignExtShift =
14462         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14463     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14464                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14465   }
14466
14467   if (CurrVT == VT)
14468     return SignExt;
14469
14470   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14471     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14472                                DAG.getConstant(31, dl, MVT::i8));
14473     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14474     return DAG.getBitcast(VT, Ext);
14475   }
14476
14477   return SDValue();
14478 }
14479
14480 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14481                                 SelectionDAG &DAG) {
14482   MVT VT = Op->getSimpleValueType(0);
14483   SDValue In = Op->getOperand(0);
14484   MVT InVT = In.getSimpleValueType();
14485   SDLoc dl(Op);
14486
14487   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14488     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14489
14490   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14491       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14492       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14493     return SDValue();
14494
14495   if (Subtarget->hasInt256())
14496     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14497
14498   // Optimize vectors in AVX mode
14499   // Sign extend  v8i16 to v8i32 and
14500   //              v4i32 to v4i64
14501   //
14502   // Divide input vector into two parts
14503   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14504   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14505   // concat the vectors to original VT
14506
14507   unsigned NumElems = InVT.getVectorNumElements();
14508   SDValue Undef = DAG.getUNDEF(InVT);
14509
14510   SmallVector<int,8> ShufMask1(NumElems, -1);
14511   for (unsigned i = 0; i != NumElems/2; ++i)
14512     ShufMask1[i] = i;
14513
14514   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14515
14516   SmallVector<int,8> ShufMask2(NumElems, -1);
14517   for (unsigned i = 0; i != NumElems/2; ++i)
14518     ShufMask2[i] = i + NumElems/2;
14519
14520   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14521
14522   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14523                                 VT.getVectorNumElements()/2);
14524
14525   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14526   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14527
14528   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14529 }
14530
14531 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14532 // may emit an illegal shuffle but the expansion is still better than scalar
14533 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14534 // we'll emit a shuffle and a arithmetic shift.
14535 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14536 // TODO: It is possible to support ZExt by zeroing the undef values during
14537 // the shuffle phase or after the shuffle.
14538 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14539                                  SelectionDAG &DAG) {
14540   MVT RegVT = Op.getSimpleValueType();
14541   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14542   assert(RegVT.isInteger() &&
14543          "We only custom lower integer vector sext loads.");
14544
14545   // Nothing useful we can do without SSE2 shuffles.
14546   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14547
14548   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14549   SDLoc dl(Ld);
14550   EVT MemVT = Ld->getMemoryVT();
14551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14552   unsigned RegSz = RegVT.getSizeInBits();
14553
14554   ISD::LoadExtType Ext = Ld->getExtensionType();
14555
14556   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14557          && "Only anyext and sext are currently implemented.");
14558   assert(MemVT != RegVT && "Cannot extend to the same type");
14559   assert(MemVT.isVector() && "Must load a vector from memory");
14560
14561   unsigned NumElems = RegVT.getVectorNumElements();
14562   unsigned MemSz = MemVT.getSizeInBits();
14563   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14564
14565   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14566     // The only way in which we have a legal 256-bit vector result but not the
14567     // integer 256-bit operations needed to directly lower a sextload is if we
14568     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14569     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14570     // correctly legalized. We do this late to allow the canonical form of
14571     // sextload to persist throughout the rest of the DAG combiner -- it wants
14572     // to fold together any extensions it can, and so will fuse a sign_extend
14573     // of an sextload into a sextload targeting a wider value.
14574     SDValue Load;
14575     if (MemSz == 128) {
14576       // Just switch this to a normal load.
14577       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14578                                        "it must be a legal 128-bit vector "
14579                                        "type!");
14580       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14581                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14582                   Ld->isInvariant(), Ld->getAlignment());
14583     } else {
14584       assert(MemSz < 128 &&
14585              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14586       // Do an sext load to a 128-bit vector type. We want to use the same
14587       // number of elements, but elements half as wide. This will end up being
14588       // recursively lowered by this routine, but will succeed as we definitely
14589       // have all the necessary features if we're using AVX1.
14590       EVT HalfEltVT =
14591           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14592       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14593       Load =
14594           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14595                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14596                          Ld->isNonTemporal(), Ld->isInvariant(),
14597                          Ld->getAlignment());
14598     }
14599
14600     // Replace chain users with the new chain.
14601     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14602     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14603
14604     // Finally, do a normal sign-extend to the desired register.
14605     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14606   }
14607
14608   // All sizes must be a power of two.
14609   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14610          "Non-power-of-two elements are not custom lowered!");
14611
14612   // Attempt to load the original value using scalar loads.
14613   // Find the largest scalar type that divides the total loaded size.
14614   MVT SclrLoadTy = MVT::i8;
14615   for (MVT Tp : MVT::integer_valuetypes()) {
14616     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14617       SclrLoadTy = Tp;
14618     }
14619   }
14620
14621   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14622   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14623       (64 <= MemSz))
14624     SclrLoadTy = MVT::f64;
14625
14626   // Calculate the number of scalar loads that we need to perform
14627   // in order to load our vector from memory.
14628   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14629
14630   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14631          "Can only lower sext loads with a single scalar load!");
14632
14633   unsigned loadRegZize = RegSz;
14634   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14635     loadRegZize = 128;
14636
14637   // Represent our vector as a sequence of elements which are the
14638   // largest scalar that we can load.
14639   EVT LoadUnitVecVT = EVT::getVectorVT(
14640       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14641
14642   // Represent the data using the same element type that is stored in
14643   // memory. In practice, we ''widen'' MemVT.
14644   EVT WideVecVT =
14645       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14646                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14647
14648   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14649          "Invalid vector type");
14650
14651   // We can't shuffle using an illegal type.
14652   assert(TLI.isTypeLegal(WideVecVT) &&
14653          "We only lower types that form legal widened vector types");
14654
14655   SmallVector<SDValue, 8> Chains;
14656   SDValue Ptr = Ld->getBasePtr();
14657   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14658                                       TLI.getPointerTy(DAG.getDataLayout()));
14659   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14660
14661   for (unsigned i = 0; i < NumLoads; ++i) {
14662     // Perform a single load.
14663     SDValue ScalarLoad =
14664         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14665                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14666                     Ld->getAlignment());
14667     Chains.push_back(ScalarLoad.getValue(1));
14668     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14669     // another round of DAGCombining.
14670     if (i == 0)
14671       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14672     else
14673       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14674                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14675
14676     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14677   }
14678
14679   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14680
14681   // Bitcast the loaded value to a vector of the original element type, in
14682   // the size of the target vector type.
14683   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14684   unsigned SizeRatio = RegSz / MemSz;
14685
14686   if (Ext == ISD::SEXTLOAD) {
14687     // If we have SSE4.1, we can directly emit a VSEXT node.
14688     if (Subtarget->hasSSE41()) {
14689       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14690       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14691       return Sext;
14692     }
14693
14694     // Otherwise we'll shuffle the small elements in the high bits of the
14695     // larger type and perform an arithmetic shift. If the shift is not legal
14696     // it's better to scalarize.
14697     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14698            "We can't implement a sext load without an arithmetic right shift!");
14699
14700     // Redistribute the loaded elements into the different locations.
14701     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14702     for (unsigned i = 0; i != NumElems; ++i)
14703       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14704
14705     SDValue Shuff = DAG.getVectorShuffle(
14706         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14707
14708     Shuff = DAG.getBitcast(RegVT, Shuff);
14709
14710     // Build the arithmetic shift.
14711     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14712                    MemVT.getVectorElementType().getSizeInBits();
14713     Shuff =
14714         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14715                     DAG.getConstant(Amt, dl, RegVT));
14716
14717     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14718     return Shuff;
14719   }
14720
14721   // Redistribute the loaded elements into the different locations.
14722   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14723   for (unsigned i = 0; i != NumElems; ++i)
14724     ShuffleVec[i * SizeRatio] = i;
14725
14726   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14727                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14728
14729   // Bitcast to the requested type.
14730   Shuff = DAG.getBitcast(RegVT, Shuff);
14731   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14732   return Shuff;
14733 }
14734
14735 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14736 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14737 // from the AND / OR.
14738 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14739   Opc = Op.getOpcode();
14740   if (Opc != ISD::OR && Opc != ISD::AND)
14741     return false;
14742   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14743           Op.getOperand(0).hasOneUse() &&
14744           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14745           Op.getOperand(1).hasOneUse());
14746 }
14747
14748 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14749 // 1 and that the SETCC node has a single use.
14750 static bool isXor1OfSetCC(SDValue Op) {
14751   if (Op.getOpcode() != ISD::XOR)
14752     return false;
14753   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14754   if (N1C && N1C->getAPIntValue() == 1) {
14755     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14756       Op.getOperand(0).hasOneUse();
14757   }
14758   return false;
14759 }
14760
14761 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14762   bool addTest = true;
14763   SDValue Chain = Op.getOperand(0);
14764   SDValue Cond  = Op.getOperand(1);
14765   SDValue Dest  = Op.getOperand(2);
14766   SDLoc dl(Op);
14767   SDValue CC;
14768   bool Inverted = false;
14769
14770   if (Cond.getOpcode() == ISD::SETCC) {
14771     // Check for setcc([su]{add,sub,mul}o == 0).
14772     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14773         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14774         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14775         Cond.getOperand(0).getResNo() == 1 &&
14776         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14777          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14778          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14779          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14780          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14781          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14782       Inverted = true;
14783       Cond = Cond.getOperand(0);
14784     } else {
14785       SDValue NewCond = LowerSETCC(Cond, DAG);
14786       if (NewCond.getNode())
14787         Cond = NewCond;
14788     }
14789   }
14790 #if 0
14791   // FIXME: LowerXALUO doesn't handle these!!
14792   else if (Cond.getOpcode() == X86ISD::ADD  ||
14793            Cond.getOpcode() == X86ISD::SUB  ||
14794            Cond.getOpcode() == X86ISD::SMUL ||
14795            Cond.getOpcode() == X86ISD::UMUL)
14796     Cond = LowerXALUO(Cond, DAG);
14797 #endif
14798
14799   // Look pass (and (setcc_carry (cmp ...)), 1).
14800   if (Cond.getOpcode() == ISD::AND &&
14801       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14802     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14803     if (C && C->getAPIntValue() == 1)
14804       Cond = Cond.getOperand(0);
14805   }
14806
14807   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14808   // setting operand in place of the X86ISD::SETCC.
14809   unsigned CondOpcode = Cond.getOpcode();
14810   if (CondOpcode == X86ISD::SETCC ||
14811       CondOpcode == X86ISD::SETCC_CARRY) {
14812     CC = Cond.getOperand(0);
14813
14814     SDValue Cmp = Cond.getOperand(1);
14815     unsigned Opc = Cmp.getOpcode();
14816     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14817     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14818       Cond = Cmp;
14819       addTest = false;
14820     } else {
14821       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14822       default: break;
14823       case X86::COND_O:
14824       case X86::COND_B:
14825         // These can only come from an arithmetic instruction with overflow,
14826         // e.g. SADDO, UADDO.
14827         Cond = Cond.getNode()->getOperand(1);
14828         addTest = false;
14829         break;
14830       }
14831     }
14832   }
14833   CondOpcode = Cond.getOpcode();
14834   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14835       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14836       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14837        Cond.getOperand(0).getValueType() != MVT::i8)) {
14838     SDValue LHS = Cond.getOperand(0);
14839     SDValue RHS = Cond.getOperand(1);
14840     unsigned X86Opcode;
14841     unsigned X86Cond;
14842     SDVTList VTs;
14843     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14844     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14845     // X86ISD::INC).
14846     switch (CondOpcode) {
14847     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14848     case ISD::SADDO:
14849       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14850         if (C->isOne()) {
14851           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14852           break;
14853         }
14854       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14855     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14856     case ISD::SSUBO:
14857       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14858         if (C->isOne()) {
14859           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14860           break;
14861         }
14862       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14863     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14864     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14865     default: llvm_unreachable("unexpected overflowing operator");
14866     }
14867     if (Inverted)
14868       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14869     if (CondOpcode == ISD::UMULO)
14870       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14871                           MVT::i32);
14872     else
14873       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14874
14875     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14876
14877     if (CondOpcode == ISD::UMULO)
14878       Cond = X86Op.getValue(2);
14879     else
14880       Cond = X86Op.getValue(1);
14881
14882     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14883     addTest = false;
14884   } else {
14885     unsigned CondOpc;
14886     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14887       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14888       if (CondOpc == ISD::OR) {
14889         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14890         // two branches instead of an explicit OR instruction with a
14891         // separate test.
14892         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14893             isX86LogicalCmp(Cmp)) {
14894           CC = Cond.getOperand(0).getOperand(0);
14895           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14896                               Chain, Dest, CC, Cmp);
14897           CC = Cond.getOperand(1).getOperand(0);
14898           Cond = Cmp;
14899           addTest = false;
14900         }
14901       } else { // ISD::AND
14902         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14903         // two branches instead of an explicit AND instruction with a
14904         // separate test. However, we only do this if this block doesn't
14905         // have a fall-through edge, because this requires an explicit
14906         // jmp when the condition is false.
14907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14908             isX86LogicalCmp(Cmp) &&
14909             Op.getNode()->hasOneUse()) {
14910           X86::CondCode CCode =
14911             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14912           CCode = X86::GetOppositeBranchCondition(CCode);
14913           CC = DAG.getConstant(CCode, dl, MVT::i8);
14914           SDNode *User = *Op.getNode()->use_begin();
14915           // Look for an unconditional branch following this conditional branch.
14916           // We need this because we need to reverse the successors in order
14917           // to implement FCMP_OEQ.
14918           if (User->getOpcode() == ISD::BR) {
14919             SDValue FalseBB = User->getOperand(1);
14920             SDNode *NewBR =
14921               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14922             assert(NewBR == User);
14923             (void)NewBR;
14924             Dest = FalseBB;
14925
14926             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14927                                 Chain, Dest, CC, Cmp);
14928             X86::CondCode CCode =
14929               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14930             CCode = X86::GetOppositeBranchCondition(CCode);
14931             CC = DAG.getConstant(CCode, dl, MVT::i8);
14932             Cond = Cmp;
14933             addTest = false;
14934           }
14935         }
14936       }
14937     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14938       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14939       // It should be transformed during dag combiner except when the condition
14940       // is set by a arithmetics with overflow node.
14941       X86::CondCode CCode =
14942         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14943       CCode = X86::GetOppositeBranchCondition(CCode);
14944       CC = DAG.getConstant(CCode, dl, MVT::i8);
14945       Cond = Cond.getOperand(0).getOperand(1);
14946       addTest = false;
14947     } else if (Cond.getOpcode() == ISD::SETCC &&
14948                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14949       // For FCMP_OEQ, we can emit
14950       // two branches instead of an explicit AND instruction with a
14951       // separate test. However, we only do this if this block doesn't
14952       // have a fall-through edge, because this requires an explicit
14953       // jmp when the condition is false.
14954       if (Op.getNode()->hasOneUse()) {
14955         SDNode *User = *Op.getNode()->use_begin();
14956         // Look for an unconditional branch following this conditional branch.
14957         // We need this because we need to reverse the successors in order
14958         // to implement FCMP_OEQ.
14959         if (User->getOpcode() == ISD::BR) {
14960           SDValue FalseBB = User->getOperand(1);
14961           SDNode *NewBR =
14962             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14963           assert(NewBR == User);
14964           (void)NewBR;
14965           Dest = FalseBB;
14966
14967           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14968                                     Cond.getOperand(0), Cond.getOperand(1));
14969           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14970           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14971           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14972                               Chain, Dest, CC, Cmp);
14973           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14974           Cond = Cmp;
14975           addTest = false;
14976         }
14977       }
14978     } else if (Cond.getOpcode() == ISD::SETCC &&
14979                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14980       // For FCMP_UNE, we can emit
14981       // two branches instead of an explicit AND instruction with a
14982       // separate test. However, we only do this if this block doesn't
14983       // have a fall-through edge, because this requires an explicit
14984       // jmp when the condition is false.
14985       if (Op.getNode()->hasOneUse()) {
14986         SDNode *User = *Op.getNode()->use_begin();
14987         // Look for an unconditional branch following this conditional branch.
14988         // We need this because we need to reverse the successors in order
14989         // to implement FCMP_UNE.
14990         if (User->getOpcode() == ISD::BR) {
14991           SDValue FalseBB = User->getOperand(1);
14992           SDNode *NewBR =
14993             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14994           assert(NewBR == User);
14995           (void)NewBR;
14996
14997           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14998                                     Cond.getOperand(0), Cond.getOperand(1));
14999           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15000           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15001           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15002                               Chain, Dest, CC, Cmp);
15003           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15004           Cond = Cmp;
15005           addTest = false;
15006           Dest = FalseBB;
15007         }
15008       }
15009     }
15010   }
15011
15012   if (addTest) {
15013     // Look pass the truncate if the high bits are known zero.
15014     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15015         Cond = Cond.getOperand(0);
15016
15017     // We know the result of AND is compared against zero. Try to match
15018     // it to BT.
15019     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15020       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15021       if (NewSetCC.getNode()) {
15022         CC = NewSetCC.getOperand(0);
15023         Cond = NewSetCC.getOperand(1);
15024         addTest = false;
15025       }
15026     }
15027   }
15028
15029   if (addTest) {
15030     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15031     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15032     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15033   }
15034   Cond = ConvertCmpIfNecessary(Cond, DAG);
15035   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15036                      Chain, Dest, CC, Cond);
15037 }
15038
15039 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15040 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15041 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15042 // that the guard pages used by the OS virtual memory manager are allocated in
15043 // correct sequence.
15044 SDValue
15045 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15046                                            SelectionDAG &DAG) const {
15047   MachineFunction &MF = DAG.getMachineFunction();
15048   bool SplitStack = MF.shouldSplitStack();
15049   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15050                SplitStack;
15051   SDLoc dl(Op);
15052
15053   if (!Lower) {
15054     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15055     SDNode* Node = Op.getNode();
15056
15057     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15058     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15059         " not tell us which reg is the stack pointer!");
15060     EVT VT = Node->getValueType(0);
15061     SDValue Tmp1 = SDValue(Node, 0);
15062     SDValue Tmp2 = SDValue(Node, 1);
15063     SDValue Tmp3 = Node->getOperand(2);
15064     SDValue Chain = Tmp1.getOperand(0);
15065
15066     // Chain the dynamic stack allocation so that it doesn't modify the stack
15067     // pointer when other instructions are using the stack.
15068     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15069         SDLoc(Node));
15070
15071     SDValue Size = Tmp2.getOperand(1);
15072     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15073     Chain = SP.getValue(1);
15074     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15075     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15076     unsigned StackAlign = TFI.getStackAlignment();
15077     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15078     if (Align > StackAlign)
15079       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15080           DAG.getConstant(-(uint64_t)Align, dl, VT));
15081     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15082
15083     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15084         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15085         SDLoc(Node));
15086
15087     SDValue Ops[2] = { Tmp1, Tmp2 };
15088     return DAG.getMergeValues(Ops, dl);
15089   }
15090
15091   // Get the inputs.
15092   SDValue Chain = Op.getOperand(0);
15093   SDValue Size  = Op.getOperand(1);
15094   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15095   EVT VT = Op.getNode()->getValueType(0);
15096
15097   bool Is64Bit = Subtarget->is64Bit();
15098   MVT SPTy = getPointerTy(DAG.getDataLayout());
15099
15100   if (SplitStack) {
15101     MachineRegisterInfo &MRI = MF.getRegInfo();
15102
15103     if (Is64Bit) {
15104       // The 64 bit implementation of segmented stacks needs to clobber both r10
15105       // r11. This makes it impossible to use it along with nested parameters.
15106       const Function *F = MF.getFunction();
15107
15108       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15109            I != E; ++I)
15110         if (I->hasNestAttr())
15111           report_fatal_error("Cannot use segmented stacks with functions that "
15112                              "have nested arguments.");
15113     }
15114
15115     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15116     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15117     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15118     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15119                                 DAG.getRegister(Vreg, SPTy));
15120     SDValue Ops1[2] = { Value, Chain };
15121     return DAG.getMergeValues(Ops1, dl);
15122   } else {
15123     SDValue Flag;
15124     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15125
15126     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15127     Flag = Chain.getValue(1);
15128     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15129
15130     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15131
15132     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15133     unsigned SPReg = RegInfo->getStackRegister();
15134     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15135     Chain = SP.getValue(1);
15136
15137     if (Align) {
15138       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15139                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15140       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15141     }
15142
15143     SDValue Ops1[2] = { SP, Chain };
15144     return DAG.getMergeValues(Ops1, dl);
15145   }
15146 }
15147
15148 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15149   MachineFunction &MF = DAG.getMachineFunction();
15150   auto PtrVT = getPointerTy(MF.getDataLayout());
15151   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15152
15153   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15154   SDLoc DL(Op);
15155
15156   if (!Subtarget->is64Bit() ||
15157       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15158     // vastart just stores the address of the VarArgsFrameIndex slot into the
15159     // memory location argument.
15160     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15161     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15162                         MachinePointerInfo(SV), false, false, 0);
15163   }
15164
15165   // __va_list_tag:
15166   //   gp_offset         (0 - 6 * 8)
15167   //   fp_offset         (48 - 48 + 8 * 16)
15168   //   overflow_arg_area (point to parameters coming in memory).
15169   //   reg_save_area
15170   SmallVector<SDValue, 8> MemOps;
15171   SDValue FIN = Op.getOperand(1);
15172   // Store gp_offset
15173   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15174                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15175                                                DL, MVT::i32),
15176                                FIN, MachinePointerInfo(SV), false, false, 0);
15177   MemOps.push_back(Store);
15178
15179   // Store fp_offset
15180   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15181   Store = DAG.getStore(Op.getOperand(0), DL,
15182                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15183                                        MVT::i32),
15184                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15185   MemOps.push_back(Store);
15186
15187   // Store ptr to overflow_arg_area
15188   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15189   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15190   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15191                        MachinePointerInfo(SV, 8),
15192                        false, false, 0);
15193   MemOps.push_back(Store);
15194
15195   // Store ptr to reg_save_area.
15196   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15197   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15198   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15199                        MachinePointerInfo(SV, 16), false, false, 0);
15200   MemOps.push_back(Store);
15201   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15202 }
15203
15204 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15205   assert(Subtarget->is64Bit() &&
15206          "LowerVAARG only handles 64-bit va_arg!");
15207   assert(Op.getNode()->getNumOperands() == 4);
15208
15209   MachineFunction &MF = DAG.getMachineFunction();
15210   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15211     // The Win64 ABI uses char* instead of a structure.
15212     return DAG.expandVAArg(Op.getNode());
15213
15214   SDValue Chain = Op.getOperand(0);
15215   SDValue SrcPtr = Op.getOperand(1);
15216   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15217   unsigned Align = Op.getConstantOperandVal(3);
15218   SDLoc dl(Op);
15219
15220   EVT ArgVT = Op.getNode()->getValueType(0);
15221   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15222   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15223   uint8_t ArgMode;
15224
15225   // Decide which area this value should be read from.
15226   // TODO: Implement the AMD64 ABI in its entirety. This simple
15227   // selection mechanism works only for the basic types.
15228   if (ArgVT == MVT::f80) {
15229     llvm_unreachable("va_arg for f80 not yet implemented");
15230   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15231     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15232   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15233     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15234   } else {
15235     llvm_unreachable("Unhandled argument type in LowerVAARG");
15236   }
15237
15238   if (ArgMode == 2) {
15239     // Sanity Check: Make sure using fp_offset makes sense.
15240     assert(!Subtarget->useSoftFloat() &&
15241            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15242            Subtarget->hasSSE1());
15243   }
15244
15245   // Insert VAARG_64 node into the DAG
15246   // VAARG_64 returns two values: Variable Argument Address, Chain
15247   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15248                        DAG.getConstant(ArgMode, dl, MVT::i8),
15249                        DAG.getConstant(Align, dl, MVT::i32)};
15250   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15251   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15252                                           VTs, InstOps, MVT::i64,
15253                                           MachinePointerInfo(SV),
15254                                           /*Align=*/0,
15255                                           /*Volatile=*/false,
15256                                           /*ReadMem=*/true,
15257                                           /*WriteMem=*/true);
15258   Chain = VAARG.getValue(1);
15259
15260   // Load the next argument and return it
15261   return DAG.getLoad(ArgVT, dl,
15262                      Chain,
15263                      VAARG,
15264                      MachinePointerInfo(),
15265                      false, false, false, 0);
15266 }
15267
15268 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15269                            SelectionDAG &DAG) {
15270   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15271   // where a va_list is still an i8*.
15272   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15273   if (Subtarget->isCallingConvWin64(
15274         DAG.getMachineFunction().getFunction()->getCallingConv()))
15275     // Probably a Win64 va_copy.
15276     return DAG.expandVACopy(Op.getNode());
15277
15278   SDValue Chain = Op.getOperand(0);
15279   SDValue DstPtr = Op.getOperand(1);
15280   SDValue SrcPtr = Op.getOperand(2);
15281   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15282   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15283   SDLoc DL(Op);
15284
15285   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15286                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15287                        false, false,
15288                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15289 }
15290
15291 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15292 // amount is a constant. Takes immediate version of shift as input.
15293 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15294                                           SDValue SrcOp, uint64_t ShiftAmt,
15295                                           SelectionDAG &DAG) {
15296   MVT ElementType = VT.getVectorElementType();
15297
15298   // Fold this packed shift into its first operand if ShiftAmt is 0.
15299   if (ShiftAmt == 0)
15300     return SrcOp;
15301
15302   // Check for ShiftAmt >= element width
15303   if (ShiftAmt >= ElementType.getSizeInBits()) {
15304     if (Opc == X86ISD::VSRAI)
15305       ShiftAmt = ElementType.getSizeInBits() - 1;
15306     else
15307       return DAG.getConstant(0, dl, VT);
15308   }
15309
15310   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15311          && "Unknown target vector shift-by-constant node");
15312
15313   // Fold this packed vector shift into a build vector if SrcOp is a
15314   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15315   if (VT == SrcOp.getSimpleValueType() &&
15316       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15317     SmallVector<SDValue, 8> Elts;
15318     unsigned NumElts = SrcOp->getNumOperands();
15319     ConstantSDNode *ND;
15320
15321     switch(Opc) {
15322     default: llvm_unreachable(nullptr);
15323     case X86ISD::VSHLI:
15324       for (unsigned i=0; i!=NumElts; ++i) {
15325         SDValue CurrentOp = SrcOp->getOperand(i);
15326         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15327           Elts.push_back(CurrentOp);
15328           continue;
15329         }
15330         ND = cast<ConstantSDNode>(CurrentOp);
15331         const APInt &C = ND->getAPIntValue();
15332         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15333       }
15334       break;
15335     case X86ISD::VSRLI:
15336       for (unsigned i=0; i!=NumElts; ++i) {
15337         SDValue CurrentOp = SrcOp->getOperand(i);
15338         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15339           Elts.push_back(CurrentOp);
15340           continue;
15341         }
15342         ND = cast<ConstantSDNode>(CurrentOp);
15343         const APInt &C = ND->getAPIntValue();
15344         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15345       }
15346       break;
15347     case X86ISD::VSRAI:
15348       for (unsigned i=0; i!=NumElts; ++i) {
15349         SDValue CurrentOp = SrcOp->getOperand(i);
15350         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15351           Elts.push_back(CurrentOp);
15352           continue;
15353         }
15354         ND = cast<ConstantSDNode>(CurrentOp);
15355         const APInt &C = ND->getAPIntValue();
15356         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15357       }
15358       break;
15359     }
15360
15361     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15362   }
15363
15364   return DAG.getNode(Opc, dl, VT, SrcOp,
15365                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15366 }
15367
15368 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15369 // may or may not be a constant. Takes immediate version of shift as input.
15370 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15371                                    SDValue SrcOp, SDValue ShAmt,
15372                                    SelectionDAG &DAG) {
15373   MVT SVT = ShAmt.getSimpleValueType();
15374   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15375
15376   // Catch shift-by-constant.
15377   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15378     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15379                                       CShAmt->getZExtValue(), DAG);
15380
15381   // Change opcode to non-immediate version
15382   switch (Opc) {
15383     default: llvm_unreachable("Unknown target vector shift node");
15384     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15385     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15386     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15387   }
15388
15389   const X86Subtarget &Subtarget =
15390       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15391   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15392       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15393     // Let the shuffle legalizer expand this shift amount node.
15394     SDValue Op0 = ShAmt.getOperand(0);
15395     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15396     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15397   } else {
15398     // Need to build a vector containing shift amount.
15399     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15400     SmallVector<SDValue, 4> ShOps;
15401     ShOps.push_back(ShAmt);
15402     if (SVT == MVT::i32) {
15403       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15404       ShOps.push_back(DAG.getUNDEF(SVT));
15405     }
15406     ShOps.push_back(DAG.getUNDEF(SVT));
15407
15408     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15409     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15410   }
15411
15412   // The return type has to be a 128-bit type with the same element
15413   // type as the input type.
15414   MVT EltVT = VT.getVectorElementType();
15415   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15416
15417   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15418   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15419 }
15420
15421 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15422 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15423 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15424 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15425                                     SDValue PreservedSrc,
15426                                     const X86Subtarget *Subtarget,
15427                                     SelectionDAG &DAG) {
15428     EVT VT = Op.getValueType();
15429     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15430                                   MVT::i1, VT.getVectorNumElements());
15431     SDValue VMask = SDValue();
15432     unsigned OpcodeSelect = ISD::VSELECT;
15433     SDLoc dl(Op);
15434
15435     assert(MaskVT.isSimple() && "invalid mask type");
15436
15437     if (isAllOnes(Mask))
15438       return Op;
15439
15440     if (MaskVT.bitsGT(Mask.getValueType())) {
15441       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15442                                          MaskVT.getSizeInBits());
15443       VMask = DAG.getBitcast(MaskVT,
15444                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15445     } else {
15446       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15447                                        Mask.getValueType().getSizeInBits());
15448       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15449       // are extracted by EXTRACT_SUBVECTOR.
15450       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15451                           DAG.getBitcast(BitcastVT, Mask),
15452                           DAG.getIntPtrConstant(0, dl));
15453     }
15454
15455     switch (Op.getOpcode()) {
15456       default: break;
15457       case X86ISD::PCMPEQM:
15458       case X86ISD::PCMPGTM:
15459       case X86ISD::CMPM:
15460       case X86ISD::CMPMU:
15461         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15462       case X86ISD::VTRUNC:
15463       case X86ISD::VTRUNCS:
15464       case X86ISD::VTRUNCUS:
15465         // We can't use ISD::VSELECT here because it is not always "Legal"
15466         // for the destination type. For example vpmovqb require only AVX512
15467         // and vselect that can operate on byte element type require BWI
15468         OpcodeSelect = X86ISD::SELECT;
15469         break;
15470     }
15471     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15472       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15473     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15474 }
15475
15476 /// \brief Creates an SDNode for a predicated scalar operation.
15477 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15478 /// The mask is coming as MVT::i8 and it should be truncated
15479 /// to MVT::i1 while lowering masking intrinsics.
15480 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15481 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15482 /// for a scalar instruction.
15483 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15484                                     SDValue PreservedSrc,
15485                                     const X86Subtarget *Subtarget,
15486                                     SelectionDAG &DAG) {
15487     if (isAllOnes(Mask))
15488       return Op;
15489
15490     EVT VT = Op.getValueType();
15491     SDLoc dl(Op);
15492     // The mask should be of type MVT::i1
15493     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15494
15495     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15496       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15497     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15498 }
15499
15500 static int getSEHRegistrationNodeSize(const Function *Fn) {
15501   if (!Fn->hasPersonalityFn())
15502     report_fatal_error(
15503         "querying registration node size for function without personality");
15504   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15505   // WinEHStatePass for the full struct definition.
15506   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15507   case EHPersonality::MSVC_X86SEH: return 24;
15508   case EHPersonality::MSVC_CXX: return 16;
15509   default: break;
15510   }
15511   report_fatal_error("can only recover FP for MSVC EH personality functions");
15512 }
15513
15514 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15515 /// function or when returning to a parent frame after catching an exception, we
15516 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15517 /// Here's the math:
15518 ///   RegNodeBase = EntryEBP - RegNodeSize
15519 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15520 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15521 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15522 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15523                                    SDValue EntryEBP) {
15524   MachineFunction &MF = DAG.getMachineFunction();
15525   SDLoc dl;
15526
15527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15528   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15529
15530   // It's possible that the parent function no longer has a personality function
15531   // if the exceptional code was optimized away, in which case we just return
15532   // the incoming EBP.
15533   if (!Fn->hasPersonalityFn())
15534     return EntryEBP;
15535
15536   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15537
15538   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15539   // registration.
15540   MCSymbol *OffsetSym =
15541       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15542           GlobalValue::getRealLinkageName(Fn->getName()));
15543   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15544   SDValue RegNodeFrameOffset =
15545       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15546
15547   // RegNodeBase = EntryEBP - RegNodeSize
15548   // ParentFP = RegNodeBase - RegNodeFrameOffset
15549   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15550                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15551   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15552 }
15553
15554 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15555                                        SelectionDAG &DAG) {
15556   SDLoc dl(Op);
15557   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15558   EVT VT = Op.getValueType();
15559   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15560   if (IntrData) {
15561     switch(IntrData->Type) {
15562     case INTR_TYPE_1OP:
15563       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15564     case INTR_TYPE_2OP:
15565       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15566         Op.getOperand(2));
15567     case INTR_TYPE_3OP:
15568       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15569         Op.getOperand(2), Op.getOperand(3));
15570     case INTR_TYPE_4OP:
15571       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15572         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15573     case INTR_TYPE_1OP_MASK_RM: {
15574       SDValue Src = Op.getOperand(1);
15575       SDValue PassThru = Op.getOperand(2);
15576       SDValue Mask = Op.getOperand(3);
15577       SDValue RoundingMode;
15578       // We allways add rounding mode to the Node.
15579       // If the rounding mode is not specified, we add the
15580       // "current direction" mode.
15581       if (Op.getNumOperands() == 4)
15582         RoundingMode =
15583           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15584       else
15585         RoundingMode = Op.getOperand(4);
15586       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15587       if (IntrWithRoundingModeOpcode != 0)
15588         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15589             X86::STATIC_ROUNDING::CUR_DIRECTION)
15590           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15591                                       dl, Op.getValueType(), Src, RoundingMode),
15592                                       Mask, PassThru, Subtarget, DAG);
15593       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15594                                               RoundingMode),
15595                                   Mask, PassThru, Subtarget, DAG);
15596     }
15597     case INTR_TYPE_1OP_MASK: {
15598       SDValue Src = Op.getOperand(1);
15599       SDValue PassThru = Op.getOperand(2);
15600       SDValue Mask = Op.getOperand(3);
15601       // We add rounding mode to the Node when
15602       //   - RM Opcode is specified and
15603       //   - RM is not "current direction".
15604       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15605       if (IntrWithRoundingModeOpcode != 0) {
15606         SDValue Rnd = Op.getOperand(4);
15607         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15608         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15609           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15610                                       dl, Op.getValueType(),
15611                                       Src, Rnd),
15612                                       Mask, PassThru, Subtarget, DAG);
15613         }
15614       }
15615       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15616                                   Mask, PassThru, Subtarget, DAG);
15617     }
15618     case INTR_TYPE_SCALAR_MASK_RM: {
15619       SDValue Src1 = Op.getOperand(1);
15620       SDValue Src2 = Op.getOperand(2);
15621       SDValue Src0 = Op.getOperand(3);
15622       SDValue Mask = Op.getOperand(4);
15623       // There are 2 kinds of intrinsics in this group:
15624       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15625       // (2) With rounding mode and sae - 7 operands.
15626       if (Op.getNumOperands() == 6) {
15627         SDValue Sae  = Op.getOperand(5);
15628         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15629         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15630                                                 Sae),
15631                                     Mask, Src0, Subtarget, DAG);
15632       }
15633       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15634       SDValue RoundingMode  = Op.getOperand(5);
15635       SDValue Sae  = Op.getOperand(6);
15636       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15637                                               RoundingMode, Sae),
15638                                   Mask, Src0, Subtarget, DAG);
15639     }
15640     case INTR_TYPE_2OP_MASK: {
15641       SDValue Src1 = Op.getOperand(1);
15642       SDValue Src2 = Op.getOperand(2);
15643       SDValue PassThru = Op.getOperand(3);
15644       SDValue Mask = Op.getOperand(4);
15645       // We specify 2 possible opcodes for intrinsics with rounding modes.
15646       // First, we check if the intrinsic may have non-default rounding mode,
15647       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15648       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15649       if (IntrWithRoundingModeOpcode != 0) {
15650         SDValue Rnd = Op.getOperand(5);
15651         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15652         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15653           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15654                                       dl, Op.getValueType(),
15655                                       Src1, Src2, Rnd),
15656                                       Mask, PassThru, Subtarget, DAG);
15657         }
15658       }
15659       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15660                                               Src1,Src2),
15661                                   Mask, PassThru, Subtarget, DAG);
15662     }
15663     case INTR_TYPE_2OP_MASK_RM: {
15664       SDValue Src1 = Op.getOperand(1);
15665       SDValue Src2 = Op.getOperand(2);
15666       SDValue PassThru = Op.getOperand(3);
15667       SDValue Mask = Op.getOperand(4);
15668       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15669       // First, we check if the intrinsic have rounding mode (6 operands),
15670       // if not, we set rounding mode to "current".
15671       SDValue Rnd;
15672       if (Op.getNumOperands() == 6)
15673         Rnd = Op.getOperand(5);
15674       else
15675         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15676       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15677                                               Src1, Src2, Rnd),
15678                                   Mask, PassThru, Subtarget, DAG);
15679     }
15680     case INTR_TYPE_3OP_MASK_RM: {
15681       SDValue Src1 = Op.getOperand(1);
15682       SDValue Src2 = Op.getOperand(2);
15683       SDValue Imm = Op.getOperand(3);
15684       SDValue PassThru = Op.getOperand(4);
15685       SDValue Mask = Op.getOperand(5);
15686       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15687       // First, we check if the intrinsic have rounding mode (7 operands),
15688       // if not, we set rounding mode to "current".
15689       SDValue Rnd;
15690       if (Op.getNumOperands() == 7)
15691         Rnd = Op.getOperand(6);
15692       else
15693         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15694       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15695         Src1, Src2, Imm, Rnd),
15696         Mask, PassThru, Subtarget, DAG);
15697     }
15698     case INTR_TYPE_3OP_IMM8_MASK:
15699     case INTR_TYPE_3OP_MASK: {
15700       SDValue Src1 = Op.getOperand(1);
15701       SDValue Src2 = Op.getOperand(2);
15702       SDValue Src3 = Op.getOperand(3);
15703       SDValue PassThru = Op.getOperand(4);
15704       SDValue Mask = Op.getOperand(5);
15705
15706       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15707         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15708       // We specify 2 possible opcodes for intrinsics with rounding modes.
15709       // First, we check if the intrinsic may have non-default rounding mode,
15710       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15711       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15712       if (IntrWithRoundingModeOpcode != 0) {
15713         SDValue Rnd = Op.getOperand(6);
15714         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15715         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15716           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15717                                       dl, Op.getValueType(),
15718                                       Src1, Src2, Src3, Rnd),
15719                                       Mask, PassThru, Subtarget, DAG);
15720         }
15721       }
15722       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15723                                               Src1, Src2, Src3),
15724                                   Mask, PassThru, Subtarget, DAG);
15725     }
15726     case VPERM_3OP_MASKZ:
15727     case VPERM_3OP_MASK:
15728     case FMA_OP_MASK3:
15729     case FMA_OP_MASKZ:
15730     case FMA_OP_MASK: {
15731       SDValue Src1 = Op.getOperand(1);
15732       SDValue Src2 = Op.getOperand(2);
15733       SDValue Src3 = Op.getOperand(3);
15734       SDValue Mask = Op.getOperand(4);
15735       EVT VT = Op.getValueType();
15736       SDValue PassThru = SDValue();
15737
15738       // set PassThru element
15739       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15740         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15741       else if (IntrData->Type == FMA_OP_MASK3)
15742         PassThru = Src3;
15743       else
15744         PassThru = Src1;
15745
15746       // We specify 2 possible opcodes for intrinsics with rounding modes.
15747       // First, we check if the intrinsic may have non-default rounding mode,
15748       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15749       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15750       if (IntrWithRoundingModeOpcode != 0) {
15751         SDValue Rnd = Op.getOperand(5);
15752         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15753             X86::STATIC_ROUNDING::CUR_DIRECTION)
15754           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15755                                                   dl, Op.getValueType(),
15756                                                   Src1, Src2, Src3, Rnd),
15757                                       Mask, PassThru, Subtarget, DAG);
15758       }
15759       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15760                                               dl, Op.getValueType(),
15761                                               Src1, Src2, Src3),
15762                                   Mask, PassThru, Subtarget, DAG);
15763     }
15764     case CMP_MASK:
15765     case CMP_MASK_CC: {
15766       // Comparison intrinsics with masks.
15767       // Example of transformation:
15768       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15769       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15770       // (i8 (bitcast
15771       //   (v8i1 (insert_subvector undef,
15772       //           (v2i1 (and (PCMPEQM %a, %b),
15773       //                      (extract_subvector
15774       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15775       EVT VT = Op.getOperand(1).getValueType();
15776       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15777                                     VT.getVectorNumElements());
15778       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15779       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15780                                        Mask.getValueType().getSizeInBits());
15781       SDValue Cmp;
15782       if (IntrData->Type == CMP_MASK_CC) {
15783         SDValue CC = Op.getOperand(3);
15784         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15785         // We specify 2 possible opcodes for intrinsics with rounding modes.
15786         // First, we check if the intrinsic may have non-default rounding mode,
15787         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15788         if (IntrData->Opc1 != 0) {
15789           SDValue Rnd = Op.getOperand(5);
15790           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15791               X86::STATIC_ROUNDING::CUR_DIRECTION)
15792             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15793                               Op.getOperand(2), CC, Rnd);
15794         }
15795         //default rounding mode
15796         if(!Cmp.getNode())
15797             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15798                               Op.getOperand(2), CC);
15799
15800       } else {
15801         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15802         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15803                           Op.getOperand(2));
15804       }
15805       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15806                                              DAG.getTargetConstant(0, dl,
15807                                                                    MaskVT),
15808                                              Subtarget, DAG);
15809       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15810                                 DAG.getUNDEF(BitcastVT), CmpMask,
15811                                 DAG.getIntPtrConstant(0, dl));
15812       return DAG.getBitcast(Op.getValueType(), Res);
15813     }
15814     case COMI: { // Comparison intrinsics
15815       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15816       SDValue LHS = Op.getOperand(1);
15817       SDValue RHS = Op.getOperand(2);
15818       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15819       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15820       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15821       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15822                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15823       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15824     }
15825     case VSHIFT:
15826       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15827                                  Op.getOperand(1), Op.getOperand(2), DAG);
15828     case VSHIFT_MASK:
15829       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15830                                                       Op.getSimpleValueType(),
15831                                                       Op.getOperand(1),
15832                                                       Op.getOperand(2), DAG),
15833                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15834                                   DAG);
15835     case COMPRESS_EXPAND_IN_REG: {
15836       SDValue Mask = Op.getOperand(3);
15837       SDValue DataToCompress = Op.getOperand(1);
15838       SDValue PassThru = Op.getOperand(2);
15839       if (isAllOnes(Mask)) // return data as is
15840         return Op.getOperand(1);
15841
15842       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15843                                               DataToCompress),
15844                                   Mask, PassThru, Subtarget, DAG);
15845     }
15846     case BLEND: {
15847       SDValue Mask = Op.getOperand(3);
15848       EVT VT = Op.getValueType();
15849       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15850                                     VT.getVectorNumElements());
15851       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15852                                        Mask.getValueType().getSizeInBits());
15853       SDLoc dl(Op);
15854       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15855                                   DAG.getBitcast(BitcastVT, Mask),
15856                                   DAG.getIntPtrConstant(0, dl));
15857       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15858                          Op.getOperand(2));
15859     }
15860     default:
15861       break;
15862     }
15863   }
15864
15865   switch (IntNo) {
15866   default: return SDValue();    // Don't custom lower most intrinsics.
15867
15868   case Intrinsic::x86_avx2_permd:
15869   case Intrinsic::x86_avx2_permps:
15870     // Operands intentionally swapped. Mask is last operand to intrinsic,
15871     // but second operand for node/instruction.
15872     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15873                        Op.getOperand(2), Op.getOperand(1));
15874
15875   // ptest and testp intrinsics. The intrinsic these come from are designed to
15876   // return an integer value, not just an instruction so lower it to the ptest
15877   // or testp pattern and a setcc for the result.
15878   case Intrinsic::x86_sse41_ptestz:
15879   case Intrinsic::x86_sse41_ptestc:
15880   case Intrinsic::x86_sse41_ptestnzc:
15881   case Intrinsic::x86_avx_ptestz_256:
15882   case Intrinsic::x86_avx_ptestc_256:
15883   case Intrinsic::x86_avx_ptestnzc_256:
15884   case Intrinsic::x86_avx_vtestz_ps:
15885   case Intrinsic::x86_avx_vtestc_ps:
15886   case Intrinsic::x86_avx_vtestnzc_ps:
15887   case Intrinsic::x86_avx_vtestz_pd:
15888   case Intrinsic::x86_avx_vtestc_pd:
15889   case Intrinsic::x86_avx_vtestnzc_pd:
15890   case Intrinsic::x86_avx_vtestz_ps_256:
15891   case Intrinsic::x86_avx_vtestc_ps_256:
15892   case Intrinsic::x86_avx_vtestnzc_ps_256:
15893   case Intrinsic::x86_avx_vtestz_pd_256:
15894   case Intrinsic::x86_avx_vtestc_pd_256:
15895   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15896     bool IsTestPacked = false;
15897     unsigned X86CC;
15898     switch (IntNo) {
15899     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15900     case Intrinsic::x86_avx_vtestz_ps:
15901     case Intrinsic::x86_avx_vtestz_pd:
15902     case Intrinsic::x86_avx_vtestz_ps_256:
15903     case Intrinsic::x86_avx_vtestz_pd_256:
15904       IsTestPacked = true; // Fallthrough
15905     case Intrinsic::x86_sse41_ptestz:
15906     case Intrinsic::x86_avx_ptestz_256:
15907       // ZF = 1
15908       X86CC = X86::COND_E;
15909       break;
15910     case Intrinsic::x86_avx_vtestc_ps:
15911     case Intrinsic::x86_avx_vtestc_pd:
15912     case Intrinsic::x86_avx_vtestc_ps_256:
15913     case Intrinsic::x86_avx_vtestc_pd_256:
15914       IsTestPacked = true; // Fallthrough
15915     case Intrinsic::x86_sse41_ptestc:
15916     case Intrinsic::x86_avx_ptestc_256:
15917       // CF = 1
15918       X86CC = X86::COND_B;
15919       break;
15920     case Intrinsic::x86_avx_vtestnzc_ps:
15921     case Intrinsic::x86_avx_vtestnzc_pd:
15922     case Intrinsic::x86_avx_vtestnzc_ps_256:
15923     case Intrinsic::x86_avx_vtestnzc_pd_256:
15924       IsTestPacked = true; // Fallthrough
15925     case Intrinsic::x86_sse41_ptestnzc:
15926     case Intrinsic::x86_avx_ptestnzc_256:
15927       // ZF and CF = 0
15928       X86CC = X86::COND_A;
15929       break;
15930     }
15931
15932     SDValue LHS = Op.getOperand(1);
15933     SDValue RHS = Op.getOperand(2);
15934     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15935     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15936     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15937     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15938     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15939   }
15940   case Intrinsic::x86_avx512_kortestz_w:
15941   case Intrinsic::x86_avx512_kortestc_w: {
15942     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15943     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15944     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15945     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15946     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15947     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15948     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15949   }
15950
15951   case Intrinsic::x86_sse42_pcmpistria128:
15952   case Intrinsic::x86_sse42_pcmpestria128:
15953   case Intrinsic::x86_sse42_pcmpistric128:
15954   case Intrinsic::x86_sse42_pcmpestric128:
15955   case Intrinsic::x86_sse42_pcmpistrio128:
15956   case Intrinsic::x86_sse42_pcmpestrio128:
15957   case Intrinsic::x86_sse42_pcmpistris128:
15958   case Intrinsic::x86_sse42_pcmpestris128:
15959   case Intrinsic::x86_sse42_pcmpistriz128:
15960   case Intrinsic::x86_sse42_pcmpestriz128: {
15961     unsigned Opcode;
15962     unsigned X86CC;
15963     switch (IntNo) {
15964     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15965     case Intrinsic::x86_sse42_pcmpistria128:
15966       Opcode = X86ISD::PCMPISTRI;
15967       X86CC = X86::COND_A;
15968       break;
15969     case Intrinsic::x86_sse42_pcmpestria128:
15970       Opcode = X86ISD::PCMPESTRI;
15971       X86CC = X86::COND_A;
15972       break;
15973     case Intrinsic::x86_sse42_pcmpistric128:
15974       Opcode = X86ISD::PCMPISTRI;
15975       X86CC = X86::COND_B;
15976       break;
15977     case Intrinsic::x86_sse42_pcmpestric128:
15978       Opcode = X86ISD::PCMPESTRI;
15979       X86CC = X86::COND_B;
15980       break;
15981     case Intrinsic::x86_sse42_pcmpistrio128:
15982       Opcode = X86ISD::PCMPISTRI;
15983       X86CC = X86::COND_O;
15984       break;
15985     case Intrinsic::x86_sse42_pcmpestrio128:
15986       Opcode = X86ISD::PCMPESTRI;
15987       X86CC = X86::COND_O;
15988       break;
15989     case Intrinsic::x86_sse42_pcmpistris128:
15990       Opcode = X86ISD::PCMPISTRI;
15991       X86CC = X86::COND_S;
15992       break;
15993     case Intrinsic::x86_sse42_pcmpestris128:
15994       Opcode = X86ISD::PCMPESTRI;
15995       X86CC = X86::COND_S;
15996       break;
15997     case Intrinsic::x86_sse42_pcmpistriz128:
15998       Opcode = X86ISD::PCMPISTRI;
15999       X86CC = X86::COND_E;
16000       break;
16001     case Intrinsic::x86_sse42_pcmpestriz128:
16002       Opcode = X86ISD::PCMPESTRI;
16003       X86CC = X86::COND_E;
16004       break;
16005     }
16006     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16007     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16008     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16009     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16010                                 DAG.getConstant(X86CC, dl, MVT::i8),
16011                                 SDValue(PCMP.getNode(), 1));
16012     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16013   }
16014
16015   case Intrinsic::x86_sse42_pcmpistri128:
16016   case Intrinsic::x86_sse42_pcmpestri128: {
16017     unsigned Opcode;
16018     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16019       Opcode = X86ISD::PCMPISTRI;
16020     else
16021       Opcode = X86ISD::PCMPESTRI;
16022
16023     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16024     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16025     return DAG.getNode(Opcode, dl, VTs, NewOps);
16026   }
16027
16028   case Intrinsic::x86_seh_lsda: {
16029     // Compute the symbol for the LSDA. We know it'll get emitted later.
16030     MachineFunction &MF = DAG.getMachineFunction();
16031     SDValue Op1 = Op.getOperand(1);
16032     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16033     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16034         GlobalValue::getRealLinkageName(Fn->getName()));
16035
16036     // Generate a simple absolute symbol reference. This intrinsic is only
16037     // supported on 32-bit Windows, which isn't PIC.
16038     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16039     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16040   }
16041
16042   case Intrinsic::x86_seh_recoverfp: {
16043     SDValue FnOp = Op.getOperand(1);
16044     SDValue IncomingFPOp = Op.getOperand(2);
16045     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16046     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16047     if (!Fn)
16048       report_fatal_error(
16049           "llvm.x86.seh.recoverfp must take a function as the first argument");
16050     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16051   }
16052
16053   case Intrinsic::localaddress: {
16054     // Returns one of the stack, base, or frame pointer registers, depending on
16055     // which is used to reference local variables.
16056     MachineFunction &MF = DAG.getMachineFunction();
16057     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16058     unsigned Reg;
16059     if (RegInfo->hasBasePointer(MF))
16060       Reg = RegInfo->getBaseRegister();
16061     else // This function handles the SP or FP case.
16062       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16063     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16064   }
16065   }
16066 }
16067
16068 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16069                               SDValue Src, SDValue Mask, SDValue Base,
16070                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16071                               const X86Subtarget * Subtarget) {
16072   SDLoc dl(Op);
16073   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16074   if (!C)
16075     llvm_unreachable("Invalid scale type");
16076   unsigned ScaleVal = C->getZExtValue();
16077   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16078     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16079
16080   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16081   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16082                              Index.getSimpleValueType().getVectorNumElements());
16083   SDValue MaskInReg;
16084   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16085   if (MaskC)
16086     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16087   else {
16088     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16089                                      Mask.getValueType().getSizeInBits());
16090
16091     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16092     // are extracted by EXTRACT_SUBVECTOR.
16093     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16094                             DAG.getBitcast(BitcastVT, Mask),
16095                             DAG.getIntPtrConstant(0, dl));
16096   }
16097   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16098   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16099   SDValue Segment = DAG.getRegister(0, MVT::i32);
16100   if (Src.getOpcode() == ISD::UNDEF)
16101     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16102   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16103   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16104   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16105   return DAG.getMergeValues(RetOps, dl);
16106 }
16107
16108 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16109                                SDValue Src, SDValue Mask, SDValue Base,
16110                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16111   SDLoc dl(Op);
16112   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16113   if (!C)
16114     llvm_unreachable("Invalid scale type");
16115   unsigned ScaleVal = C->getZExtValue();
16116   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16117     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16118
16119   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16120   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16121   SDValue Segment = DAG.getRegister(0, MVT::i32);
16122   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16123                              Index.getSimpleValueType().getVectorNumElements());
16124   SDValue MaskInReg;
16125   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16126   if (MaskC)
16127     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16128   else {
16129     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16130                                      Mask.getValueType().getSizeInBits());
16131
16132     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16133     // are extracted by EXTRACT_SUBVECTOR.
16134     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16135                             DAG.getBitcast(BitcastVT, Mask),
16136                             DAG.getIntPtrConstant(0, dl));
16137   }
16138   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16139   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16140   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16141   return SDValue(Res, 1);
16142 }
16143
16144 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16145                                SDValue Mask, SDValue Base, SDValue Index,
16146                                SDValue ScaleOp, SDValue Chain) {
16147   SDLoc dl(Op);
16148   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16149   assert(C && "Invalid scale type");
16150   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16151   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16152   SDValue Segment = DAG.getRegister(0, MVT::i32);
16153   EVT MaskVT =
16154     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16155   SDValue MaskInReg;
16156   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16157   if (MaskC)
16158     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16159   else
16160     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16161   //SDVTList VTs = DAG.getVTList(MVT::Other);
16162   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16163   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16164   return SDValue(Res, 0);
16165 }
16166
16167 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16168 // read performance monitor counters (x86_rdpmc).
16169 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16170                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16171                               SmallVectorImpl<SDValue> &Results) {
16172   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16173   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16174   SDValue LO, HI;
16175
16176   // The ECX register is used to select the index of the performance counter
16177   // to read.
16178   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16179                                    N->getOperand(2));
16180   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16181
16182   // Reads the content of a 64-bit performance counter and returns it in the
16183   // registers EDX:EAX.
16184   if (Subtarget->is64Bit()) {
16185     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16186     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16187                             LO.getValue(2));
16188   } else {
16189     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16190     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16191                             LO.getValue(2));
16192   }
16193   Chain = HI.getValue(1);
16194
16195   if (Subtarget->is64Bit()) {
16196     // The EAX register is loaded with the low-order 32 bits. The EDX register
16197     // is loaded with the supported high-order bits of the counter.
16198     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16199                               DAG.getConstant(32, DL, MVT::i8));
16200     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16201     Results.push_back(Chain);
16202     return;
16203   }
16204
16205   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16206   SDValue Ops[] = { LO, HI };
16207   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16208   Results.push_back(Pair);
16209   Results.push_back(Chain);
16210 }
16211
16212 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16213 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16214 // also used to custom lower READCYCLECOUNTER nodes.
16215 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16216                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16217                               SmallVectorImpl<SDValue> &Results) {
16218   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16219   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16220   SDValue LO, HI;
16221
16222   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16223   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16224   // and the EAX register is loaded with the low-order 32 bits.
16225   if (Subtarget->is64Bit()) {
16226     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16227     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16228                             LO.getValue(2));
16229   } else {
16230     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16231     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16232                             LO.getValue(2));
16233   }
16234   SDValue Chain = HI.getValue(1);
16235
16236   if (Opcode == X86ISD::RDTSCP_DAG) {
16237     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16238
16239     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16240     // the ECX register. Add 'ecx' explicitly to the chain.
16241     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16242                                      HI.getValue(2));
16243     // Explicitly store the content of ECX at the location passed in input
16244     // to the 'rdtscp' intrinsic.
16245     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16246                          MachinePointerInfo(), false, false, 0);
16247   }
16248
16249   if (Subtarget->is64Bit()) {
16250     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16251     // the EAX register is loaded with the low-order 32 bits.
16252     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16253                               DAG.getConstant(32, DL, MVT::i8));
16254     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16255     Results.push_back(Chain);
16256     return;
16257   }
16258
16259   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16260   SDValue Ops[] = { LO, HI };
16261   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16262   Results.push_back(Pair);
16263   Results.push_back(Chain);
16264 }
16265
16266 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16267                                      SelectionDAG &DAG) {
16268   SmallVector<SDValue, 2> Results;
16269   SDLoc DL(Op);
16270   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16271                           Results);
16272   return DAG.getMergeValues(Results, DL);
16273 }
16274
16275 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16276                                     SelectionDAG &DAG) {
16277   MachineFunction &MF = DAG.getMachineFunction();
16278   const Function *Fn = MF.getFunction();
16279   SDLoc dl(Op);
16280   SDValue Chain = Op.getOperand(0);
16281
16282   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16283          "using llvm.x86.seh.restoreframe requires a frame pointer");
16284
16285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16286   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16287
16288   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16289   unsigned FrameReg =
16290       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16291   unsigned SPReg = RegInfo->getStackRegister();
16292   unsigned SlotSize = RegInfo->getSlotSize();
16293
16294   // Get incoming EBP.
16295   SDValue IncomingEBP =
16296       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16297
16298   // SP is saved in the first field of every registration node, so load
16299   // [EBP-RegNodeSize] into SP.
16300   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16301   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16302                                DAG.getConstant(-RegNodeSize, dl, VT));
16303   SDValue NewSP =
16304       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16305                   false, VT.getScalarSizeInBits() / 8);
16306   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16307
16308   if (!RegInfo->needsStackRealignment(MF)) {
16309     // Adjust EBP to point back to the original frame position.
16310     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16311     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16312   } else {
16313     assert(RegInfo->hasBasePointer(MF) &&
16314            "functions with Win32 EH must use frame or base pointer register");
16315
16316     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16317     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16318     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16319
16320     // Reload the spilled EBP value, now that the stack and base pointers are
16321     // set up.
16322     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16323     X86FI->setHasSEHFramePtrSave(true);
16324     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16325     X86FI->setSEHFramePtrSaveIndex(FI);
16326     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16327                                 MachinePointerInfo(), false, false, false,
16328                                 VT.getScalarSizeInBits() / 8);
16329     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16330   }
16331
16332   return Chain;
16333 }
16334
16335 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16336 /// return truncate Store/MaskedStore Node
16337 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16338                                                SelectionDAG &DAG,
16339                                                MVT ElementType) {
16340   SDLoc dl(Op);
16341   SDValue Mask = Op.getOperand(4);
16342   SDValue DataToTruncate = Op.getOperand(3);
16343   SDValue Addr = Op.getOperand(2);
16344   SDValue Chain = Op.getOperand(0);
16345
16346   EVT VT  = DataToTruncate.getValueType();
16347   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16348                              ElementType, VT.getVectorNumElements());
16349
16350   if (isAllOnes(Mask)) // return just a truncate store
16351     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16352                              MachinePointerInfo(), SVT, false, false,
16353                              SVT.getScalarSizeInBits()/8);
16354
16355   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16356                                 MVT::i1, VT.getVectorNumElements());
16357   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16358                                    Mask.getValueType().getSizeInBits());
16359   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16360   // are extracted by EXTRACT_SUBVECTOR.
16361   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16362                               DAG.getBitcast(BitcastVT, Mask),
16363                               DAG.getIntPtrConstant(0, dl));
16364
16365   MachineMemOperand *MMO = DAG.getMachineFunction().
16366     getMachineMemOperand(MachinePointerInfo(),
16367                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16368                          SVT.getScalarSizeInBits()/8);
16369
16370   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16371                             VMask, SVT, MMO, true);
16372 }
16373
16374 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16375                                       SelectionDAG &DAG) {
16376   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16377
16378   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16379   if (!IntrData) {
16380     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16381       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16382     return SDValue();
16383   }
16384
16385   SDLoc dl(Op);
16386   switch(IntrData->Type) {
16387   default:
16388     llvm_unreachable("Unknown Intrinsic Type");
16389     break;
16390   case RDSEED:
16391   case RDRAND: {
16392     // Emit the node with the right value type.
16393     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16394     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16395
16396     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16397     // Otherwise return the value from Rand, which is always 0, casted to i32.
16398     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16399                       DAG.getConstant(1, dl, Op->getValueType(1)),
16400                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16401                       SDValue(Result.getNode(), 1) };
16402     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16403                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16404                                   Ops);
16405
16406     // Return { result, isValid, chain }.
16407     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16408                        SDValue(Result.getNode(), 2));
16409   }
16410   case GATHER: {
16411   //gather(v1, mask, index, base, scale);
16412     SDValue Chain = Op.getOperand(0);
16413     SDValue Src   = Op.getOperand(2);
16414     SDValue Base  = Op.getOperand(3);
16415     SDValue Index = Op.getOperand(4);
16416     SDValue Mask  = Op.getOperand(5);
16417     SDValue Scale = Op.getOperand(6);
16418     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16419                          Chain, Subtarget);
16420   }
16421   case SCATTER: {
16422   //scatter(base, mask, index, v1, scale);
16423     SDValue Chain = Op.getOperand(0);
16424     SDValue Base  = Op.getOperand(2);
16425     SDValue Mask  = Op.getOperand(3);
16426     SDValue Index = Op.getOperand(4);
16427     SDValue Src   = Op.getOperand(5);
16428     SDValue Scale = Op.getOperand(6);
16429     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16430                           Scale, Chain);
16431   }
16432   case PREFETCH: {
16433     SDValue Hint = Op.getOperand(6);
16434     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16435     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16436     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16437     SDValue Chain = Op.getOperand(0);
16438     SDValue Mask  = Op.getOperand(2);
16439     SDValue Index = Op.getOperand(3);
16440     SDValue Base  = Op.getOperand(4);
16441     SDValue Scale = Op.getOperand(5);
16442     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16443   }
16444   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16445   case RDTSC: {
16446     SmallVector<SDValue, 2> Results;
16447     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16448                             Results);
16449     return DAG.getMergeValues(Results, dl);
16450   }
16451   // Read Performance Monitoring Counters.
16452   case RDPMC: {
16453     SmallVector<SDValue, 2> Results;
16454     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16455     return DAG.getMergeValues(Results, dl);
16456   }
16457   // XTEST intrinsics.
16458   case XTEST: {
16459     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16460     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16461     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16462                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16463                                 InTrans);
16464     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16465     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16466                        Ret, SDValue(InTrans.getNode(), 1));
16467   }
16468   // ADC/ADCX/SBB
16469   case ADX: {
16470     SmallVector<SDValue, 2> Results;
16471     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16472     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16473     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16474                                 DAG.getConstant(-1, dl, MVT::i8));
16475     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16476                               Op.getOperand(4), GenCF.getValue(1));
16477     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16478                                  Op.getOperand(5), MachinePointerInfo(),
16479                                  false, false, 0);
16480     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16481                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16482                                 Res.getValue(1));
16483     Results.push_back(SetCC);
16484     Results.push_back(Store);
16485     return DAG.getMergeValues(Results, dl);
16486   }
16487   case COMPRESS_TO_MEM: {
16488     SDLoc dl(Op);
16489     SDValue Mask = Op.getOperand(4);
16490     SDValue DataToCompress = Op.getOperand(3);
16491     SDValue Addr = Op.getOperand(2);
16492     SDValue Chain = Op.getOperand(0);
16493
16494     EVT VT = DataToCompress.getValueType();
16495     if (isAllOnes(Mask)) // return just a store
16496       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16497                           MachinePointerInfo(), false, false,
16498                           VT.getScalarSizeInBits()/8);
16499
16500     SDValue Compressed =
16501       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16502                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16503     return DAG.getStore(Chain, dl, Compressed, Addr,
16504                         MachinePointerInfo(), false, false,
16505                         VT.getScalarSizeInBits()/8);
16506   }
16507   case TRUNCATE_TO_MEM_VI8:
16508     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16509   case TRUNCATE_TO_MEM_VI16:
16510     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16511   case TRUNCATE_TO_MEM_VI32:
16512     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16513   case EXPAND_FROM_MEM: {
16514     SDLoc dl(Op);
16515     SDValue Mask = Op.getOperand(4);
16516     SDValue PassThru = Op.getOperand(3);
16517     SDValue Addr = Op.getOperand(2);
16518     SDValue Chain = Op.getOperand(0);
16519     EVT VT = Op.getValueType();
16520
16521     if (isAllOnes(Mask)) // return just a load
16522       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16523                          false, VT.getScalarSizeInBits()/8);
16524
16525     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16526                                        false, false, false,
16527                                        VT.getScalarSizeInBits()/8);
16528
16529     SDValue Results[] = {
16530       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16531                            Mask, PassThru, Subtarget, DAG), Chain};
16532     return DAG.getMergeValues(Results, dl);
16533   }
16534   }
16535 }
16536
16537 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16538                                            SelectionDAG &DAG) const {
16539   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16540   MFI->setReturnAddressIsTaken(true);
16541
16542   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16543     return SDValue();
16544
16545   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16546   SDLoc dl(Op);
16547   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16548
16549   if (Depth > 0) {
16550     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16551     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16552     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16553     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16554                        DAG.getNode(ISD::ADD, dl, PtrVT,
16555                                    FrameAddr, Offset),
16556                        MachinePointerInfo(), false, false, false, 0);
16557   }
16558
16559   // Just load the return address.
16560   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16561   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16562                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16563 }
16564
16565 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16566   MachineFunction &MF = DAG.getMachineFunction();
16567   MachineFrameInfo *MFI = MF.getFrameInfo();
16568   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16569   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16570   EVT VT = Op.getValueType();
16571
16572   MFI->setFrameAddressIsTaken(true);
16573
16574   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16575     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16576     // is not possible to crawl up the stack without looking at the unwind codes
16577     // simultaneously.
16578     int FrameAddrIndex = FuncInfo->getFAIndex();
16579     if (!FrameAddrIndex) {
16580       // Set up a frame object for the return address.
16581       unsigned SlotSize = RegInfo->getSlotSize();
16582       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16583           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16584       FuncInfo->setFAIndex(FrameAddrIndex);
16585     }
16586     return DAG.getFrameIndex(FrameAddrIndex, VT);
16587   }
16588
16589   unsigned FrameReg =
16590       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16591   SDLoc dl(Op);  // FIXME probably not meaningful
16592   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16593   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16594           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16595          "Invalid Frame Register!");
16596   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16597   while (Depth--)
16598     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16599                             MachinePointerInfo(),
16600                             false, false, false, 0);
16601   return FrameAddr;
16602 }
16603
16604 // FIXME? Maybe this could be a TableGen attribute on some registers and
16605 // this table could be generated automatically from RegInfo.
16606 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16607                                               SelectionDAG &DAG) const {
16608   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16609   const MachineFunction &MF = DAG.getMachineFunction();
16610
16611   unsigned Reg = StringSwitch<unsigned>(RegName)
16612                        .Case("esp", X86::ESP)
16613                        .Case("rsp", X86::RSP)
16614                        .Case("ebp", X86::EBP)
16615                        .Case("rbp", X86::RBP)
16616                        .Default(0);
16617
16618   if (Reg == X86::EBP || Reg == X86::RBP) {
16619     if (!TFI.hasFP(MF))
16620       report_fatal_error("register " + StringRef(RegName) +
16621                          " is allocatable: function has no frame pointer");
16622 #ifndef NDEBUG
16623     else {
16624       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16625       unsigned FrameReg =
16626           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16627       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16628              "Invalid Frame Register!");
16629     }
16630 #endif
16631   }
16632
16633   if (Reg)
16634     return Reg;
16635
16636   report_fatal_error("Invalid register name global variable");
16637 }
16638
16639 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16640                                                      SelectionDAG &DAG) const {
16641   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16642   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16643 }
16644
16645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16646   SDValue Chain     = Op.getOperand(0);
16647   SDValue Offset    = Op.getOperand(1);
16648   SDValue Handler   = Op.getOperand(2);
16649   SDLoc dl      (Op);
16650
16651   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16652   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16653   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16654   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16655           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16656          "Invalid Frame Register!");
16657   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16658   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16659
16660   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16661                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16662                                                        dl));
16663   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16664   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16665                        false, false, 0);
16666   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16667
16668   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16669                      DAG.getRegister(StoreAddrReg, PtrVT));
16670 }
16671
16672 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16673   SDValue Chain = Op.getOperand(0);
16674   SDValue Dest = Op.getOperand(1);
16675   SDLoc DL(Op);
16676
16677   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16678   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16679
16680   // Load the address of the destination block.
16681   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16682   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16683   unsigned WrapperKind =
16684       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16685   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16686   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16687   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16688                      DAG.getRegister(ReturnReg, PtrVT));
16689 }
16690
16691 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16692                                                SelectionDAG &DAG) const {
16693   SDLoc DL(Op);
16694   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16695                      DAG.getVTList(MVT::i32, MVT::Other),
16696                      Op.getOperand(0), Op.getOperand(1));
16697 }
16698
16699 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16700                                                 SelectionDAG &DAG) const {
16701   SDLoc DL(Op);
16702   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16703                      Op.getOperand(0), Op.getOperand(1));
16704 }
16705
16706 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16707   return Op.getOperand(0);
16708 }
16709
16710 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16711                                                 SelectionDAG &DAG) const {
16712   SDValue Root = Op.getOperand(0);
16713   SDValue Trmp = Op.getOperand(1); // trampoline
16714   SDValue FPtr = Op.getOperand(2); // nested function
16715   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16716   SDLoc dl (Op);
16717
16718   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16719   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16720
16721   if (Subtarget->is64Bit()) {
16722     SDValue OutChains[6];
16723
16724     // Large code-model.
16725     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16726     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16727
16728     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16729     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16730
16731     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16732
16733     // Load the pointer to the nested function into R11.
16734     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16735     SDValue Addr = Trmp;
16736     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16737                                 Addr, MachinePointerInfo(TrmpAddr),
16738                                 false, false, 0);
16739
16740     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16741                        DAG.getConstant(2, dl, MVT::i64));
16742     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16743                                 MachinePointerInfo(TrmpAddr, 2),
16744                                 false, false, 2);
16745
16746     // Load the 'nest' parameter value into R10.
16747     // R10 is specified in X86CallingConv.td
16748     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16749     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16750                        DAG.getConstant(10, dl, MVT::i64));
16751     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16752                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16753                                 false, false, 0);
16754
16755     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16756                        DAG.getConstant(12, dl, MVT::i64));
16757     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16758                                 MachinePointerInfo(TrmpAddr, 12),
16759                                 false, false, 2);
16760
16761     // Jump to the nested function.
16762     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16763     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16764                        DAG.getConstant(20, dl, MVT::i64));
16765     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16766                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16767                                 false, false, 0);
16768
16769     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16770     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16771                        DAG.getConstant(22, dl, MVT::i64));
16772     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16773                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16774                                 false, false, 0);
16775
16776     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16777   } else {
16778     const Function *Func =
16779       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16780     CallingConv::ID CC = Func->getCallingConv();
16781     unsigned NestReg;
16782
16783     switch (CC) {
16784     default:
16785       llvm_unreachable("Unsupported calling convention");
16786     case CallingConv::C:
16787     case CallingConv::X86_StdCall: {
16788       // Pass 'nest' parameter in ECX.
16789       // Must be kept in sync with X86CallingConv.td
16790       NestReg = X86::ECX;
16791
16792       // Check that ECX wasn't needed by an 'inreg' parameter.
16793       FunctionType *FTy = Func->getFunctionType();
16794       const AttributeSet &Attrs = Func->getAttributes();
16795
16796       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16797         unsigned InRegCount = 0;
16798         unsigned Idx = 1;
16799
16800         for (FunctionType::param_iterator I = FTy->param_begin(),
16801              E = FTy->param_end(); I != E; ++I, ++Idx)
16802           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16803             auto &DL = DAG.getDataLayout();
16804             // FIXME: should only count parameters that are lowered to integers.
16805             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16806           }
16807
16808         if (InRegCount > 2) {
16809           report_fatal_error("Nest register in use - reduce number of inreg"
16810                              " parameters!");
16811         }
16812       }
16813       break;
16814     }
16815     case CallingConv::X86_FastCall:
16816     case CallingConv::X86_ThisCall:
16817     case CallingConv::Fast:
16818       // Pass 'nest' parameter in EAX.
16819       // Must be kept in sync with X86CallingConv.td
16820       NestReg = X86::EAX;
16821       break;
16822     }
16823
16824     SDValue OutChains[4];
16825     SDValue Addr, Disp;
16826
16827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16828                        DAG.getConstant(10, dl, MVT::i32));
16829     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16830
16831     // This is storing the opcode for MOV32ri.
16832     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16833     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16834     OutChains[0] = DAG.getStore(Root, dl,
16835                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16836                                 Trmp, MachinePointerInfo(TrmpAddr),
16837                                 false, false, 0);
16838
16839     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16840                        DAG.getConstant(1, dl, MVT::i32));
16841     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16842                                 MachinePointerInfo(TrmpAddr, 1),
16843                                 false, false, 1);
16844
16845     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16846     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16847                        DAG.getConstant(5, dl, MVT::i32));
16848     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16849                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16850                                 false, false, 1);
16851
16852     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16853                        DAG.getConstant(6, dl, MVT::i32));
16854     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16855                                 MachinePointerInfo(TrmpAddr, 6),
16856                                 false, false, 1);
16857
16858     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16859   }
16860 }
16861
16862 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16863                                             SelectionDAG &DAG) const {
16864   /*
16865    The rounding mode is in bits 11:10 of FPSR, and has the following
16866    settings:
16867      00 Round to nearest
16868      01 Round to -inf
16869      10 Round to +inf
16870      11 Round to 0
16871
16872   FLT_ROUNDS, on the other hand, expects the following:
16873     -1 Undefined
16874      0 Round to 0
16875      1 Round to nearest
16876      2 Round to +inf
16877      3 Round to -inf
16878
16879   To perform the conversion, we do:
16880     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16881   */
16882
16883   MachineFunction &MF = DAG.getMachineFunction();
16884   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16885   unsigned StackAlignment = TFI.getStackAlignment();
16886   MVT VT = Op.getSimpleValueType();
16887   SDLoc DL(Op);
16888
16889   // Save FP Control Word to stack slot
16890   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16891   SDValue StackSlot =
16892       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16893
16894   MachineMemOperand *MMO =
16895       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16896                               MachineMemOperand::MOStore, 2, 2);
16897
16898   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16899   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16900                                           DAG.getVTList(MVT::Other),
16901                                           Ops, MVT::i16, MMO);
16902
16903   // Load FP Control Word from stack slot
16904   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16905                             MachinePointerInfo(), false, false, false, 0);
16906
16907   // Transform as necessary
16908   SDValue CWD1 =
16909     DAG.getNode(ISD::SRL, DL, MVT::i16,
16910                 DAG.getNode(ISD::AND, DL, MVT::i16,
16911                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16912                 DAG.getConstant(11, DL, MVT::i8));
16913   SDValue CWD2 =
16914     DAG.getNode(ISD::SRL, DL, MVT::i16,
16915                 DAG.getNode(ISD::AND, DL, MVT::i16,
16916                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16917                 DAG.getConstant(9, DL, MVT::i8));
16918
16919   SDValue RetVal =
16920     DAG.getNode(ISD::AND, DL, MVT::i16,
16921                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16922                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16923                             DAG.getConstant(1, DL, MVT::i16)),
16924                 DAG.getConstant(3, DL, MVT::i16));
16925
16926   return DAG.getNode((VT.getSizeInBits() < 16 ?
16927                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16928 }
16929
16930 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16931   MVT VT = Op.getSimpleValueType();
16932   EVT OpVT = VT;
16933   unsigned NumBits = VT.getSizeInBits();
16934   SDLoc dl(Op);
16935
16936   Op = Op.getOperand(0);
16937   if (VT == MVT::i8) {
16938     // Zero extend to i32 since there is not an i8 bsr.
16939     OpVT = MVT::i32;
16940     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16941   }
16942
16943   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16944   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16945   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16946
16947   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16948   SDValue Ops[] = {
16949     Op,
16950     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16951     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16952     Op.getValue(1)
16953   };
16954   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16955
16956   // Finally xor with NumBits-1.
16957   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16958                    DAG.getConstant(NumBits - 1, dl, OpVT));
16959
16960   if (VT == MVT::i8)
16961     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16962   return Op;
16963 }
16964
16965 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16966   MVT VT = Op.getSimpleValueType();
16967   EVT OpVT = VT;
16968   unsigned NumBits = VT.getSizeInBits();
16969   SDLoc dl(Op);
16970
16971   Op = Op.getOperand(0);
16972   if (VT == MVT::i8) {
16973     // Zero extend to i32 since there is not an i8 bsr.
16974     OpVT = MVT::i32;
16975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16976   }
16977
16978   // Issue a bsr (scan bits in reverse).
16979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16981
16982   // And xor with NumBits-1.
16983   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16984                    DAG.getConstant(NumBits - 1, dl, OpVT));
16985
16986   if (VT == MVT::i8)
16987     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16988   return Op;
16989 }
16990
16991 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16992   MVT VT = Op.getSimpleValueType();
16993   unsigned NumBits = VT.getSizeInBits();
16994   SDLoc dl(Op);
16995   Op = Op.getOperand(0);
16996
16997   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16998   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16999   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17000
17001   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17002   SDValue Ops[] = {
17003     Op,
17004     DAG.getConstant(NumBits, dl, VT),
17005     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17006     Op.getValue(1)
17007   };
17008   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17009 }
17010
17011 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17012 // ones, and then concatenate the result back.
17013 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17014   MVT VT = Op.getSimpleValueType();
17015
17016   assert(VT.is256BitVector() && VT.isInteger() &&
17017          "Unsupported value type for operation");
17018
17019   unsigned NumElems = VT.getVectorNumElements();
17020   SDLoc dl(Op);
17021
17022   // Extract the LHS vectors
17023   SDValue LHS = Op.getOperand(0);
17024   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17025   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17026
17027   // Extract the RHS vectors
17028   SDValue RHS = Op.getOperand(1);
17029   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17030   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17031
17032   MVT EltVT = VT.getVectorElementType();
17033   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17034
17035   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17036                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17037                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17038 }
17039
17040 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17041   if (Op.getValueType() == MVT::i1)
17042     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17043                        Op.getOperand(0), Op.getOperand(1));
17044   assert(Op.getSimpleValueType().is256BitVector() &&
17045          Op.getSimpleValueType().isInteger() &&
17046          "Only handle AVX 256-bit vector integer operation");
17047   return Lower256IntArith(Op, DAG);
17048 }
17049
17050 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17051   if (Op.getValueType() == MVT::i1)
17052     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17053                        Op.getOperand(0), Op.getOperand(1));
17054   assert(Op.getSimpleValueType().is256BitVector() &&
17055          Op.getSimpleValueType().isInteger() &&
17056          "Only handle AVX 256-bit vector integer operation");
17057   return Lower256IntArith(Op, DAG);
17058 }
17059
17060 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17061   assert(Op.getSimpleValueType().is256BitVector() &&
17062          Op.getSimpleValueType().isInteger() &&
17063          "Only handle AVX 256-bit vector integer operation");
17064   return Lower256IntArith(Op, DAG);
17065 }
17066
17067 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17068                         SelectionDAG &DAG) {
17069   SDLoc dl(Op);
17070   MVT VT = Op.getSimpleValueType();
17071
17072   if (VT == MVT::i1)
17073     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17074
17075   // Decompose 256-bit ops into smaller 128-bit ops.
17076   if (VT.is256BitVector() && !Subtarget->hasInt256())
17077     return Lower256IntArith(Op, DAG);
17078
17079   SDValue A = Op.getOperand(0);
17080   SDValue B = Op.getOperand(1);
17081
17082   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17083   // pairs, multiply and truncate.
17084   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17085     if (Subtarget->hasInt256()) {
17086       if (VT == MVT::v32i8) {
17087         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17088         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17089         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17090         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17091         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17092         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17093         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17094         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17095                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17096                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17097       }
17098
17099       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17100       return DAG.getNode(
17101           ISD::TRUNCATE, dl, VT,
17102           DAG.getNode(ISD::MUL, dl, ExVT,
17103                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17104                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17105     }
17106
17107     assert(VT == MVT::v16i8 &&
17108            "Pre-AVX2 support only supports v16i8 multiplication");
17109     MVT ExVT = MVT::v8i16;
17110
17111     // Extract the lo parts and sign extend to i16
17112     SDValue ALo, BLo;
17113     if (Subtarget->hasSSE41()) {
17114       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17115       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17116     } else {
17117       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17118                               -1, 4, -1, 5, -1, 6, -1, 7};
17119       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17120       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17121       ALo = DAG.getBitcast(ExVT, ALo);
17122       BLo = DAG.getBitcast(ExVT, BLo);
17123       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17124       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17125     }
17126
17127     // Extract the hi parts and sign extend to i16
17128     SDValue AHi, BHi;
17129     if (Subtarget->hasSSE41()) {
17130       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17131                               -1, -1, -1, -1, -1, -1, -1, -1};
17132       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17133       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17134       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17135       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17136     } else {
17137       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17138                               -1, 12, -1, 13, -1, 14, -1, 15};
17139       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17140       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17141       AHi = DAG.getBitcast(ExVT, AHi);
17142       BHi = DAG.getBitcast(ExVT, BHi);
17143       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17144       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17145     }
17146
17147     // Multiply, mask the lower 8bits of the lo/hi results and pack
17148     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17149     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17150     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17151     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17152     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17153   }
17154
17155   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17156   if (VT == MVT::v4i32) {
17157     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17158            "Should not custom lower when pmuldq is available!");
17159
17160     // Extract the odd parts.
17161     static const int UnpackMask[] = { 1, -1, 3, -1 };
17162     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17163     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17164
17165     // Multiply the even parts.
17166     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17167     // Now multiply odd parts.
17168     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17169
17170     Evens = DAG.getBitcast(VT, Evens);
17171     Odds = DAG.getBitcast(VT, Odds);
17172
17173     // Merge the two vectors back together with a shuffle. This expands into 2
17174     // shuffles.
17175     static const int ShufMask[] = { 0, 4, 2, 6 };
17176     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17177   }
17178
17179   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17180          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17181
17182   //  Ahi = psrlqi(a, 32);
17183   //  Bhi = psrlqi(b, 32);
17184   //
17185   //  AloBlo = pmuludq(a, b);
17186   //  AloBhi = pmuludq(a, Bhi);
17187   //  AhiBlo = pmuludq(Ahi, b);
17188
17189   //  AloBhi = psllqi(AloBhi, 32);
17190   //  AhiBlo = psllqi(AhiBlo, 32);
17191   //  return AloBlo + AloBhi + AhiBlo;
17192
17193   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17194   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17195
17196   SDValue AhiBlo = Ahi;
17197   SDValue AloBhi = Bhi;
17198   // Bit cast to 32-bit vectors for MULUDQ
17199   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17200                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17201   A = DAG.getBitcast(MulVT, A);
17202   B = DAG.getBitcast(MulVT, B);
17203   Ahi = DAG.getBitcast(MulVT, Ahi);
17204   Bhi = DAG.getBitcast(MulVT, Bhi);
17205
17206   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17207   // After shifting right const values the result may be all-zero.
17208   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17209     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17210     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17211   }
17212   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17213     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17214     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17215   }
17216
17217   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17218   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17219 }
17220
17221 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17222   assert(Subtarget->isTargetWin64() && "Unexpected target");
17223   EVT VT = Op.getValueType();
17224   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17225          "Unexpected return type for lowering");
17226
17227   RTLIB::Libcall LC;
17228   bool isSigned;
17229   switch (Op->getOpcode()) {
17230   default: llvm_unreachable("Unexpected request for libcall!");
17231   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17232   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17233   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17234   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17235   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17236   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17237   }
17238
17239   SDLoc dl(Op);
17240   SDValue InChain = DAG.getEntryNode();
17241
17242   TargetLowering::ArgListTy Args;
17243   TargetLowering::ArgListEntry Entry;
17244   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17245     EVT ArgVT = Op->getOperand(i).getValueType();
17246     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17247            "Unexpected argument type for lowering");
17248     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17249     Entry.Node = StackPtr;
17250     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17251                            false, false, 16);
17252     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17253     Entry.Ty = PointerType::get(ArgTy,0);
17254     Entry.isSExt = false;
17255     Entry.isZExt = false;
17256     Args.push_back(Entry);
17257   }
17258
17259   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17260                                          getPointerTy(DAG.getDataLayout()));
17261
17262   TargetLowering::CallLoweringInfo CLI(DAG);
17263   CLI.setDebugLoc(dl).setChain(InChain)
17264     .setCallee(getLibcallCallingConv(LC),
17265                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17266                Callee, std::move(Args), 0)
17267     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17268
17269   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17270   return DAG.getBitcast(VT, CallInfo.first);
17271 }
17272
17273 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17274                              SelectionDAG &DAG) {
17275   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17276   EVT VT = Op0.getValueType();
17277   SDLoc dl(Op);
17278
17279   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17280          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17281
17282   // PMULxD operations multiply each even value (starting at 0) of LHS with
17283   // the related value of RHS and produce a widen result.
17284   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17285   // => <2 x i64> <ae|cg>
17286   //
17287   // In other word, to have all the results, we need to perform two PMULxD:
17288   // 1. one with the even values.
17289   // 2. one with the odd values.
17290   // To achieve #2, with need to place the odd values at an even position.
17291   //
17292   // Place the odd value at an even position (basically, shift all values 1
17293   // step to the left):
17294   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17295   // <a|b|c|d> => <b|undef|d|undef>
17296   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17297   // <e|f|g|h> => <f|undef|h|undef>
17298   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17299
17300   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17301   // ints.
17302   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17303   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17304   unsigned Opcode =
17305       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17306   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17307   // => <2 x i64> <ae|cg>
17308   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17309   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17310   // => <2 x i64> <bf|dh>
17311   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17312
17313   // Shuffle it back into the right order.
17314   SDValue Highs, Lows;
17315   if (VT == MVT::v8i32) {
17316     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17317     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17318     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17319     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17320   } else {
17321     const int HighMask[] = {1, 5, 3, 7};
17322     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17323     const int LowMask[] = {0, 4, 2, 6};
17324     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17325   }
17326
17327   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17328   // unsigned multiply.
17329   if (IsSigned && !Subtarget->hasSSE41()) {
17330     SDValue ShAmt = DAG.getConstant(
17331         31, dl,
17332         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17333     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17334                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17335     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17336                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17337
17338     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17339     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17340   }
17341
17342   // The first result of MUL_LOHI is actually the low value, followed by the
17343   // high value.
17344   SDValue Ops[] = {Lows, Highs};
17345   return DAG.getMergeValues(Ops, dl);
17346 }
17347
17348 // Return true if the required (according to Opcode) shift-imm form is natively
17349 // supported by the Subtarget
17350 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17351                                         unsigned Opcode) {
17352   if (VT.getScalarSizeInBits() < 16)
17353     return false;
17354
17355   if (VT.is512BitVector() &&
17356       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17357     return true;
17358
17359   bool LShift = VT.is128BitVector() ||
17360     (VT.is256BitVector() && Subtarget->hasInt256());
17361
17362   bool AShift = LShift && (Subtarget->hasVLX() ||
17363     (VT != MVT::v2i64 && VT != MVT::v4i64));
17364   return (Opcode == ISD::SRA) ? AShift : LShift;
17365 }
17366
17367 // The shift amount is a variable, but it is the same for all vector lanes.
17368 // These instructions are defined together with shift-immediate.
17369 static
17370 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17371                                       unsigned Opcode) {
17372   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17373 }
17374
17375 // Return true if the required (according to Opcode) variable-shift form is
17376 // natively supported by the Subtarget
17377 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17378                                     unsigned Opcode) {
17379
17380   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17381     return false;
17382
17383   // vXi16 supported only on AVX-512, BWI
17384   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17385     return false;
17386
17387   if (VT.is512BitVector() || Subtarget->hasVLX())
17388     return true;
17389
17390   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17391   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17392   return (Opcode == ISD::SRA) ? AShift : LShift;
17393 }
17394
17395 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17396                                          const X86Subtarget *Subtarget) {
17397   MVT VT = Op.getSimpleValueType();
17398   SDLoc dl(Op);
17399   SDValue R = Op.getOperand(0);
17400   SDValue Amt = Op.getOperand(1);
17401
17402   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17403     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17404
17405   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17406     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17407     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17408     SDValue Ex = DAG.getBitcast(ExVT, R);
17409
17410     if (ShiftAmt >= 32) {
17411       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17412       SDValue Upper =
17413           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17414       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17415                                                  ShiftAmt - 32, DAG);
17416       if (VT == MVT::v2i64)
17417         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17418       if (VT == MVT::v4i64)
17419         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17420                                   {9, 1, 11, 3, 13, 5, 15, 7});
17421     } else {
17422       // SRA upper i32, SHL whole i64 and select lower i32.
17423       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17424                                                  ShiftAmt, DAG);
17425       SDValue Lower =
17426           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17427       Lower = DAG.getBitcast(ExVT, Lower);
17428       if (VT == MVT::v2i64)
17429         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17430       if (VT == MVT::v4i64)
17431         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17432                                   {8, 1, 10, 3, 12, 5, 14, 7});
17433     }
17434     return DAG.getBitcast(VT, Ex);
17435   };
17436
17437   // Optimize shl/srl/sra with constant shift amount.
17438   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17439     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17440       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17441
17442       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17443         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17444
17445       // i64 SRA needs to be performed as partial shifts.
17446       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17447           Op.getOpcode() == ISD::SRA)
17448         return ArithmeticShiftRight64(ShiftAmt);
17449
17450       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17451         unsigned NumElts = VT.getVectorNumElements();
17452         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17453
17454         if (Op.getOpcode() == ISD::SHL) {
17455           // Simple i8 add case
17456           if (ShiftAmt == 1)
17457             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17458
17459           // Make a large shift.
17460           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17461                                                    R, ShiftAmt, DAG);
17462           SHL = DAG.getBitcast(VT, SHL);
17463           // Zero out the rightmost bits.
17464           SmallVector<SDValue, 32> V(
17465               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17466           return DAG.getNode(ISD::AND, dl, VT, SHL,
17467                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17468         }
17469         if (Op.getOpcode() == ISD::SRL) {
17470           // Make a large shift.
17471           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17472                                                    R, ShiftAmt, DAG);
17473           SRL = DAG.getBitcast(VT, SRL);
17474           // Zero out the leftmost bits.
17475           SmallVector<SDValue, 32> V(
17476               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17477           return DAG.getNode(ISD::AND, dl, VT, SRL,
17478                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17479         }
17480         if (Op.getOpcode() == ISD::SRA) {
17481           if (ShiftAmt == 7) {
17482             // ashr(R, 7)  === cmp_slt(R, 0)
17483             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17484             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17485           }
17486
17487           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17488           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17489           SmallVector<SDValue, 32> V(NumElts,
17490                                      DAG.getConstant(128 >> ShiftAmt, dl,
17491                                                      MVT::i8));
17492           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17493           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17494           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17495           return Res;
17496         }
17497         llvm_unreachable("Unknown shift opcode.");
17498       }
17499     }
17500   }
17501
17502   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17503   if (!Subtarget->is64Bit() &&
17504       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17505
17506     // Peek through any splat that was introduced for i64 shift vectorization.
17507     int SplatIndex = -1;
17508     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17509       if (SVN->isSplat()) {
17510         SplatIndex = SVN->getSplatIndex();
17511         Amt = Amt.getOperand(0);
17512         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17513                "Splat shuffle referencing second operand");
17514       }
17515
17516     if (Amt.getOpcode() != ISD::BITCAST ||
17517         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17518       return SDValue();
17519
17520     Amt = Amt.getOperand(0);
17521     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17522                      VT.getVectorNumElements();
17523     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17524     uint64_t ShiftAmt = 0;
17525     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17526     for (unsigned i = 0; i != Ratio; ++i) {
17527       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17528       if (!C)
17529         return SDValue();
17530       // 6 == Log2(64)
17531       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17532     }
17533
17534     // Check remaining shift amounts (if not a splat).
17535     if (SplatIndex < 0) {
17536       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17537         uint64_t ShAmt = 0;
17538         for (unsigned j = 0; j != Ratio; ++j) {
17539           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17540           if (!C)
17541             return SDValue();
17542           // 6 == Log2(64)
17543           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17544         }
17545         if (ShAmt != ShiftAmt)
17546           return SDValue();
17547       }
17548     }
17549
17550     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17551       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17552
17553     if (Op.getOpcode() == ISD::SRA)
17554       return ArithmeticShiftRight64(ShiftAmt);
17555   }
17556
17557   return SDValue();
17558 }
17559
17560 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17561                                         const X86Subtarget* Subtarget) {
17562   MVT VT = Op.getSimpleValueType();
17563   SDLoc dl(Op);
17564   SDValue R = Op.getOperand(0);
17565   SDValue Amt = Op.getOperand(1);
17566
17567   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17568     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17569
17570   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17571     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17572
17573   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17574     SDValue BaseShAmt;
17575     EVT EltVT = VT.getVectorElementType();
17576
17577     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17578       // Check if this build_vector node is doing a splat.
17579       // If so, then set BaseShAmt equal to the splat value.
17580       BaseShAmt = BV->getSplatValue();
17581       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17582         BaseShAmt = SDValue();
17583     } else {
17584       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17585         Amt = Amt.getOperand(0);
17586
17587       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17588       if (SVN && SVN->isSplat()) {
17589         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17590         SDValue InVec = Amt.getOperand(0);
17591         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17592           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17593                  "Unexpected shuffle index found!");
17594           BaseShAmt = InVec.getOperand(SplatIdx);
17595         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17596            if (ConstantSDNode *C =
17597                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17598              if (C->getZExtValue() == SplatIdx)
17599                BaseShAmt = InVec.getOperand(1);
17600            }
17601         }
17602
17603         if (!BaseShAmt)
17604           // Avoid introducing an extract element from a shuffle.
17605           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17606                                   DAG.getIntPtrConstant(SplatIdx, dl));
17607       }
17608     }
17609
17610     if (BaseShAmt.getNode()) {
17611       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17612       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17613         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17614       else if (EltVT.bitsLT(MVT::i32))
17615         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17616
17617       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17618     }
17619   }
17620
17621   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17622   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17623       Amt.getOpcode() == ISD::BITCAST &&
17624       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17625     Amt = Amt.getOperand(0);
17626     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17627                      VT.getVectorNumElements();
17628     std::vector<SDValue> Vals(Ratio);
17629     for (unsigned i = 0; i != Ratio; ++i)
17630       Vals[i] = Amt.getOperand(i);
17631     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17632       for (unsigned j = 0; j != Ratio; ++j)
17633         if (Vals[j] != Amt.getOperand(i + j))
17634           return SDValue();
17635     }
17636
17637     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17638       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17639   }
17640   return SDValue();
17641 }
17642
17643 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17644                           SelectionDAG &DAG) {
17645   MVT VT = Op.getSimpleValueType();
17646   SDLoc dl(Op);
17647   SDValue R = Op.getOperand(0);
17648   SDValue Amt = Op.getOperand(1);
17649
17650   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17651   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17652
17653   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17654     return V;
17655
17656   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17657       return V;
17658
17659   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17660     return Op;
17661
17662   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17663   // shifts per-lane and then shuffle the partial results back together.
17664   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17665     // Splat the shift amounts so the scalar shifts above will catch it.
17666     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17667     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17668     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17669     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17670     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17671   }
17672
17673   // i64 vector arithmetic shift can be emulated with the transform:
17674   // M = lshr(SIGN_BIT, Amt)
17675   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17676   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17677       Op.getOpcode() == ISD::SRA) {
17678     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17679     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17680     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17681     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17682     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17683     return R;
17684   }
17685
17686   // If possible, lower this packed shift into a vector multiply instead of
17687   // expanding it into a sequence of scalar shifts.
17688   // Do this only if the vector shift count is a constant build_vector.
17689   if (Op.getOpcode() == ISD::SHL &&
17690       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17691        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17692       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17693     SmallVector<SDValue, 8> Elts;
17694     EVT SVT = VT.getScalarType();
17695     unsigned SVTBits = SVT.getSizeInBits();
17696     const APInt &One = APInt(SVTBits, 1);
17697     unsigned NumElems = VT.getVectorNumElements();
17698
17699     for (unsigned i=0; i !=NumElems; ++i) {
17700       SDValue Op = Amt->getOperand(i);
17701       if (Op->getOpcode() == ISD::UNDEF) {
17702         Elts.push_back(Op);
17703         continue;
17704       }
17705
17706       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17707       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17708       uint64_t ShAmt = C.getZExtValue();
17709       if (ShAmt >= SVTBits) {
17710         Elts.push_back(DAG.getUNDEF(SVT));
17711         continue;
17712       }
17713       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17714     }
17715     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17716     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17717   }
17718
17719   // Lower SHL with variable shift amount.
17720   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17721     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17722
17723     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17724                      DAG.getConstant(0x3f800000U, dl, VT));
17725     Op = DAG.getBitcast(MVT::v4f32, Op);
17726     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17727     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17728   }
17729
17730   // If possible, lower this shift as a sequence of two shifts by
17731   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17732   // Example:
17733   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17734   //
17735   // Could be rewritten as:
17736   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17737   //
17738   // The advantage is that the two shifts from the example would be
17739   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17740   // the vector shift into four scalar shifts plus four pairs of vector
17741   // insert/extract.
17742   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17743       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17744     unsigned TargetOpcode = X86ISD::MOVSS;
17745     bool CanBeSimplified;
17746     // The splat value for the first packed shift (the 'X' from the example).
17747     SDValue Amt1 = Amt->getOperand(0);
17748     // The splat value for the second packed shift (the 'Y' from the example).
17749     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17750                                         Amt->getOperand(2);
17751
17752     // See if it is possible to replace this node with a sequence of
17753     // two shifts followed by a MOVSS/MOVSD
17754     if (VT == MVT::v4i32) {
17755       // Check if it is legal to use a MOVSS.
17756       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17757                         Amt2 == Amt->getOperand(3);
17758       if (!CanBeSimplified) {
17759         // Otherwise, check if we can still simplify this node using a MOVSD.
17760         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17761                           Amt->getOperand(2) == Amt->getOperand(3);
17762         TargetOpcode = X86ISD::MOVSD;
17763         Amt2 = Amt->getOperand(2);
17764       }
17765     } else {
17766       // Do similar checks for the case where the machine value type
17767       // is MVT::v8i16.
17768       CanBeSimplified = Amt1 == Amt->getOperand(1);
17769       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17770         CanBeSimplified = Amt2 == Amt->getOperand(i);
17771
17772       if (!CanBeSimplified) {
17773         TargetOpcode = X86ISD::MOVSD;
17774         CanBeSimplified = true;
17775         Amt2 = Amt->getOperand(4);
17776         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17777           CanBeSimplified = Amt1 == Amt->getOperand(i);
17778         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17779           CanBeSimplified = Amt2 == Amt->getOperand(j);
17780       }
17781     }
17782
17783     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17784         isa<ConstantSDNode>(Amt2)) {
17785       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17786       EVT CastVT = MVT::v4i32;
17787       SDValue Splat1 =
17788         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17789       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17790       SDValue Splat2 =
17791         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17792       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17793       if (TargetOpcode == X86ISD::MOVSD)
17794         CastVT = MVT::v2i64;
17795       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17796       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17797       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17798                                             BitCast1, DAG);
17799       return DAG.getBitcast(VT, Result);
17800     }
17801   }
17802
17803   // v4i32 Non Uniform Shifts.
17804   // If the shift amount is constant we can shift each lane using the SSE2
17805   // immediate shifts, else we need to zero-extend each lane to the lower i64
17806   // and shift using the SSE2 variable shifts.
17807   // The separate results can then be blended together.
17808   if (VT == MVT::v4i32) {
17809     unsigned Opc = Op.getOpcode();
17810     SDValue Amt0, Amt1, Amt2, Amt3;
17811     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17812       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17813       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17814       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17815       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17816     } else {
17817       // ISD::SHL is handled above but we include it here for completeness.
17818       switch (Opc) {
17819       default:
17820         llvm_unreachable("Unknown target vector shift node");
17821       case ISD::SHL:
17822         Opc = X86ISD::VSHL;
17823         break;
17824       case ISD::SRL:
17825         Opc = X86ISD::VSRL;
17826         break;
17827       case ISD::SRA:
17828         Opc = X86ISD::VSRA;
17829         break;
17830       }
17831       // The SSE2 shifts use the lower i64 as the same shift amount for
17832       // all lanes and the upper i64 is ignored. These shuffle masks
17833       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17834       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17835       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17836       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17837       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17838       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17839     }
17840
17841     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17842     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17843     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17844     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17845     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17846     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17847     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17848   }
17849
17850   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17851     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17852     unsigned ShiftOpcode = Op->getOpcode();
17853
17854     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17855       // On SSE41 targets we make use of the fact that VSELECT lowers
17856       // to PBLENDVB which selects bytes based just on the sign bit.
17857       if (Subtarget->hasSSE41()) {
17858         V0 = DAG.getBitcast(VT, V0);
17859         V1 = DAG.getBitcast(VT, V1);
17860         Sel = DAG.getBitcast(VT, Sel);
17861         return DAG.getBitcast(SelVT,
17862                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17863       }
17864       // On pre-SSE41 targets we test for the sign bit by comparing to
17865       // zero - a negative value will set all bits of the lanes to true
17866       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17867       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17868       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17869       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17870     };
17871
17872     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17873     // We can safely do this using i16 shifts as we're only interested in
17874     // the 3 lower bits of each byte.
17875     Amt = DAG.getBitcast(ExtVT, Amt);
17876     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17877     Amt = DAG.getBitcast(VT, Amt);
17878
17879     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17880       // r = VSELECT(r, shift(r, 4), a);
17881       SDValue M =
17882           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17883       R = SignBitSelect(VT, Amt, M, R);
17884
17885       // a += a
17886       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17887
17888       // r = VSELECT(r, shift(r, 2), a);
17889       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17890       R = SignBitSelect(VT, Amt, M, R);
17891
17892       // a += a
17893       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17894
17895       // return VSELECT(r, shift(r, 1), a);
17896       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17897       R = SignBitSelect(VT, Amt, M, R);
17898       return R;
17899     }
17900
17901     if (Op->getOpcode() == ISD::SRA) {
17902       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17903       // so we can correctly sign extend. We don't care what happens to the
17904       // lower byte.
17905       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17906       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17907       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17908       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17909       ALo = DAG.getBitcast(ExtVT, ALo);
17910       AHi = DAG.getBitcast(ExtVT, AHi);
17911       RLo = DAG.getBitcast(ExtVT, RLo);
17912       RHi = DAG.getBitcast(ExtVT, RHi);
17913
17914       // r = VSELECT(r, shift(r, 4), a);
17915       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17916                                 DAG.getConstant(4, dl, ExtVT));
17917       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17918                                 DAG.getConstant(4, dl, ExtVT));
17919       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17920       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17921
17922       // a += a
17923       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17924       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17925
17926       // r = VSELECT(r, shift(r, 2), a);
17927       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17928                         DAG.getConstant(2, dl, ExtVT));
17929       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17930                         DAG.getConstant(2, dl, ExtVT));
17931       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17932       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17933
17934       // a += a
17935       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17936       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17937
17938       // r = VSELECT(r, shift(r, 1), a);
17939       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17940                         DAG.getConstant(1, dl, ExtVT));
17941       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17942                         DAG.getConstant(1, dl, ExtVT));
17943       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17944       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17945
17946       // Logical shift the result back to the lower byte, leaving a zero upper
17947       // byte
17948       // meaning that we can safely pack with PACKUSWB.
17949       RLo =
17950           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17951       RHi =
17952           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17953       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17954     }
17955   }
17956
17957   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17958   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17959   // solution better.
17960   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17961     MVT ExtVT = MVT::v8i32;
17962     unsigned ExtOpc =
17963         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17964     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17965     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17966     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17967                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17968   }
17969
17970   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17971     MVT ExtVT = MVT::v8i32;
17972     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17973     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17974     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17975     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17976     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17977     ALo = DAG.getBitcast(ExtVT, ALo);
17978     AHi = DAG.getBitcast(ExtVT, AHi);
17979     RLo = DAG.getBitcast(ExtVT, RLo);
17980     RHi = DAG.getBitcast(ExtVT, RHi);
17981     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17982     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17983     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17984     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17985     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17986   }
17987
17988   if (VT == MVT::v8i16) {
17989     unsigned ShiftOpcode = Op->getOpcode();
17990
17991     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17992       // On SSE41 targets we make use of the fact that VSELECT lowers
17993       // to PBLENDVB which selects bytes based just on the sign bit.
17994       if (Subtarget->hasSSE41()) {
17995         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17996         V0 = DAG.getBitcast(ExtVT, V0);
17997         V1 = DAG.getBitcast(ExtVT, V1);
17998         Sel = DAG.getBitcast(ExtVT, Sel);
17999         return DAG.getBitcast(
18000             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18001       }
18002       // On pre-SSE41 targets we splat the sign bit - a negative value will
18003       // set all bits of the lanes to true and VSELECT uses that in
18004       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18005       SDValue C =
18006           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18007       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18008     };
18009
18010     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18011     if (Subtarget->hasSSE41()) {
18012       // On SSE41 targets we need to replicate the shift mask in both
18013       // bytes for PBLENDVB.
18014       Amt = DAG.getNode(
18015           ISD::OR, dl, VT,
18016           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18017           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18018     } else {
18019       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18020     }
18021
18022     // r = VSELECT(r, shift(r, 8), a);
18023     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18024     R = SignBitSelect(Amt, M, R);
18025
18026     // a += a
18027     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18028
18029     // r = VSELECT(r, shift(r, 4), a);
18030     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18031     R = SignBitSelect(Amt, M, R);
18032
18033     // a += a
18034     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18035
18036     // r = VSELECT(r, shift(r, 2), a);
18037     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18038     R = SignBitSelect(Amt, M, R);
18039
18040     // a += a
18041     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18042
18043     // return VSELECT(r, shift(r, 1), a);
18044     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18045     R = SignBitSelect(Amt, M, R);
18046     return R;
18047   }
18048
18049   // Decompose 256-bit shifts into smaller 128-bit shifts.
18050   if (VT.is256BitVector()) {
18051     unsigned NumElems = VT.getVectorNumElements();
18052     MVT EltVT = VT.getVectorElementType();
18053     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18054
18055     // Extract the two vectors
18056     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18057     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18058
18059     // Recreate the shift amount vectors
18060     SDValue Amt1, Amt2;
18061     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18062       // Constant shift amount
18063       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18064       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18065       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18066
18067       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18068       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18069     } else {
18070       // Variable shift amount
18071       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18072       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18073     }
18074
18075     // Issue new vector shifts for the smaller types
18076     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18077     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18078
18079     // Concatenate the result back
18080     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18081   }
18082
18083   return SDValue();
18084 }
18085
18086 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18087   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18088   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18089   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18090   // has only one use.
18091   SDNode *N = Op.getNode();
18092   SDValue LHS = N->getOperand(0);
18093   SDValue RHS = N->getOperand(1);
18094   unsigned BaseOp = 0;
18095   unsigned Cond = 0;
18096   SDLoc DL(Op);
18097   switch (Op.getOpcode()) {
18098   default: llvm_unreachable("Unknown ovf instruction!");
18099   case ISD::SADDO:
18100     // A subtract of one will be selected as a INC. Note that INC doesn't
18101     // set CF, so we can't do this for UADDO.
18102     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18103       if (C->isOne()) {
18104         BaseOp = X86ISD::INC;
18105         Cond = X86::COND_O;
18106         break;
18107       }
18108     BaseOp = X86ISD::ADD;
18109     Cond = X86::COND_O;
18110     break;
18111   case ISD::UADDO:
18112     BaseOp = X86ISD::ADD;
18113     Cond = X86::COND_B;
18114     break;
18115   case ISD::SSUBO:
18116     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18117     // set CF, so we can't do this for USUBO.
18118     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18119       if (C->isOne()) {
18120         BaseOp = X86ISD::DEC;
18121         Cond = X86::COND_O;
18122         break;
18123       }
18124     BaseOp = X86ISD::SUB;
18125     Cond = X86::COND_O;
18126     break;
18127   case ISD::USUBO:
18128     BaseOp = X86ISD::SUB;
18129     Cond = X86::COND_B;
18130     break;
18131   case ISD::SMULO:
18132     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18133     Cond = X86::COND_O;
18134     break;
18135   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18136     if (N->getValueType(0) == MVT::i8) {
18137       BaseOp = X86ISD::UMUL8;
18138       Cond = X86::COND_O;
18139       break;
18140     }
18141     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18142                                  MVT::i32);
18143     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18144
18145     SDValue SetCC =
18146       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18147                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18148                   SDValue(Sum.getNode(), 2));
18149
18150     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18151   }
18152   }
18153
18154   // Also sets EFLAGS.
18155   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18156   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18157
18158   SDValue SetCC =
18159     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18160                 DAG.getConstant(Cond, DL, MVT::i32),
18161                 SDValue(Sum.getNode(), 1));
18162
18163   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18164 }
18165
18166 /// Returns true if the operand type is exactly twice the native width, and
18167 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18168 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18169 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18170 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18171   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18172
18173   if (OpWidth == 64)
18174     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18175   else if (OpWidth == 128)
18176     return Subtarget->hasCmpxchg16b();
18177   else
18178     return false;
18179 }
18180
18181 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18182   return needsCmpXchgNb(SI->getValueOperand()->getType());
18183 }
18184
18185 // Note: this turns large loads into lock cmpxchg8b/16b.
18186 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18187 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18188   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18189   return needsCmpXchgNb(PTy->getElementType());
18190 }
18191
18192 TargetLoweringBase::AtomicRMWExpansionKind
18193 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18194   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18195   Type *MemType = AI->getType();
18196
18197   // If the operand is too big, we must see if cmpxchg8/16b is available
18198   // and default to library calls otherwise.
18199   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18200     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18201                                    : AtomicRMWExpansionKind::None;
18202   }
18203
18204   AtomicRMWInst::BinOp Op = AI->getOperation();
18205   switch (Op) {
18206   default:
18207     llvm_unreachable("Unknown atomic operation");
18208   case AtomicRMWInst::Xchg:
18209   case AtomicRMWInst::Add:
18210   case AtomicRMWInst::Sub:
18211     // It's better to use xadd, xsub or xchg for these in all cases.
18212     return AtomicRMWExpansionKind::None;
18213   case AtomicRMWInst::Or:
18214   case AtomicRMWInst::And:
18215   case AtomicRMWInst::Xor:
18216     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18217     // prefix to a normal instruction for these operations.
18218     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18219                             : AtomicRMWExpansionKind::None;
18220   case AtomicRMWInst::Nand:
18221   case AtomicRMWInst::Max:
18222   case AtomicRMWInst::Min:
18223   case AtomicRMWInst::UMax:
18224   case AtomicRMWInst::UMin:
18225     // These always require a non-trivial set of data operations on x86. We must
18226     // use a cmpxchg loop.
18227     return AtomicRMWExpansionKind::CmpXChg;
18228   }
18229 }
18230
18231 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18232   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18233   // no-sse2). There isn't any reason to disable it if the target processor
18234   // supports it.
18235   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18236 }
18237
18238 LoadInst *
18239 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18240   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18241   Type *MemType = AI->getType();
18242   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18243   // there is no benefit in turning such RMWs into loads, and it is actually
18244   // harmful as it introduces a mfence.
18245   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18246     return nullptr;
18247
18248   auto Builder = IRBuilder<>(AI);
18249   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18250   auto SynchScope = AI->getSynchScope();
18251   // We must restrict the ordering to avoid generating loads with Release or
18252   // ReleaseAcquire orderings.
18253   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18254   auto Ptr = AI->getPointerOperand();
18255
18256   // Before the load we need a fence. Here is an example lifted from
18257   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18258   // is required:
18259   // Thread 0:
18260   //   x.store(1, relaxed);
18261   //   r1 = y.fetch_add(0, release);
18262   // Thread 1:
18263   //   y.fetch_add(42, acquire);
18264   //   r2 = x.load(relaxed);
18265   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18266   // lowered to just a load without a fence. A mfence flushes the store buffer,
18267   // making the optimization clearly correct.
18268   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18269   // otherwise, we might be able to be more aggressive on relaxed idempotent
18270   // rmw. In practice, they do not look useful, so we don't try to be
18271   // especially clever.
18272   if (SynchScope == SingleThread)
18273     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18274     // the IR level, so we must wrap it in an intrinsic.
18275     return nullptr;
18276
18277   if (!hasMFENCE(*Subtarget))
18278     // FIXME: it might make sense to use a locked operation here but on a
18279     // different cache-line to prevent cache-line bouncing. In practice it
18280     // is probably a small win, and x86 processors without mfence are rare
18281     // enough that we do not bother.
18282     return nullptr;
18283
18284   Function *MFence =
18285       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18286   Builder.CreateCall(MFence, {});
18287
18288   // Finally we can emit the atomic load.
18289   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18290           AI->getType()->getPrimitiveSizeInBits());
18291   Loaded->setAtomic(Order, SynchScope);
18292   AI->replaceAllUsesWith(Loaded);
18293   AI->eraseFromParent();
18294   return Loaded;
18295 }
18296
18297 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18298                                  SelectionDAG &DAG) {
18299   SDLoc dl(Op);
18300   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18301     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18302   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18303     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18304
18305   // The only fence that needs an instruction is a sequentially-consistent
18306   // cross-thread fence.
18307   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18308     if (hasMFENCE(*Subtarget))
18309       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18310
18311     SDValue Chain = Op.getOperand(0);
18312     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18313     SDValue Ops[] = {
18314       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18315       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18316       DAG.getRegister(0, MVT::i32),            // Index
18317       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18318       DAG.getRegister(0, MVT::i32),            // Segment.
18319       Zero,
18320       Chain
18321     };
18322     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18323     return SDValue(Res, 0);
18324   }
18325
18326   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18327   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18328 }
18329
18330 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18331                              SelectionDAG &DAG) {
18332   MVT T = Op.getSimpleValueType();
18333   SDLoc DL(Op);
18334   unsigned Reg = 0;
18335   unsigned size = 0;
18336   switch(T.SimpleTy) {
18337   default: llvm_unreachable("Invalid value type!");
18338   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18339   case MVT::i16: Reg = X86::AX;  size = 2; break;
18340   case MVT::i32: Reg = X86::EAX; size = 4; break;
18341   case MVT::i64:
18342     assert(Subtarget->is64Bit() && "Node not type legal!");
18343     Reg = X86::RAX; size = 8;
18344     break;
18345   }
18346   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18347                                   Op.getOperand(2), SDValue());
18348   SDValue Ops[] = { cpIn.getValue(0),
18349                     Op.getOperand(1),
18350                     Op.getOperand(3),
18351                     DAG.getTargetConstant(size, DL, MVT::i8),
18352                     cpIn.getValue(1) };
18353   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18354   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18355   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18356                                            Ops, T, MMO);
18357
18358   SDValue cpOut =
18359     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18360   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18361                                       MVT::i32, cpOut.getValue(2));
18362   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18363                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18364                                 EFLAGS);
18365
18366   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18367   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18368   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18369   return SDValue();
18370 }
18371
18372 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18373                             SelectionDAG &DAG) {
18374   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18375   MVT DstVT = Op.getSimpleValueType();
18376
18377   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18378     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18379     if (DstVT != MVT::f64)
18380       // This conversion needs to be expanded.
18381       return SDValue();
18382
18383     SDValue InVec = Op->getOperand(0);
18384     SDLoc dl(Op);
18385     unsigned NumElts = SrcVT.getVectorNumElements();
18386     EVT SVT = SrcVT.getVectorElementType();
18387
18388     // Widen the vector in input in the case of MVT::v2i32.
18389     // Example: from MVT::v2i32 to MVT::v4i32.
18390     SmallVector<SDValue, 16> Elts;
18391     for (unsigned i = 0, e = NumElts; i != e; ++i)
18392       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18393                                  DAG.getIntPtrConstant(i, dl)));
18394
18395     // Explicitly mark the extra elements as Undef.
18396     Elts.append(NumElts, DAG.getUNDEF(SVT));
18397
18398     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18399     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18400     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18401     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18402                        DAG.getIntPtrConstant(0, dl));
18403   }
18404
18405   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18406          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18407   assert((DstVT == MVT::i64 ||
18408           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18409          "Unexpected custom BITCAST");
18410   // i64 <=> MMX conversions are Legal.
18411   if (SrcVT==MVT::i64 && DstVT.isVector())
18412     return Op;
18413   if (DstVT==MVT::i64 && SrcVT.isVector())
18414     return Op;
18415   // MMX <=> MMX conversions are Legal.
18416   if (SrcVT.isVector() && DstVT.isVector())
18417     return Op;
18418   // All other conversions need to be expanded.
18419   return SDValue();
18420 }
18421
18422 /// Compute the horizontal sum of bytes in V for the elements of VT.
18423 ///
18424 /// Requires V to be a byte vector and VT to be an integer vector type with
18425 /// wider elements than V's type. The width of the elements of VT determines
18426 /// how many bytes of V are summed horizontally to produce each element of the
18427 /// result.
18428 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18429                                       const X86Subtarget *Subtarget,
18430                                       SelectionDAG &DAG) {
18431   SDLoc DL(V);
18432   MVT ByteVecVT = V.getSimpleValueType();
18433   MVT EltVT = VT.getVectorElementType();
18434   int NumElts = VT.getVectorNumElements();
18435   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18436          "Expected value to have byte element type.");
18437   assert(EltVT != MVT::i8 &&
18438          "Horizontal byte sum only makes sense for wider elements!");
18439   unsigned VecSize = VT.getSizeInBits();
18440   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18441
18442   // PSADBW instruction horizontally add all bytes and leave the result in i64
18443   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18444   if (EltVT == MVT::i64) {
18445     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18446     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18447     return DAG.getBitcast(VT, V);
18448   }
18449
18450   if (EltVT == MVT::i32) {
18451     // We unpack the low half and high half into i32s interleaved with zeros so
18452     // that we can use PSADBW to horizontally sum them. The most useful part of
18453     // this is that it lines up the results of two PSADBW instructions to be
18454     // two v2i64 vectors which concatenated are the 4 population counts. We can
18455     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18456     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18457     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18458     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18459
18460     // Do the horizontal sums into two v2i64s.
18461     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18462     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18463                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18464     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18465                        DAG.getBitcast(ByteVecVT, High), Zeros);
18466
18467     // Merge them together.
18468     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18469     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18470                     DAG.getBitcast(ShortVecVT, Low),
18471                     DAG.getBitcast(ShortVecVT, High));
18472
18473     return DAG.getBitcast(VT, V);
18474   }
18475
18476   // The only element type left is i16.
18477   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18478
18479   // To obtain pop count for each i16 element starting from the pop count for
18480   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18481   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18482   // directly supported.
18483   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18484   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18485   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18486   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18487                   DAG.getBitcast(ByteVecVT, V));
18488   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18489 }
18490
18491 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18492                                         const X86Subtarget *Subtarget,
18493                                         SelectionDAG &DAG) {
18494   MVT VT = Op.getSimpleValueType();
18495   MVT EltVT = VT.getVectorElementType();
18496   unsigned VecSize = VT.getSizeInBits();
18497
18498   // Implement a lookup table in register by using an algorithm based on:
18499   // http://wm.ite.pl/articles/sse-popcount.html
18500   //
18501   // The general idea is that every lower byte nibble in the input vector is an
18502   // index into a in-register pre-computed pop count table. We then split up the
18503   // input vector in two new ones: (1) a vector with only the shifted-right
18504   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18505   // masked out higher ones) for each byte. PSHUB is used separately with both
18506   // to index the in-register table. Next, both are added and the result is a
18507   // i8 vector where each element contains the pop count for input byte.
18508   //
18509   // To obtain the pop count for elements != i8, we follow up with the same
18510   // approach and use additional tricks as described below.
18511   //
18512   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18513                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18514                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18515                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18516
18517   int NumByteElts = VecSize / 8;
18518   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18519   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18520   SmallVector<SDValue, 16> LUTVec;
18521   for (int i = 0; i < NumByteElts; ++i)
18522     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18523   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18524   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18525                                   DAG.getConstant(0x0F, DL, MVT::i8));
18526   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18527
18528   // High nibbles
18529   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18530   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18531   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18532
18533   // Low nibbles
18534   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18535
18536   // The input vector is used as the shuffle mask that index elements into the
18537   // LUT. After counting low and high nibbles, add the vector to obtain the
18538   // final pop count per i8 element.
18539   SDValue HighPopCnt =
18540       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18541   SDValue LowPopCnt =
18542       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18543   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18544
18545   if (EltVT == MVT::i8)
18546     return PopCnt;
18547
18548   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18549 }
18550
18551 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18552                                        const X86Subtarget *Subtarget,
18553                                        SelectionDAG &DAG) {
18554   MVT VT = Op.getSimpleValueType();
18555   assert(VT.is128BitVector() &&
18556          "Only 128-bit vector bitmath lowering supported.");
18557
18558   int VecSize = VT.getSizeInBits();
18559   MVT EltVT = VT.getVectorElementType();
18560   int Len = EltVT.getSizeInBits();
18561
18562   // This is the vectorized version of the "best" algorithm from
18563   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18564   // with a minor tweak to use a series of adds + shifts instead of vector
18565   // multiplications. Implemented for all integer vector types. We only use
18566   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18567   // much faster, even faster than using native popcnt instructions.
18568
18569   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18570     MVT VT = V.getSimpleValueType();
18571     SmallVector<SDValue, 32> Shifters(
18572         VT.getVectorNumElements(),
18573         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18574     return DAG.getNode(OpCode, DL, VT, V,
18575                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18576   };
18577   auto GetMask = [&](SDValue V, APInt Mask) {
18578     MVT VT = V.getSimpleValueType();
18579     SmallVector<SDValue, 32> Masks(
18580         VT.getVectorNumElements(),
18581         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18582     return DAG.getNode(ISD::AND, DL, VT, V,
18583                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18584   };
18585
18586   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18587   // x86, so set the SRL type to have elements at least i16 wide. This is
18588   // correct because all of our SRLs are followed immediately by a mask anyways
18589   // that handles any bits that sneak into the high bits of the byte elements.
18590   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18591
18592   SDValue V = Op;
18593
18594   // v = v - ((v >> 1) & 0x55555555...)
18595   SDValue Srl =
18596       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18597   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18598   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18599
18600   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18601   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18602   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18603   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18604   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18605
18606   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18607   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18608   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18609   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18610
18611   // At this point, V contains the byte-wise population count, and we are
18612   // merely doing a horizontal sum if necessary to get the wider element
18613   // counts.
18614   if (EltVT == MVT::i8)
18615     return V;
18616
18617   return LowerHorizontalByteSum(
18618       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18619       DAG);
18620 }
18621
18622 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18623                                 SelectionDAG &DAG) {
18624   MVT VT = Op.getSimpleValueType();
18625   // FIXME: Need to add AVX-512 support here!
18626   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18627          "Unknown CTPOP type to handle");
18628   SDLoc DL(Op.getNode());
18629   SDValue Op0 = Op.getOperand(0);
18630
18631   if (!Subtarget->hasSSSE3()) {
18632     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18633     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18634     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18635   }
18636
18637   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18638     unsigned NumElems = VT.getVectorNumElements();
18639
18640     // Extract each 128-bit vector, compute pop count and concat the result.
18641     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18642     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18643
18644     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18645                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18646                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18647   }
18648
18649   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18650 }
18651
18652 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18653                           SelectionDAG &DAG) {
18654   assert(Op.getValueType().isVector() &&
18655          "We only do custom lowering for vector population count.");
18656   return LowerVectorCTPOP(Op, Subtarget, DAG);
18657 }
18658
18659 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18660   SDNode *Node = Op.getNode();
18661   SDLoc dl(Node);
18662   EVT T = Node->getValueType(0);
18663   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18664                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18665   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18666                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18667                        Node->getOperand(0),
18668                        Node->getOperand(1), negOp,
18669                        cast<AtomicSDNode>(Node)->getMemOperand(),
18670                        cast<AtomicSDNode>(Node)->getOrdering(),
18671                        cast<AtomicSDNode>(Node)->getSynchScope());
18672 }
18673
18674 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18675   SDNode *Node = Op.getNode();
18676   SDLoc dl(Node);
18677   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18678
18679   // Convert seq_cst store -> xchg
18680   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18681   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18682   //        (The only way to get a 16-byte store is cmpxchg16b)
18683   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18684   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18685       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18686     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18687                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18688                                  Node->getOperand(0),
18689                                  Node->getOperand(1), Node->getOperand(2),
18690                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18691                                  cast<AtomicSDNode>(Node)->getOrdering(),
18692                                  cast<AtomicSDNode>(Node)->getSynchScope());
18693     return Swap.getValue(1);
18694   }
18695   // Other atomic stores have a simple pattern.
18696   return Op;
18697 }
18698
18699 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18700   EVT VT = Op.getNode()->getSimpleValueType(0);
18701
18702   // Let legalize expand this if it isn't a legal type yet.
18703   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18704     return SDValue();
18705
18706   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18707
18708   unsigned Opc;
18709   bool ExtraOp = false;
18710   switch (Op.getOpcode()) {
18711   default: llvm_unreachable("Invalid code");
18712   case ISD::ADDC: Opc = X86ISD::ADD; break;
18713   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18714   case ISD::SUBC: Opc = X86ISD::SUB; break;
18715   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18716   }
18717
18718   if (!ExtraOp)
18719     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18720                        Op.getOperand(1));
18721   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18722                      Op.getOperand(1), Op.getOperand(2));
18723 }
18724
18725 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18726                             SelectionDAG &DAG) {
18727   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18728
18729   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18730   // which returns the values as { float, float } (in XMM0) or
18731   // { double, double } (which is returned in XMM0, XMM1).
18732   SDLoc dl(Op);
18733   SDValue Arg = Op.getOperand(0);
18734   EVT ArgVT = Arg.getValueType();
18735   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18736
18737   TargetLowering::ArgListTy Args;
18738   TargetLowering::ArgListEntry Entry;
18739
18740   Entry.Node = Arg;
18741   Entry.Ty = ArgTy;
18742   Entry.isSExt = false;
18743   Entry.isZExt = false;
18744   Args.push_back(Entry);
18745
18746   bool isF64 = ArgVT == MVT::f64;
18747   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18748   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18749   // the results are returned via SRet in memory.
18750   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18752   SDValue Callee =
18753       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18754
18755   Type *RetTy = isF64
18756     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18757     : (Type*)VectorType::get(ArgTy, 4);
18758
18759   TargetLowering::CallLoweringInfo CLI(DAG);
18760   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18761     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18762
18763   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18764
18765   if (isF64)
18766     // Returned in xmm0 and xmm1.
18767     return CallResult.first;
18768
18769   // Returned in bits 0:31 and 32:64 xmm0.
18770   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18771                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18772   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18773                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18774   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18775   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18776 }
18777
18778 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18779                              SelectionDAG &DAG) {
18780   assert(Subtarget->hasAVX512() &&
18781          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18782
18783   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18784   EVT VT = N->getValue().getValueType();
18785   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18786   SDLoc dl(Op);
18787
18788   // X86 scatter kills mask register, so its type should be added to
18789   // the list of return values
18790   if (N->getNumValues() == 1) {
18791     SDValue Index = N->getIndex();
18792     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18793         !Index.getValueType().is512BitVector())
18794       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18795
18796     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18797     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18798                       N->getOperand(3), Index };
18799
18800     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18801     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18802     return SDValue(NewScatter.getNode(), 0);
18803   }
18804   return Op;
18805 }
18806
18807 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18808                             SelectionDAG &DAG) {
18809   assert(Subtarget->hasAVX512() &&
18810          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18811
18812   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18813   EVT VT = Op.getValueType();
18814   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18815   SDLoc dl(Op);
18816
18817   SDValue Index = N->getIndex();
18818   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18819       !Index.getValueType().is512BitVector()) {
18820     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18821     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18822                       N->getOperand(3), Index };
18823     DAG.UpdateNodeOperands(N, Ops);
18824   }
18825   return Op;
18826 }
18827
18828 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18829                                                     SelectionDAG &DAG) const {
18830   // TODO: Eventually, the lowering of these nodes should be informed by or
18831   // deferred to the GC strategy for the function in which they appear. For
18832   // now, however, they must be lowered to something. Since they are logically
18833   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18834   // require special handling for these nodes), lower them as literal NOOPs for
18835   // the time being.
18836   SmallVector<SDValue, 2> Ops;
18837
18838   Ops.push_back(Op.getOperand(0));
18839   if (Op->getGluedNode())
18840     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18841
18842   SDLoc OpDL(Op);
18843   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18844   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18845
18846   return NOOP;
18847 }
18848
18849 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18850                                                   SelectionDAG &DAG) const {
18851   // TODO: Eventually, the lowering of these nodes should be informed by or
18852   // deferred to the GC strategy for the function in which they appear. For
18853   // now, however, they must be lowered to something. Since they are logically
18854   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18855   // require special handling for these nodes), lower them as literal NOOPs for
18856   // the time being.
18857   SmallVector<SDValue, 2> Ops;
18858
18859   Ops.push_back(Op.getOperand(0));
18860   if (Op->getGluedNode())
18861     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18862
18863   SDLoc OpDL(Op);
18864   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18865   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18866
18867   return NOOP;
18868 }
18869
18870 /// LowerOperation - Provide custom lowering hooks for some operations.
18871 ///
18872 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18873   switch (Op.getOpcode()) {
18874   default: llvm_unreachable("Should not custom lower this!");
18875   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18876   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18877     return LowerCMP_SWAP(Op, Subtarget, DAG);
18878   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18879   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18880   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18881   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18882   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18883   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18884   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18885   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18886   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18887   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18888   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18889   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18890   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18891   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18892   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18893   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18894   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18895   case ISD::SHL_PARTS:
18896   case ISD::SRA_PARTS:
18897   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18898   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18899   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18900   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18901   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18902   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18903   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18904   case ISD::SIGN_EXTEND_VECTOR_INREG:
18905     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18906   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18907   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18908   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18909   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18910   case ISD::FABS:
18911   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18912   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18913   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18914   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18915   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18916   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18917   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18918   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18919   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18920   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18921   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18922   case ISD::INTRINSIC_VOID:
18923   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18924   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18925   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18926   case ISD::FRAME_TO_ARGS_OFFSET:
18927                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18928   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18929   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18930   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
18931   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18932   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18933   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18934   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18935   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18936   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18937   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18938   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18939   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18940   case ISD::UMUL_LOHI:
18941   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18942   case ISD::SRA:
18943   case ISD::SRL:
18944   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18945   case ISD::SADDO:
18946   case ISD::UADDO:
18947   case ISD::SSUBO:
18948   case ISD::USUBO:
18949   case ISD::SMULO:
18950   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18951   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18952   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18953   case ISD::ADDC:
18954   case ISD::ADDE:
18955   case ISD::SUBC:
18956   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18957   case ISD::ADD:                return LowerADD(Op, DAG);
18958   case ISD::SUB:                return LowerSUB(Op, DAG);
18959   case ISD::SMAX:
18960   case ISD::SMIN:
18961   case ISD::UMAX:
18962   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18963   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18964   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18965   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18966   case ISD::GC_TRANSITION_START:
18967                                 return LowerGC_TRANSITION_START(Op, DAG);
18968   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18969   }
18970 }
18971
18972 /// ReplaceNodeResults - Replace a node with an illegal result type
18973 /// with a new node built out of custom code.
18974 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18975                                            SmallVectorImpl<SDValue>&Results,
18976                                            SelectionDAG &DAG) const {
18977   SDLoc dl(N);
18978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18979   switch (N->getOpcode()) {
18980   default:
18981     llvm_unreachable("Do not know how to custom type legalize this operation!");
18982   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18983   case X86ISD::FMINC:
18984   case X86ISD::FMIN:
18985   case X86ISD::FMAXC:
18986   case X86ISD::FMAX: {
18987     EVT VT = N->getValueType(0);
18988     if (VT != MVT::v2f32)
18989       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18990     SDValue UNDEF = DAG.getUNDEF(VT);
18991     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18992                               N->getOperand(0), UNDEF);
18993     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18994                               N->getOperand(1), UNDEF);
18995     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18996     return;
18997   }
18998   case ISD::SIGN_EXTEND_INREG:
18999   case ISD::ADDC:
19000   case ISD::ADDE:
19001   case ISD::SUBC:
19002   case ISD::SUBE:
19003     // We don't want to expand or promote these.
19004     return;
19005   case ISD::SDIV:
19006   case ISD::UDIV:
19007   case ISD::SREM:
19008   case ISD::UREM:
19009   case ISD::SDIVREM:
19010   case ISD::UDIVREM: {
19011     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19012     Results.push_back(V);
19013     return;
19014   }
19015   case ISD::FP_TO_SINT:
19016   case ISD::FP_TO_UINT: {
19017     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19018
19019     std::pair<SDValue,SDValue> Vals =
19020         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19021     SDValue FIST = Vals.first, StackSlot = Vals.second;
19022     if (FIST.getNode()) {
19023       EVT VT = N->getValueType(0);
19024       // Return a load from the stack slot.
19025       if (StackSlot.getNode())
19026         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19027                                       MachinePointerInfo(),
19028                                       false, false, false, 0));
19029       else
19030         Results.push_back(FIST);
19031     }
19032     return;
19033   }
19034   case ISD::UINT_TO_FP: {
19035     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19036     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19037         N->getValueType(0) != MVT::v2f32)
19038       return;
19039     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19040                                  N->getOperand(0));
19041     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19042                                      MVT::f64);
19043     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19044     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19045                              DAG.getBitcast(MVT::v2i64, VBias));
19046     Or = DAG.getBitcast(MVT::v2f64, Or);
19047     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19048     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19049     return;
19050   }
19051   case ISD::FP_ROUND: {
19052     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19053         return;
19054     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19055     Results.push_back(V);
19056     return;
19057   }
19058   case ISD::FP_EXTEND: {
19059     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19060     // No other ValueType for FP_EXTEND should reach this point.
19061     assert(N->getValueType(0) == MVT::v2f32 &&
19062            "Do not know how to legalize this Node");
19063     return;
19064   }
19065   case ISD::INTRINSIC_W_CHAIN: {
19066     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19067     switch (IntNo) {
19068     default : llvm_unreachable("Do not know how to custom type "
19069                                "legalize this intrinsic operation!");
19070     case Intrinsic::x86_rdtsc:
19071       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19072                                      Results);
19073     case Intrinsic::x86_rdtscp:
19074       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19075                                      Results);
19076     case Intrinsic::x86_rdpmc:
19077       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19078     }
19079   }
19080   case ISD::READCYCLECOUNTER: {
19081     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19082                                    Results);
19083   }
19084   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19085     EVT T = N->getValueType(0);
19086     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19087     bool Regs64bit = T == MVT::i128;
19088     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19089     SDValue cpInL, cpInH;
19090     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19091                         DAG.getConstant(0, dl, HalfT));
19092     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19093                         DAG.getConstant(1, dl, HalfT));
19094     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19095                              Regs64bit ? X86::RAX : X86::EAX,
19096                              cpInL, SDValue());
19097     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19098                              Regs64bit ? X86::RDX : X86::EDX,
19099                              cpInH, cpInL.getValue(1));
19100     SDValue swapInL, swapInH;
19101     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19102                           DAG.getConstant(0, dl, HalfT));
19103     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19104                           DAG.getConstant(1, dl, HalfT));
19105     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19106                                Regs64bit ? X86::RBX : X86::EBX,
19107                                swapInL, cpInH.getValue(1));
19108     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19109                                Regs64bit ? X86::RCX : X86::ECX,
19110                                swapInH, swapInL.getValue(1));
19111     SDValue Ops[] = { swapInH.getValue(0),
19112                       N->getOperand(1),
19113                       swapInH.getValue(1) };
19114     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19115     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19116     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19117                                   X86ISD::LCMPXCHG8_DAG;
19118     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19119     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19120                                         Regs64bit ? X86::RAX : X86::EAX,
19121                                         HalfT, Result.getValue(1));
19122     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19123                                         Regs64bit ? X86::RDX : X86::EDX,
19124                                         HalfT, cpOutL.getValue(2));
19125     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19126
19127     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19128                                         MVT::i32, cpOutH.getValue(2));
19129     SDValue Success =
19130         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19131                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19132     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19133
19134     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19135     Results.push_back(Success);
19136     Results.push_back(EFLAGS.getValue(1));
19137     return;
19138   }
19139   case ISD::ATOMIC_SWAP:
19140   case ISD::ATOMIC_LOAD_ADD:
19141   case ISD::ATOMIC_LOAD_SUB:
19142   case ISD::ATOMIC_LOAD_AND:
19143   case ISD::ATOMIC_LOAD_OR:
19144   case ISD::ATOMIC_LOAD_XOR:
19145   case ISD::ATOMIC_LOAD_NAND:
19146   case ISD::ATOMIC_LOAD_MIN:
19147   case ISD::ATOMIC_LOAD_MAX:
19148   case ISD::ATOMIC_LOAD_UMIN:
19149   case ISD::ATOMIC_LOAD_UMAX:
19150   case ISD::ATOMIC_LOAD: {
19151     // Delegate to generic TypeLegalization. Situations we can really handle
19152     // should have already been dealt with by AtomicExpandPass.cpp.
19153     break;
19154   }
19155   case ISD::BITCAST: {
19156     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19157     EVT DstVT = N->getValueType(0);
19158     EVT SrcVT = N->getOperand(0)->getValueType(0);
19159
19160     if (SrcVT != MVT::f64 ||
19161         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19162       return;
19163
19164     unsigned NumElts = DstVT.getVectorNumElements();
19165     EVT SVT = DstVT.getVectorElementType();
19166     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19167     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19168                                    MVT::v2f64, N->getOperand(0));
19169     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19170
19171     if (ExperimentalVectorWideningLegalization) {
19172       // If we are legalizing vectors by widening, we already have the desired
19173       // legal vector type, just return it.
19174       Results.push_back(ToVecInt);
19175       return;
19176     }
19177
19178     SmallVector<SDValue, 8> Elts;
19179     for (unsigned i = 0, e = NumElts; i != e; ++i)
19180       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19181                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19182
19183     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19184   }
19185   }
19186 }
19187
19188 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19189   switch ((X86ISD::NodeType)Opcode) {
19190   case X86ISD::FIRST_NUMBER:       break;
19191   case X86ISD::BSF:                return "X86ISD::BSF";
19192   case X86ISD::BSR:                return "X86ISD::BSR";
19193   case X86ISD::SHLD:               return "X86ISD::SHLD";
19194   case X86ISD::SHRD:               return "X86ISD::SHRD";
19195   case X86ISD::FAND:               return "X86ISD::FAND";
19196   case X86ISD::FANDN:              return "X86ISD::FANDN";
19197   case X86ISD::FOR:                return "X86ISD::FOR";
19198   case X86ISD::FXOR:               return "X86ISD::FXOR";
19199   case X86ISD::FILD:               return "X86ISD::FILD";
19200   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19201   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19202   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19203   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19204   case X86ISD::FLD:                return "X86ISD::FLD";
19205   case X86ISD::FST:                return "X86ISD::FST";
19206   case X86ISD::CALL:               return "X86ISD::CALL";
19207   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19208   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19209   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19210   case X86ISD::BT:                 return "X86ISD::BT";
19211   case X86ISD::CMP:                return "X86ISD::CMP";
19212   case X86ISD::COMI:               return "X86ISD::COMI";
19213   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19214   case X86ISD::CMPM:               return "X86ISD::CMPM";
19215   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19216   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19217   case X86ISD::SETCC:              return "X86ISD::SETCC";
19218   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19219   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19220   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19221   case X86ISD::CMOV:               return "X86ISD::CMOV";
19222   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19223   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19224   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19225   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19226   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19227   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19228   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19229   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19230   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19231   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19232   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19233   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19234   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19235   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19236   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19237   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19238   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19239   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19240   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19241   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19242   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19243   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19244   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19245   case X86ISD::HADD:               return "X86ISD::HADD";
19246   case X86ISD::HSUB:               return "X86ISD::HSUB";
19247   case X86ISD::FHADD:              return "X86ISD::FHADD";
19248   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19249   case X86ISD::ABS:                return "X86ISD::ABS";
19250   case X86ISD::FMAX:               return "X86ISD::FMAX";
19251   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19252   case X86ISD::FMIN:               return "X86ISD::FMIN";
19253   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19254   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19255   case X86ISD::FMINC:              return "X86ISD::FMINC";
19256   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19257   case X86ISD::FRCP:               return "X86ISD::FRCP";
19258   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19259   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19260   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19261   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19262   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19263   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19264   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19265   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19266   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19267   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19268   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19269   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19270   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19271   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19272   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19273   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19274   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19275   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19276   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19277   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19278   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19279   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19280   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19281   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19282   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19283   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19284   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19285   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19286   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19287   case X86ISD::VSHL:               return "X86ISD::VSHL";
19288   case X86ISD::VSRL:               return "X86ISD::VSRL";
19289   case X86ISD::VSRA:               return "X86ISD::VSRA";
19290   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19291   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19292   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19293   case X86ISD::CMPP:               return "X86ISD::CMPP";
19294   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19295   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19296   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19297   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19298   case X86ISD::ADD:                return "X86ISD::ADD";
19299   case X86ISD::SUB:                return "X86ISD::SUB";
19300   case X86ISD::ADC:                return "X86ISD::ADC";
19301   case X86ISD::SBB:                return "X86ISD::SBB";
19302   case X86ISD::SMUL:               return "X86ISD::SMUL";
19303   case X86ISD::UMUL:               return "X86ISD::UMUL";
19304   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19305   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19306   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19307   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19308   case X86ISD::INC:                return "X86ISD::INC";
19309   case X86ISD::DEC:                return "X86ISD::DEC";
19310   case X86ISD::OR:                 return "X86ISD::OR";
19311   case X86ISD::XOR:                return "X86ISD::XOR";
19312   case X86ISD::AND:                return "X86ISD::AND";
19313   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19314   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19315   case X86ISD::PTEST:              return "X86ISD::PTEST";
19316   case X86ISD::TESTP:              return "X86ISD::TESTP";
19317   case X86ISD::TESTM:              return "X86ISD::TESTM";
19318   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19319   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19320   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19321   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19322   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19323   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19324   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19325   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19326   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19327   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19328   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19329   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19330   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19331   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19332   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19333   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19334   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19335   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19336   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19337   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19338   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19339   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19340   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19341   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19342   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19343   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19344   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19345   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19346   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19347   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19348   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19349   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19350   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19351   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19352   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19353   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19354   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19355   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19356   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19357   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19358   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19359   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19360   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19361   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19362   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19363   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19364   case X86ISD::SAHF:               return "X86ISD::SAHF";
19365   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19366   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19367   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19368   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19369   case X86ISD::FMADD:              return "X86ISD::FMADD";
19370   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19371   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19372   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19373   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19374   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19375   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19376   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19377   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19378   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19379   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19380   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19381   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19382   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19383   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19384   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19385   case X86ISD::XTEST:              return "X86ISD::XTEST";
19386   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19387   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19388   case X86ISD::SELECT:             return "X86ISD::SELECT";
19389   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19390   case X86ISD::RCP28:              return "X86ISD::RCP28";
19391   case X86ISD::EXP2:               return "X86ISD::EXP2";
19392   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19393   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19394   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19395   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19396   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19397   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19398   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19399   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19400   case X86ISD::ADDS:               return "X86ISD::ADDS";
19401   case X86ISD::SUBS:               return "X86ISD::SUBS";
19402   case X86ISD::AVG:                return "X86ISD::AVG";
19403   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19404   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19405   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19406   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19407   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19408   }
19409   return nullptr;
19410 }
19411
19412 // isLegalAddressingMode - Return true if the addressing mode represented
19413 // by AM is legal for this target, for a load/store of the specified type.
19414 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19415                                               const AddrMode &AM, Type *Ty,
19416                                               unsigned AS) const {
19417   // X86 supports extremely general addressing modes.
19418   CodeModel::Model M = getTargetMachine().getCodeModel();
19419   Reloc::Model R = getTargetMachine().getRelocationModel();
19420
19421   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19422   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19423     return false;
19424
19425   if (AM.BaseGV) {
19426     unsigned GVFlags =
19427       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19428
19429     // If a reference to this global requires an extra load, we can't fold it.
19430     if (isGlobalStubReference(GVFlags))
19431       return false;
19432
19433     // If BaseGV requires a register for the PIC base, we cannot also have a
19434     // BaseReg specified.
19435     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19436       return false;
19437
19438     // If lower 4G is not available, then we must use rip-relative addressing.
19439     if ((M != CodeModel::Small || R != Reloc::Static) &&
19440         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19441       return false;
19442   }
19443
19444   switch (AM.Scale) {
19445   case 0:
19446   case 1:
19447   case 2:
19448   case 4:
19449   case 8:
19450     // These scales always work.
19451     break;
19452   case 3:
19453   case 5:
19454   case 9:
19455     // These scales are formed with basereg+scalereg.  Only accept if there is
19456     // no basereg yet.
19457     if (AM.HasBaseReg)
19458       return false;
19459     break;
19460   default:  // Other stuff never works.
19461     return false;
19462   }
19463
19464   return true;
19465 }
19466
19467 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19468   unsigned Bits = Ty->getScalarSizeInBits();
19469
19470   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19471   // particularly cheaper than those without.
19472   if (Bits == 8)
19473     return false;
19474
19475   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19476   // variable shifts just as cheap as scalar ones.
19477   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19478     return false;
19479
19480   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19481   // fully general vector.
19482   return true;
19483 }
19484
19485 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19486   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19487     return false;
19488   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19489   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19490   return NumBits1 > NumBits2;
19491 }
19492
19493 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19494   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19495     return false;
19496
19497   if (!isTypeLegal(EVT::getEVT(Ty1)))
19498     return false;
19499
19500   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19501
19502   // Assuming the caller doesn't have a zeroext or signext return parameter,
19503   // truncation all the way down to i1 is valid.
19504   return true;
19505 }
19506
19507 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19508   return isInt<32>(Imm);
19509 }
19510
19511 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19512   // Can also use sub to handle negated immediates.
19513   return isInt<32>(Imm);
19514 }
19515
19516 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19517   if (!VT1.isInteger() || !VT2.isInteger())
19518     return false;
19519   unsigned NumBits1 = VT1.getSizeInBits();
19520   unsigned NumBits2 = VT2.getSizeInBits();
19521   return NumBits1 > NumBits2;
19522 }
19523
19524 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19525   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19526   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19527 }
19528
19529 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19530   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19531   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19532 }
19533
19534 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19535   EVT VT1 = Val.getValueType();
19536   if (isZExtFree(VT1, VT2))
19537     return true;
19538
19539   if (Val.getOpcode() != ISD::LOAD)
19540     return false;
19541
19542   if (!VT1.isSimple() || !VT1.isInteger() ||
19543       !VT2.isSimple() || !VT2.isInteger())
19544     return false;
19545
19546   switch (VT1.getSimpleVT().SimpleTy) {
19547   default: break;
19548   case MVT::i8:
19549   case MVT::i16:
19550   case MVT::i32:
19551     // X86 has 8, 16, and 32-bit zero-extending loads.
19552     return true;
19553   }
19554
19555   return false;
19556 }
19557
19558 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19559
19560 bool
19561 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19562   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19563     return false;
19564
19565   VT = VT.getScalarType();
19566
19567   if (!VT.isSimple())
19568     return false;
19569
19570   switch (VT.getSimpleVT().SimpleTy) {
19571   case MVT::f32:
19572   case MVT::f64:
19573     return true;
19574   default:
19575     break;
19576   }
19577
19578   return false;
19579 }
19580
19581 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19582   // i16 instructions are longer (0x66 prefix) and potentially slower.
19583   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19584 }
19585
19586 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19587 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19588 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19589 /// are assumed to be legal.
19590 bool
19591 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19592                                       EVT VT) const {
19593   if (!VT.isSimple())
19594     return false;
19595
19596   // Not for i1 vectors
19597   if (VT.getScalarType() == MVT::i1)
19598     return false;
19599
19600   // Very little shuffling can be done for 64-bit vectors right now.
19601   if (VT.getSizeInBits() == 64)
19602     return false;
19603
19604   // We only care that the types being shuffled are legal. The lowering can
19605   // handle any possible shuffle mask that results.
19606   return isTypeLegal(VT.getSimpleVT());
19607 }
19608
19609 bool
19610 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19611                                           EVT VT) const {
19612   // Just delegate to the generic legality, clear masks aren't special.
19613   return isShuffleMaskLegal(Mask, VT);
19614 }
19615
19616 //===----------------------------------------------------------------------===//
19617 //                           X86 Scheduler Hooks
19618 //===----------------------------------------------------------------------===//
19619
19620 /// Utility function to emit xbegin specifying the start of an RTM region.
19621 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19622                                      const TargetInstrInfo *TII) {
19623   DebugLoc DL = MI->getDebugLoc();
19624
19625   const BasicBlock *BB = MBB->getBasicBlock();
19626   MachineFunction::iterator I = MBB;
19627   ++I;
19628
19629   // For the v = xbegin(), we generate
19630   //
19631   // thisMBB:
19632   //  xbegin sinkMBB
19633   //
19634   // mainMBB:
19635   //  eax = -1
19636   //
19637   // sinkMBB:
19638   //  v = eax
19639
19640   MachineBasicBlock *thisMBB = MBB;
19641   MachineFunction *MF = MBB->getParent();
19642   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19643   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19644   MF->insert(I, mainMBB);
19645   MF->insert(I, sinkMBB);
19646
19647   // Transfer the remainder of BB and its successor edges to sinkMBB.
19648   sinkMBB->splice(sinkMBB->begin(), MBB,
19649                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19650   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19651
19652   // thisMBB:
19653   //  xbegin sinkMBB
19654   //  # fallthrough to mainMBB
19655   //  # abortion to sinkMBB
19656   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19657   thisMBB->addSuccessor(mainMBB);
19658   thisMBB->addSuccessor(sinkMBB);
19659
19660   // mainMBB:
19661   //  EAX = -1
19662   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19663   mainMBB->addSuccessor(sinkMBB);
19664
19665   // sinkMBB:
19666   // EAX is live into the sinkMBB
19667   sinkMBB->addLiveIn(X86::EAX);
19668   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19669           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19670     .addReg(X86::EAX);
19671
19672   MI->eraseFromParent();
19673   return sinkMBB;
19674 }
19675
19676 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19677 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19678 // in the .td file.
19679 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19680                                        const TargetInstrInfo *TII) {
19681   unsigned Opc;
19682   switch (MI->getOpcode()) {
19683   default: llvm_unreachable("illegal opcode!");
19684   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19685   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19686   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19687   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19688   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19689   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19690   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19691   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19692   }
19693
19694   DebugLoc dl = MI->getDebugLoc();
19695   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19696
19697   unsigned NumArgs = MI->getNumOperands();
19698   for (unsigned i = 1; i < NumArgs; ++i) {
19699     MachineOperand &Op = MI->getOperand(i);
19700     if (!(Op.isReg() && Op.isImplicit()))
19701       MIB.addOperand(Op);
19702   }
19703   if (MI->hasOneMemOperand())
19704     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19705
19706   BuildMI(*BB, MI, dl,
19707     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19708     .addReg(X86::XMM0);
19709
19710   MI->eraseFromParent();
19711   return BB;
19712 }
19713
19714 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19715 // defs in an instruction pattern
19716 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19717                                        const TargetInstrInfo *TII) {
19718   unsigned Opc;
19719   switch (MI->getOpcode()) {
19720   default: llvm_unreachable("illegal opcode!");
19721   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19722   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19723   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19724   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19725   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19726   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19727   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19728   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19729   }
19730
19731   DebugLoc dl = MI->getDebugLoc();
19732   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19733
19734   unsigned NumArgs = MI->getNumOperands(); // remove the results
19735   for (unsigned i = 1; i < NumArgs; ++i) {
19736     MachineOperand &Op = MI->getOperand(i);
19737     if (!(Op.isReg() && Op.isImplicit()))
19738       MIB.addOperand(Op);
19739   }
19740   if (MI->hasOneMemOperand())
19741     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19742
19743   BuildMI(*BB, MI, dl,
19744     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19745     .addReg(X86::ECX);
19746
19747   MI->eraseFromParent();
19748   return BB;
19749 }
19750
19751 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19752                                       const X86Subtarget *Subtarget) {
19753   DebugLoc dl = MI->getDebugLoc();
19754   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19755   // Address into RAX/EAX, other two args into ECX, EDX.
19756   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19757   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19758   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19759   for (int i = 0; i < X86::AddrNumOperands; ++i)
19760     MIB.addOperand(MI->getOperand(i));
19761
19762   unsigned ValOps = X86::AddrNumOperands;
19763   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19764     .addReg(MI->getOperand(ValOps).getReg());
19765   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19766     .addReg(MI->getOperand(ValOps+1).getReg());
19767
19768   // The instruction doesn't actually take any operands though.
19769   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19770
19771   MI->eraseFromParent(); // The pseudo is gone now.
19772   return BB;
19773 }
19774
19775 MachineBasicBlock *
19776 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19777                                                  MachineBasicBlock *MBB) const {
19778   // Emit va_arg instruction on X86-64.
19779
19780   // Operands to this pseudo-instruction:
19781   // 0  ) Output        : destination address (reg)
19782   // 1-5) Input         : va_list address (addr, i64mem)
19783   // 6  ) ArgSize       : Size (in bytes) of vararg type
19784   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19785   // 8  ) Align         : Alignment of type
19786   // 9  ) EFLAGS (implicit-def)
19787
19788   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19789   static_assert(X86::AddrNumOperands == 5,
19790                 "VAARG_64 assumes 5 address operands");
19791
19792   unsigned DestReg = MI->getOperand(0).getReg();
19793   MachineOperand &Base = MI->getOperand(1);
19794   MachineOperand &Scale = MI->getOperand(2);
19795   MachineOperand &Index = MI->getOperand(3);
19796   MachineOperand &Disp = MI->getOperand(4);
19797   MachineOperand &Segment = MI->getOperand(5);
19798   unsigned ArgSize = MI->getOperand(6).getImm();
19799   unsigned ArgMode = MI->getOperand(7).getImm();
19800   unsigned Align = MI->getOperand(8).getImm();
19801
19802   // Memory Reference
19803   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19804   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19805   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19806
19807   // Machine Information
19808   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19809   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19810   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19811   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19812   DebugLoc DL = MI->getDebugLoc();
19813
19814   // struct va_list {
19815   //   i32   gp_offset
19816   //   i32   fp_offset
19817   //   i64   overflow_area (address)
19818   //   i64   reg_save_area (address)
19819   // }
19820   // sizeof(va_list) = 24
19821   // alignment(va_list) = 8
19822
19823   unsigned TotalNumIntRegs = 6;
19824   unsigned TotalNumXMMRegs = 8;
19825   bool UseGPOffset = (ArgMode == 1);
19826   bool UseFPOffset = (ArgMode == 2);
19827   unsigned MaxOffset = TotalNumIntRegs * 8 +
19828                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19829
19830   /* Align ArgSize to a multiple of 8 */
19831   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19832   bool NeedsAlign = (Align > 8);
19833
19834   MachineBasicBlock *thisMBB = MBB;
19835   MachineBasicBlock *overflowMBB;
19836   MachineBasicBlock *offsetMBB;
19837   MachineBasicBlock *endMBB;
19838
19839   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19840   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19841   unsigned OffsetReg = 0;
19842
19843   if (!UseGPOffset && !UseFPOffset) {
19844     // If we only pull from the overflow region, we don't create a branch.
19845     // We don't need to alter control flow.
19846     OffsetDestReg = 0; // unused
19847     OverflowDestReg = DestReg;
19848
19849     offsetMBB = nullptr;
19850     overflowMBB = thisMBB;
19851     endMBB = thisMBB;
19852   } else {
19853     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19854     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19855     // If not, pull from overflow_area. (branch to overflowMBB)
19856     //
19857     //       thisMBB
19858     //         |     .
19859     //         |        .
19860     //     offsetMBB   overflowMBB
19861     //         |        .
19862     //         |     .
19863     //        endMBB
19864
19865     // Registers for the PHI in endMBB
19866     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19867     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19868
19869     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19870     MachineFunction *MF = MBB->getParent();
19871     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19872     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19873     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19874
19875     MachineFunction::iterator MBBIter = MBB;
19876     ++MBBIter;
19877
19878     // Insert the new basic blocks
19879     MF->insert(MBBIter, offsetMBB);
19880     MF->insert(MBBIter, overflowMBB);
19881     MF->insert(MBBIter, endMBB);
19882
19883     // Transfer the remainder of MBB and its successor edges to endMBB.
19884     endMBB->splice(endMBB->begin(), thisMBB,
19885                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19886     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19887
19888     // Make offsetMBB and overflowMBB successors of thisMBB
19889     thisMBB->addSuccessor(offsetMBB);
19890     thisMBB->addSuccessor(overflowMBB);
19891
19892     // endMBB is a successor of both offsetMBB and overflowMBB
19893     offsetMBB->addSuccessor(endMBB);
19894     overflowMBB->addSuccessor(endMBB);
19895
19896     // Load the offset value into a register
19897     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19898     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19899       .addOperand(Base)
19900       .addOperand(Scale)
19901       .addOperand(Index)
19902       .addDisp(Disp, UseFPOffset ? 4 : 0)
19903       .addOperand(Segment)
19904       .setMemRefs(MMOBegin, MMOEnd);
19905
19906     // Check if there is enough room left to pull this argument.
19907     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19908       .addReg(OffsetReg)
19909       .addImm(MaxOffset + 8 - ArgSizeA8);
19910
19911     // Branch to "overflowMBB" if offset >= max
19912     // Fall through to "offsetMBB" otherwise
19913     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19914       .addMBB(overflowMBB);
19915   }
19916
19917   // In offsetMBB, emit code to use the reg_save_area.
19918   if (offsetMBB) {
19919     assert(OffsetReg != 0);
19920
19921     // Read the reg_save_area address.
19922     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19923     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19924       .addOperand(Base)
19925       .addOperand(Scale)
19926       .addOperand(Index)
19927       .addDisp(Disp, 16)
19928       .addOperand(Segment)
19929       .setMemRefs(MMOBegin, MMOEnd);
19930
19931     // Zero-extend the offset
19932     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19933       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19934         .addImm(0)
19935         .addReg(OffsetReg)
19936         .addImm(X86::sub_32bit);
19937
19938     // Add the offset to the reg_save_area to get the final address.
19939     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19940       .addReg(OffsetReg64)
19941       .addReg(RegSaveReg);
19942
19943     // Compute the offset for the next argument
19944     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19945     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19946       .addReg(OffsetReg)
19947       .addImm(UseFPOffset ? 16 : 8);
19948
19949     // Store it back into the va_list.
19950     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19951       .addOperand(Base)
19952       .addOperand(Scale)
19953       .addOperand(Index)
19954       .addDisp(Disp, UseFPOffset ? 4 : 0)
19955       .addOperand(Segment)
19956       .addReg(NextOffsetReg)
19957       .setMemRefs(MMOBegin, MMOEnd);
19958
19959     // Jump to endMBB
19960     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19961       .addMBB(endMBB);
19962   }
19963
19964   //
19965   // Emit code to use overflow area
19966   //
19967
19968   // Load the overflow_area address into a register.
19969   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19970   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19971     .addOperand(Base)
19972     .addOperand(Scale)
19973     .addOperand(Index)
19974     .addDisp(Disp, 8)
19975     .addOperand(Segment)
19976     .setMemRefs(MMOBegin, MMOEnd);
19977
19978   // If we need to align it, do so. Otherwise, just copy the address
19979   // to OverflowDestReg.
19980   if (NeedsAlign) {
19981     // Align the overflow address
19982     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19983     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19984
19985     // aligned_addr = (addr + (align-1)) & ~(align-1)
19986     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19987       .addReg(OverflowAddrReg)
19988       .addImm(Align-1);
19989
19990     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19991       .addReg(TmpReg)
19992       .addImm(~(uint64_t)(Align-1));
19993   } else {
19994     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19995       .addReg(OverflowAddrReg);
19996   }
19997
19998   // Compute the next overflow address after this argument.
19999   // (the overflow address should be kept 8-byte aligned)
20000   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20001   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20002     .addReg(OverflowDestReg)
20003     .addImm(ArgSizeA8);
20004
20005   // Store the new overflow address.
20006   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20007     .addOperand(Base)
20008     .addOperand(Scale)
20009     .addOperand(Index)
20010     .addDisp(Disp, 8)
20011     .addOperand(Segment)
20012     .addReg(NextAddrReg)
20013     .setMemRefs(MMOBegin, MMOEnd);
20014
20015   // If we branched, emit the PHI to the front of endMBB.
20016   if (offsetMBB) {
20017     BuildMI(*endMBB, endMBB->begin(), DL,
20018             TII->get(X86::PHI), DestReg)
20019       .addReg(OffsetDestReg).addMBB(offsetMBB)
20020       .addReg(OverflowDestReg).addMBB(overflowMBB);
20021   }
20022
20023   // Erase the pseudo instruction
20024   MI->eraseFromParent();
20025
20026   return endMBB;
20027 }
20028
20029 MachineBasicBlock *
20030 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20031                                                  MachineInstr *MI,
20032                                                  MachineBasicBlock *MBB) const {
20033   // Emit code to save XMM registers to the stack. The ABI says that the
20034   // number of registers to save is given in %al, so it's theoretically
20035   // possible to do an indirect jump trick to avoid saving all of them,
20036   // however this code takes a simpler approach and just executes all
20037   // of the stores if %al is non-zero. It's less code, and it's probably
20038   // easier on the hardware branch predictor, and stores aren't all that
20039   // expensive anyway.
20040
20041   // Create the new basic blocks. One block contains all the XMM stores,
20042   // and one block is the final destination regardless of whether any
20043   // stores were performed.
20044   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20045   MachineFunction *F = MBB->getParent();
20046   MachineFunction::iterator MBBIter = MBB;
20047   ++MBBIter;
20048   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20049   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20050   F->insert(MBBIter, XMMSaveMBB);
20051   F->insert(MBBIter, EndMBB);
20052
20053   // Transfer the remainder of MBB and its successor edges to EndMBB.
20054   EndMBB->splice(EndMBB->begin(), MBB,
20055                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20056   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20057
20058   // The original block will now fall through to the XMM save block.
20059   MBB->addSuccessor(XMMSaveMBB);
20060   // The XMMSaveMBB will fall through to the end block.
20061   XMMSaveMBB->addSuccessor(EndMBB);
20062
20063   // Now add the instructions.
20064   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20065   DebugLoc DL = MI->getDebugLoc();
20066
20067   unsigned CountReg = MI->getOperand(0).getReg();
20068   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20069   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20070
20071   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20072     // If %al is 0, branch around the XMM save block.
20073     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20074     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20075     MBB->addSuccessor(EndMBB);
20076   }
20077
20078   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20079   // that was just emitted, but clearly shouldn't be "saved".
20080   assert((MI->getNumOperands() <= 3 ||
20081           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20082           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20083          && "Expected last argument to be EFLAGS");
20084   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20085   // In the XMM save block, save all the XMM argument registers.
20086   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20087     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20088     MachineMemOperand *MMO = F->getMachineMemOperand(
20089         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20090         MachineMemOperand::MOStore,
20091         /*Size=*/16, /*Align=*/16);
20092     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20093       .addFrameIndex(RegSaveFrameIndex)
20094       .addImm(/*Scale=*/1)
20095       .addReg(/*IndexReg=*/0)
20096       .addImm(/*Disp=*/Offset)
20097       .addReg(/*Segment=*/0)
20098       .addReg(MI->getOperand(i).getReg())
20099       .addMemOperand(MMO);
20100   }
20101
20102   MI->eraseFromParent();   // The pseudo instruction is gone now.
20103
20104   return EndMBB;
20105 }
20106
20107 // The EFLAGS operand of SelectItr might be missing a kill marker
20108 // because there were multiple uses of EFLAGS, and ISel didn't know
20109 // which to mark. Figure out whether SelectItr should have had a
20110 // kill marker, and set it if it should. Returns the correct kill
20111 // marker value.
20112 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20113                                      MachineBasicBlock* BB,
20114                                      const TargetRegisterInfo* TRI) {
20115   // Scan forward through BB for a use/def of EFLAGS.
20116   MachineBasicBlock::iterator miI(std::next(SelectItr));
20117   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20118     const MachineInstr& mi = *miI;
20119     if (mi.readsRegister(X86::EFLAGS))
20120       return false;
20121     if (mi.definesRegister(X86::EFLAGS))
20122       break; // Should have kill-flag - update below.
20123   }
20124
20125   // If we hit the end of the block, check whether EFLAGS is live into a
20126   // successor.
20127   if (miI == BB->end()) {
20128     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20129                                           sEnd = BB->succ_end();
20130          sItr != sEnd; ++sItr) {
20131       MachineBasicBlock* succ = *sItr;
20132       if (succ->isLiveIn(X86::EFLAGS))
20133         return false;
20134     }
20135   }
20136
20137   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20138   // out. SelectMI should have a kill flag on EFLAGS.
20139   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20140   return true;
20141 }
20142
20143 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20144 // together with other CMOV pseudo-opcodes into a single basic-block with
20145 // conditional jump around it.
20146 static bool isCMOVPseudo(MachineInstr *MI) {
20147   switch (MI->getOpcode()) {
20148   case X86::CMOV_FR32:
20149   case X86::CMOV_FR64:
20150   case X86::CMOV_GR8:
20151   case X86::CMOV_GR16:
20152   case X86::CMOV_GR32:
20153   case X86::CMOV_RFP32:
20154   case X86::CMOV_RFP64:
20155   case X86::CMOV_RFP80:
20156   case X86::CMOV_V2F64:
20157   case X86::CMOV_V2I64:
20158   case X86::CMOV_V4F32:
20159   case X86::CMOV_V4F64:
20160   case X86::CMOV_V4I64:
20161   case X86::CMOV_V16F32:
20162   case X86::CMOV_V8F32:
20163   case X86::CMOV_V8F64:
20164   case X86::CMOV_V8I64:
20165   case X86::CMOV_V8I1:
20166   case X86::CMOV_V16I1:
20167   case X86::CMOV_V32I1:
20168   case X86::CMOV_V64I1:
20169     return true;
20170
20171   default:
20172     return false;
20173   }
20174 }
20175
20176 MachineBasicBlock *
20177 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20178                                      MachineBasicBlock *BB) const {
20179   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20180   DebugLoc DL = MI->getDebugLoc();
20181
20182   // To "insert" a SELECT_CC instruction, we actually have to insert the
20183   // diamond control-flow pattern.  The incoming instruction knows the
20184   // destination vreg to set, the condition code register to branch on, the
20185   // true/false values to select between, and a branch opcode to use.
20186   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20187   MachineFunction::iterator It = BB;
20188   ++It;
20189
20190   //  thisMBB:
20191   //  ...
20192   //   TrueVal = ...
20193   //   cmpTY ccX, r1, r2
20194   //   bCC copy1MBB
20195   //   fallthrough --> copy0MBB
20196   MachineBasicBlock *thisMBB = BB;
20197   MachineFunction *F = BB->getParent();
20198
20199   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20200   // as described above, by inserting a BB, and then making a PHI at the join
20201   // point to select the true and false operands of the CMOV in the PHI.
20202   //
20203   // The code also handles two different cases of multiple CMOV opcodes
20204   // in a row.
20205   //
20206   // Case 1:
20207   // In this case, there are multiple CMOVs in a row, all which are based on
20208   // the same condition setting (or the exact opposite condition setting).
20209   // In this case we can lower all the CMOVs using a single inserted BB, and
20210   // then make a number of PHIs at the join point to model the CMOVs. The only
20211   // trickiness here, is that in a case like:
20212   //
20213   // t2 = CMOV cond1 t1, f1
20214   // t3 = CMOV cond1 t2, f2
20215   //
20216   // when rewriting this into PHIs, we have to perform some renaming on the
20217   // temps since you cannot have a PHI operand refer to a PHI result earlier
20218   // in the same block.  The "simple" but wrong lowering would be:
20219   //
20220   // t2 = PHI t1(BB1), f1(BB2)
20221   // t3 = PHI t2(BB1), f2(BB2)
20222   //
20223   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20224   // renaming is to note that on the path through BB1, t2 is really just a
20225   // copy of t1, and do that renaming, properly generating:
20226   //
20227   // t2 = PHI t1(BB1), f1(BB2)
20228   // t3 = PHI t1(BB1), f2(BB2)
20229   //
20230   // Case 2, we lower cascaded CMOVs such as
20231   //
20232   //   (CMOV (CMOV F, T, cc1), T, cc2)
20233   //
20234   // to two successives branches.  For that, we look for another CMOV as the
20235   // following instruction.
20236   //
20237   // Without this, we would add a PHI between the two jumps, which ends up
20238   // creating a few copies all around. For instance, for
20239   //
20240   //    (sitofp (zext (fcmp une)))
20241   //
20242   // we would generate:
20243   //
20244   //         ucomiss %xmm1, %xmm0
20245   //         movss  <1.0f>, %xmm0
20246   //         movaps  %xmm0, %xmm1
20247   //         jne     .LBB5_2
20248   //         xorps   %xmm1, %xmm1
20249   // .LBB5_2:
20250   //         jp      .LBB5_4
20251   //         movaps  %xmm1, %xmm0
20252   // .LBB5_4:
20253   //         retq
20254   //
20255   // because this custom-inserter would have generated:
20256   //
20257   //   A
20258   //   | \
20259   //   |  B
20260   //   | /
20261   //   C
20262   //   | \
20263   //   |  D
20264   //   | /
20265   //   E
20266   //
20267   // A: X = ...; Y = ...
20268   // B: empty
20269   // C: Z = PHI [X, A], [Y, B]
20270   // D: empty
20271   // E: PHI [X, C], [Z, D]
20272   //
20273   // If we lower both CMOVs in a single step, we can instead generate:
20274   //
20275   //   A
20276   //   | \
20277   //   |  C
20278   //   | /|
20279   //   |/ |
20280   //   |  |
20281   //   |  D
20282   //   | /
20283   //   E
20284   //
20285   // A: X = ...; Y = ...
20286   // D: empty
20287   // E: PHI [X, A], [X, C], [Y, D]
20288   //
20289   // Which, in our sitofp/fcmp example, gives us something like:
20290   //
20291   //         ucomiss %xmm1, %xmm0
20292   //         movss  <1.0f>, %xmm0
20293   //         jne     .LBB5_4
20294   //         jp      .LBB5_4
20295   //         xorps   %xmm0, %xmm0
20296   // .LBB5_4:
20297   //         retq
20298   //
20299   MachineInstr *CascadedCMOV = nullptr;
20300   MachineInstr *LastCMOV = MI;
20301   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20302   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20303   MachineBasicBlock::iterator NextMIIt =
20304       std::next(MachineBasicBlock::iterator(MI));
20305
20306   // Check for case 1, where there are multiple CMOVs with the same condition
20307   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20308   // number of jumps the most.
20309
20310   if (isCMOVPseudo(MI)) {
20311     // See if we have a string of CMOVS with the same condition.
20312     while (NextMIIt != BB->end() &&
20313            isCMOVPseudo(NextMIIt) &&
20314            (NextMIIt->getOperand(3).getImm() == CC ||
20315             NextMIIt->getOperand(3).getImm() == OppCC)) {
20316       LastCMOV = &*NextMIIt;
20317       ++NextMIIt;
20318     }
20319   }
20320
20321   // This checks for case 2, but only do this if we didn't already find
20322   // case 1, as indicated by LastCMOV == MI.
20323   if (LastCMOV == MI &&
20324       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20325       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20326       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20327     CascadedCMOV = &*NextMIIt;
20328   }
20329
20330   MachineBasicBlock *jcc1MBB = nullptr;
20331
20332   // If we have a cascaded CMOV, we lower it to two successive branches to
20333   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20334   if (CascadedCMOV) {
20335     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20336     F->insert(It, jcc1MBB);
20337     jcc1MBB->addLiveIn(X86::EFLAGS);
20338   }
20339
20340   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20341   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20342   F->insert(It, copy0MBB);
20343   F->insert(It, sinkMBB);
20344
20345   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20346   // live into the sink and copy blocks.
20347   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20348
20349   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20350   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20351       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20352     copy0MBB->addLiveIn(X86::EFLAGS);
20353     sinkMBB->addLiveIn(X86::EFLAGS);
20354   }
20355
20356   // Transfer the remainder of BB and its successor edges to sinkMBB.
20357   sinkMBB->splice(sinkMBB->begin(), BB,
20358                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20359   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20360
20361   // Add the true and fallthrough blocks as its successors.
20362   if (CascadedCMOV) {
20363     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20364     BB->addSuccessor(jcc1MBB);
20365
20366     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20367     // jump to the sinkMBB.
20368     jcc1MBB->addSuccessor(copy0MBB);
20369     jcc1MBB->addSuccessor(sinkMBB);
20370   } else {
20371     BB->addSuccessor(copy0MBB);
20372   }
20373
20374   // The true block target of the first (or only) branch is always sinkMBB.
20375   BB->addSuccessor(sinkMBB);
20376
20377   // Create the conditional branch instruction.
20378   unsigned Opc = X86::GetCondBranchFromCond(CC);
20379   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20380
20381   if (CascadedCMOV) {
20382     unsigned Opc2 = X86::GetCondBranchFromCond(
20383         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20384     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20385   }
20386
20387   //  copy0MBB:
20388   //   %FalseValue = ...
20389   //   # fallthrough to sinkMBB
20390   copy0MBB->addSuccessor(sinkMBB);
20391
20392   //  sinkMBB:
20393   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20394   //  ...
20395   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20396   MachineBasicBlock::iterator MIItEnd =
20397     std::next(MachineBasicBlock::iterator(LastCMOV));
20398   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20399   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20400   MachineInstrBuilder MIB;
20401
20402   // As we are creating the PHIs, we have to be careful if there is more than
20403   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20404   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20405   // That also means that PHI construction must work forward from earlier to
20406   // later, and that the code must maintain a mapping from earlier PHI's
20407   // destination registers, and the registers that went into the PHI.
20408
20409   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20410     unsigned DestReg = MIIt->getOperand(0).getReg();
20411     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20412     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20413
20414     // If this CMOV we are generating is the opposite condition from
20415     // the jump we generated, then we have to swap the operands for the
20416     // PHI that is going to be generated.
20417     if (MIIt->getOperand(3).getImm() == OppCC)
20418         std::swap(Op1Reg, Op2Reg);
20419
20420     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20421       Op1Reg = RegRewriteTable[Op1Reg].first;
20422
20423     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20424       Op2Reg = RegRewriteTable[Op2Reg].second;
20425
20426     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20427                   TII->get(X86::PHI), DestReg)
20428           .addReg(Op1Reg).addMBB(copy0MBB)
20429           .addReg(Op2Reg).addMBB(thisMBB);
20430
20431     // Add this PHI to the rewrite table.
20432     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20433   }
20434
20435   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20436   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20437   if (CascadedCMOV) {
20438     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20439     // Copy the PHI result to the register defined by the second CMOV.
20440     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20441             DL, TII->get(TargetOpcode::COPY),
20442             CascadedCMOV->getOperand(0).getReg())
20443         .addReg(MI->getOperand(0).getReg());
20444     CascadedCMOV->eraseFromParent();
20445   }
20446
20447   // Now remove the CMOV(s).
20448   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20449     (MIIt++)->eraseFromParent();
20450
20451   return sinkMBB;
20452 }
20453
20454 MachineBasicBlock *
20455 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20456                                        MachineBasicBlock *BB) const {
20457   // Combine the following atomic floating-point modification pattern:
20458   //   a.store(reg OP a.load(acquire), release)
20459   // Transform them into:
20460   //   OPss (%gpr), %xmm
20461   //   movss %xmm, (%gpr)
20462   // Or sd equivalent for 64-bit operations.
20463   unsigned MOp, FOp;
20464   switch (MI->getOpcode()) {
20465   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20466   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20467   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20468   }
20469   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20470   DebugLoc DL = MI->getDebugLoc();
20471   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20472   unsigned MSrc = MI->getOperand(0).getReg();
20473   unsigned VSrc = MI->getOperand(5).getReg();
20474   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20475                                 .addReg(/*Base=*/MSrc)
20476                                 .addImm(/*Scale=*/1)
20477                                 .addReg(/*Index=*/0)
20478                                 .addImm(0)
20479                                 .addReg(0);
20480   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20481                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20482                           .addReg(VSrc)
20483                           .addReg(/*Base=*/MSrc)
20484                           .addImm(/*Scale=*/1)
20485                           .addReg(/*Index=*/0)
20486                           .addImm(/*Disp=*/0)
20487                           .addReg(/*Segment=*/0);
20488   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20489   MI->eraseFromParent(); // The pseudo instruction is gone now.
20490   return BB;
20491 }
20492
20493 MachineBasicBlock *
20494 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20495                                         MachineBasicBlock *BB) const {
20496   MachineFunction *MF = BB->getParent();
20497   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20498   DebugLoc DL = MI->getDebugLoc();
20499   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20500
20501   assert(MF->shouldSplitStack());
20502
20503   const bool Is64Bit = Subtarget->is64Bit();
20504   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20505
20506   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20507   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20508
20509   // BB:
20510   //  ... [Till the alloca]
20511   // If stacklet is not large enough, jump to mallocMBB
20512   //
20513   // bumpMBB:
20514   //  Allocate by subtracting from RSP
20515   //  Jump to continueMBB
20516   //
20517   // mallocMBB:
20518   //  Allocate by call to runtime
20519   //
20520   // continueMBB:
20521   //  ...
20522   //  [rest of original BB]
20523   //
20524
20525   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20526   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20527   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20528
20529   MachineRegisterInfo &MRI = MF->getRegInfo();
20530   const TargetRegisterClass *AddrRegClass =
20531       getRegClassFor(getPointerTy(MF->getDataLayout()));
20532
20533   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20534     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20535     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20536     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20537     sizeVReg = MI->getOperand(1).getReg(),
20538     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20539
20540   MachineFunction::iterator MBBIter = BB;
20541   ++MBBIter;
20542
20543   MF->insert(MBBIter, bumpMBB);
20544   MF->insert(MBBIter, mallocMBB);
20545   MF->insert(MBBIter, continueMBB);
20546
20547   continueMBB->splice(continueMBB->begin(), BB,
20548                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20549   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20550
20551   // Add code to the main basic block to check if the stack limit has been hit,
20552   // and if so, jump to mallocMBB otherwise to bumpMBB.
20553   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20554   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20555     .addReg(tmpSPVReg).addReg(sizeVReg);
20556   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20557     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20558     .addReg(SPLimitVReg);
20559   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20560
20561   // bumpMBB simply decreases the stack pointer, since we know the current
20562   // stacklet has enough space.
20563   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20564     .addReg(SPLimitVReg);
20565   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20566     .addReg(SPLimitVReg);
20567   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20568
20569   // Calls into a routine in libgcc to allocate more space from the heap.
20570   const uint32_t *RegMask =
20571       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20572   if (IsLP64) {
20573     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20574       .addReg(sizeVReg);
20575     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20576       .addExternalSymbol("__morestack_allocate_stack_space")
20577       .addRegMask(RegMask)
20578       .addReg(X86::RDI, RegState::Implicit)
20579       .addReg(X86::RAX, RegState::ImplicitDefine);
20580   } else if (Is64Bit) {
20581     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20582       .addReg(sizeVReg);
20583     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20584       .addExternalSymbol("__morestack_allocate_stack_space")
20585       .addRegMask(RegMask)
20586       .addReg(X86::EDI, RegState::Implicit)
20587       .addReg(X86::EAX, RegState::ImplicitDefine);
20588   } else {
20589     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20590       .addImm(12);
20591     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20592     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20593       .addExternalSymbol("__morestack_allocate_stack_space")
20594       .addRegMask(RegMask)
20595       .addReg(X86::EAX, RegState::ImplicitDefine);
20596   }
20597
20598   if (!Is64Bit)
20599     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20600       .addImm(16);
20601
20602   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20603     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20604   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20605
20606   // Set up the CFG correctly.
20607   BB->addSuccessor(bumpMBB);
20608   BB->addSuccessor(mallocMBB);
20609   mallocMBB->addSuccessor(continueMBB);
20610   bumpMBB->addSuccessor(continueMBB);
20611
20612   // Take care of the PHI nodes.
20613   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20614           MI->getOperand(0).getReg())
20615     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20616     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20617
20618   // Delete the original pseudo instruction.
20619   MI->eraseFromParent();
20620
20621   // And we're done.
20622   return continueMBB;
20623 }
20624
20625 MachineBasicBlock *
20626 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20627                                         MachineBasicBlock *BB) const {
20628   DebugLoc DL = MI->getDebugLoc();
20629
20630   assert(!Subtarget->isTargetMachO());
20631
20632   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20633                                                     DL);
20634
20635   MI->eraseFromParent();   // The pseudo instruction is gone now.
20636   return BB;
20637 }
20638
20639 MachineBasicBlock *
20640 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20641                                       MachineBasicBlock *BB) const {
20642   // This is pretty easy.  We're taking the value that we received from
20643   // our load from the relocation, sticking it in either RDI (x86-64)
20644   // or EAX and doing an indirect call.  The return value will then
20645   // be in the normal return register.
20646   MachineFunction *F = BB->getParent();
20647   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20648   DebugLoc DL = MI->getDebugLoc();
20649
20650   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20651   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20652
20653   // Get a register mask for the lowered call.
20654   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20655   // proper register mask.
20656   const uint32_t *RegMask =
20657       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20658   if (Subtarget->is64Bit()) {
20659     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20660                                       TII->get(X86::MOV64rm), X86::RDI)
20661     .addReg(X86::RIP)
20662     .addImm(0).addReg(0)
20663     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20664                       MI->getOperand(3).getTargetFlags())
20665     .addReg(0);
20666     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20667     addDirectMem(MIB, X86::RDI);
20668     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20669   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20670     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20671                                       TII->get(X86::MOV32rm), X86::EAX)
20672     .addReg(0)
20673     .addImm(0).addReg(0)
20674     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20675                       MI->getOperand(3).getTargetFlags())
20676     .addReg(0);
20677     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20678     addDirectMem(MIB, X86::EAX);
20679     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20680   } else {
20681     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20682                                       TII->get(X86::MOV32rm), X86::EAX)
20683     .addReg(TII->getGlobalBaseReg(F))
20684     .addImm(0).addReg(0)
20685     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20686                       MI->getOperand(3).getTargetFlags())
20687     .addReg(0);
20688     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20689     addDirectMem(MIB, X86::EAX);
20690     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20691   }
20692
20693   MI->eraseFromParent(); // The pseudo instruction is gone now.
20694   return BB;
20695 }
20696
20697 MachineBasicBlock *
20698 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20699                                     MachineBasicBlock *MBB) const {
20700   DebugLoc DL = MI->getDebugLoc();
20701   MachineFunction *MF = MBB->getParent();
20702   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20703   MachineRegisterInfo &MRI = MF->getRegInfo();
20704
20705   const BasicBlock *BB = MBB->getBasicBlock();
20706   MachineFunction::iterator I = MBB;
20707   ++I;
20708
20709   // Memory Reference
20710   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20711   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20712
20713   unsigned DstReg;
20714   unsigned MemOpndSlot = 0;
20715
20716   unsigned CurOp = 0;
20717
20718   DstReg = MI->getOperand(CurOp++).getReg();
20719   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20720   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20721   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20722   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20723
20724   MemOpndSlot = CurOp;
20725
20726   MVT PVT = getPointerTy(MF->getDataLayout());
20727   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20728          "Invalid Pointer Size!");
20729
20730   // For v = setjmp(buf), we generate
20731   //
20732   // thisMBB:
20733   //  buf[LabelOffset] = restoreMBB
20734   //  SjLjSetup restoreMBB
20735   //
20736   // mainMBB:
20737   //  v_main = 0
20738   //
20739   // sinkMBB:
20740   //  v = phi(main, restore)
20741   //
20742   // restoreMBB:
20743   //  if base pointer being used, load it from frame
20744   //  v_restore = 1
20745
20746   MachineBasicBlock *thisMBB = MBB;
20747   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20748   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20749   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20750   MF->insert(I, mainMBB);
20751   MF->insert(I, sinkMBB);
20752   MF->push_back(restoreMBB);
20753
20754   MachineInstrBuilder MIB;
20755
20756   // Transfer the remainder of BB and its successor edges to sinkMBB.
20757   sinkMBB->splice(sinkMBB->begin(), MBB,
20758                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20759   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20760
20761   // thisMBB:
20762   unsigned PtrStoreOpc = 0;
20763   unsigned LabelReg = 0;
20764   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20765   Reloc::Model RM = MF->getTarget().getRelocationModel();
20766   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20767                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20768
20769   // Prepare IP either in reg or imm.
20770   if (!UseImmLabel) {
20771     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20772     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20773     LabelReg = MRI.createVirtualRegister(PtrRC);
20774     if (Subtarget->is64Bit()) {
20775       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20776               .addReg(X86::RIP)
20777               .addImm(0)
20778               .addReg(0)
20779               .addMBB(restoreMBB)
20780               .addReg(0);
20781     } else {
20782       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20783       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20784               .addReg(XII->getGlobalBaseReg(MF))
20785               .addImm(0)
20786               .addReg(0)
20787               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20788               .addReg(0);
20789     }
20790   } else
20791     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20792   // Store IP
20793   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20794   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20795     if (i == X86::AddrDisp)
20796       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20797     else
20798       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20799   }
20800   if (!UseImmLabel)
20801     MIB.addReg(LabelReg);
20802   else
20803     MIB.addMBB(restoreMBB);
20804   MIB.setMemRefs(MMOBegin, MMOEnd);
20805   // Setup
20806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20807           .addMBB(restoreMBB);
20808
20809   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20810   MIB.addRegMask(RegInfo->getNoPreservedMask());
20811   thisMBB->addSuccessor(mainMBB);
20812   thisMBB->addSuccessor(restoreMBB);
20813
20814   // mainMBB:
20815   //  EAX = 0
20816   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20817   mainMBB->addSuccessor(sinkMBB);
20818
20819   // sinkMBB:
20820   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20821           TII->get(X86::PHI), DstReg)
20822     .addReg(mainDstReg).addMBB(mainMBB)
20823     .addReg(restoreDstReg).addMBB(restoreMBB);
20824
20825   // restoreMBB:
20826   if (RegInfo->hasBasePointer(*MF)) {
20827     const bool Uses64BitFramePtr =
20828         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20829     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20830     X86FI->setRestoreBasePointer(MF);
20831     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20832     unsigned BasePtr = RegInfo->getBaseRegister();
20833     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20834     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20835                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20836       .setMIFlag(MachineInstr::FrameSetup);
20837   }
20838   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20839   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20840   restoreMBB->addSuccessor(sinkMBB);
20841
20842   MI->eraseFromParent();
20843   return sinkMBB;
20844 }
20845
20846 MachineBasicBlock *
20847 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20848                                      MachineBasicBlock *MBB) const {
20849   DebugLoc DL = MI->getDebugLoc();
20850   MachineFunction *MF = MBB->getParent();
20851   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20852   MachineRegisterInfo &MRI = MF->getRegInfo();
20853
20854   // Memory Reference
20855   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20856   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20857
20858   MVT PVT = getPointerTy(MF->getDataLayout());
20859   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20860          "Invalid Pointer Size!");
20861
20862   const TargetRegisterClass *RC =
20863     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20864   unsigned Tmp = MRI.createVirtualRegister(RC);
20865   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20866   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20867   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20868   unsigned SP = RegInfo->getStackRegister();
20869
20870   MachineInstrBuilder MIB;
20871
20872   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20873   const int64_t SPOffset = 2 * PVT.getStoreSize();
20874
20875   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20876   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20877
20878   // Reload FP
20879   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20880   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20881     MIB.addOperand(MI->getOperand(i));
20882   MIB.setMemRefs(MMOBegin, MMOEnd);
20883   // Reload IP
20884   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20885   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20886     if (i == X86::AddrDisp)
20887       MIB.addDisp(MI->getOperand(i), LabelOffset);
20888     else
20889       MIB.addOperand(MI->getOperand(i));
20890   }
20891   MIB.setMemRefs(MMOBegin, MMOEnd);
20892   // Reload SP
20893   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20894   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20895     if (i == X86::AddrDisp)
20896       MIB.addDisp(MI->getOperand(i), SPOffset);
20897     else
20898       MIB.addOperand(MI->getOperand(i));
20899   }
20900   MIB.setMemRefs(MMOBegin, MMOEnd);
20901   // Jump
20902   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20903
20904   MI->eraseFromParent();
20905   return MBB;
20906 }
20907
20908 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20909 // accumulator loops. Writing back to the accumulator allows the coalescer
20910 // to remove extra copies in the loop.
20911 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20912 MachineBasicBlock *
20913 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20914                                  MachineBasicBlock *MBB) const {
20915   MachineOperand &AddendOp = MI->getOperand(3);
20916
20917   // Bail out early if the addend isn't a register - we can't switch these.
20918   if (!AddendOp.isReg())
20919     return MBB;
20920
20921   MachineFunction &MF = *MBB->getParent();
20922   MachineRegisterInfo &MRI = MF.getRegInfo();
20923
20924   // Check whether the addend is defined by a PHI:
20925   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20926   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20927   if (!AddendDef.isPHI())
20928     return MBB;
20929
20930   // Look for the following pattern:
20931   // loop:
20932   //   %addend = phi [%entry, 0], [%loop, %result]
20933   //   ...
20934   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20935
20936   // Replace with:
20937   //   loop:
20938   //   %addend = phi [%entry, 0], [%loop, %result]
20939   //   ...
20940   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20941
20942   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20943     assert(AddendDef.getOperand(i).isReg());
20944     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20945     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20946     if (&PHISrcInst == MI) {
20947       // Found a matching instruction.
20948       unsigned NewFMAOpc = 0;
20949       switch (MI->getOpcode()) {
20950         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20951         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20952         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20953         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20954         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20955         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20956         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20957         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20958         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20959         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20960         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20961         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20962         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20963         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20964         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20965         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20966         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20967         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20968         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20969         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20970
20971         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20972         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20973         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20974         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20975         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20976         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20977         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20978         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20979         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20980         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20981         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20982         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20983         default: llvm_unreachable("Unrecognized FMA variant.");
20984       }
20985
20986       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20987       MachineInstrBuilder MIB =
20988         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20989         .addOperand(MI->getOperand(0))
20990         .addOperand(MI->getOperand(3))
20991         .addOperand(MI->getOperand(2))
20992         .addOperand(MI->getOperand(1));
20993       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20994       MI->eraseFromParent();
20995     }
20996   }
20997
20998   return MBB;
20999 }
21000
21001 MachineBasicBlock *
21002 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21003                                                MachineBasicBlock *BB) const {
21004   switch (MI->getOpcode()) {
21005   default: llvm_unreachable("Unexpected instr type to insert");
21006   case X86::TAILJMPd64:
21007   case X86::TAILJMPr64:
21008   case X86::TAILJMPm64:
21009   case X86::TAILJMPd64_REX:
21010   case X86::TAILJMPr64_REX:
21011   case X86::TAILJMPm64_REX:
21012     llvm_unreachable("TAILJMP64 would not be touched here.");
21013   case X86::TCRETURNdi64:
21014   case X86::TCRETURNri64:
21015   case X86::TCRETURNmi64:
21016     return BB;
21017   case X86::WIN_ALLOCA:
21018     return EmitLoweredWinAlloca(MI, BB);
21019   case X86::SEG_ALLOCA_32:
21020   case X86::SEG_ALLOCA_64:
21021     return EmitLoweredSegAlloca(MI, BB);
21022   case X86::TLSCall_32:
21023   case X86::TLSCall_64:
21024     return EmitLoweredTLSCall(MI, BB);
21025   case X86::CMOV_FR32:
21026   case X86::CMOV_FR64:
21027   case X86::CMOV_GR8:
21028   case X86::CMOV_GR16:
21029   case X86::CMOV_GR32:
21030   case X86::CMOV_RFP32:
21031   case X86::CMOV_RFP64:
21032   case X86::CMOV_RFP80:
21033   case X86::CMOV_V2F64:
21034   case X86::CMOV_V2I64:
21035   case X86::CMOV_V4F32:
21036   case X86::CMOV_V4F64:
21037   case X86::CMOV_V4I64:
21038   case X86::CMOV_V16F32:
21039   case X86::CMOV_V8F32:
21040   case X86::CMOV_V8F64:
21041   case X86::CMOV_V8I64:
21042   case X86::CMOV_V8I1:
21043   case X86::CMOV_V16I1:
21044   case X86::CMOV_V32I1:
21045   case X86::CMOV_V64I1:
21046     return EmitLoweredSelect(MI, BB);
21047
21048   case X86::RELEASE_FADD32mr:
21049   case X86::RELEASE_FADD64mr:
21050     return EmitLoweredAtomicFP(MI, BB);
21051
21052   case X86::FP32_TO_INT16_IN_MEM:
21053   case X86::FP32_TO_INT32_IN_MEM:
21054   case X86::FP32_TO_INT64_IN_MEM:
21055   case X86::FP64_TO_INT16_IN_MEM:
21056   case X86::FP64_TO_INT32_IN_MEM:
21057   case X86::FP64_TO_INT64_IN_MEM:
21058   case X86::FP80_TO_INT16_IN_MEM:
21059   case X86::FP80_TO_INT32_IN_MEM:
21060   case X86::FP80_TO_INT64_IN_MEM: {
21061     MachineFunction *F = BB->getParent();
21062     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21063     DebugLoc DL = MI->getDebugLoc();
21064
21065     // Change the floating point control register to use "round towards zero"
21066     // mode when truncating to an integer value.
21067     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21068     addFrameReference(BuildMI(*BB, MI, DL,
21069                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21070
21071     // Load the old value of the high byte of the control word...
21072     unsigned OldCW =
21073       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21074     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21075                       CWFrameIdx);
21076
21077     // Set the high part to be round to zero...
21078     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21079       .addImm(0xC7F);
21080
21081     // Reload the modified control word now...
21082     addFrameReference(BuildMI(*BB, MI, DL,
21083                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21084
21085     // Restore the memory image of control word to original value
21086     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21087       .addReg(OldCW);
21088
21089     // Get the X86 opcode to use.
21090     unsigned Opc;
21091     switch (MI->getOpcode()) {
21092     default: llvm_unreachable("illegal opcode!");
21093     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21094     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21095     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21096     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21097     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21098     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21099     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21100     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21101     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21102     }
21103
21104     X86AddressMode AM;
21105     MachineOperand &Op = MI->getOperand(0);
21106     if (Op.isReg()) {
21107       AM.BaseType = X86AddressMode::RegBase;
21108       AM.Base.Reg = Op.getReg();
21109     } else {
21110       AM.BaseType = X86AddressMode::FrameIndexBase;
21111       AM.Base.FrameIndex = Op.getIndex();
21112     }
21113     Op = MI->getOperand(1);
21114     if (Op.isImm())
21115       AM.Scale = Op.getImm();
21116     Op = MI->getOperand(2);
21117     if (Op.isImm())
21118       AM.IndexReg = Op.getImm();
21119     Op = MI->getOperand(3);
21120     if (Op.isGlobal()) {
21121       AM.GV = Op.getGlobal();
21122     } else {
21123       AM.Disp = Op.getImm();
21124     }
21125     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21126                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21127
21128     // Reload the original control word now.
21129     addFrameReference(BuildMI(*BB, MI, DL,
21130                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21131
21132     MI->eraseFromParent();   // The pseudo instruction is gone now.
21133     return BB;
21134   }
21135     // String/text processing lowering.
21136   case X86::PCMPISTRM128REG:
21137   case X86::VPCMPISTRM128REG:
21138   case X86::PCMPISTRM128MEM:
21139   case X86::VPCMPISTRM128MEM:
21140   case X86::PCMPESTRM128REG:
21141   case X86::VPCMPESTRM128REG:
21142   case X86::PCMPESTRM128MEM:
21143   case X86::VPCMPESTRM128MEM:
21144     assert(Subtarget->hasSSE42() &&
21145            "Target must have SSE4.2 or AVX features enabled");
21146     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21147
21148   // String/text processing lowering.
21149   case X86::PCMPISTRIREG:
21150   case X86::VPCMPISTRIREG:
21151   case X86::PCMPISTRIMEM:
21152   case X86::VPCMPISTRIMEM:
21153   case X86::PCMPESTRIREG:
21154   case X86::VPCMPESTRIREG:
21155   case X86::PCMPESTRIMEM:
21156   case X86::VPCMPESTRIMEM:
21157     assert(Subtarget->hasSSE42() &&
21158            "Target must have SSE4.2 or AVX features enabled");
21159     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21160
21161   // Thread synchronization.
21162   case X86::MONITOR:
21163     return EmitMonitor(MI, BB, Subtarget);
21164
21165   // xbegin
21166   case X86::XBEGIN:
21167     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21168
21169   case X86::VASTART_SAVE_XMM_REGS:
21170     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21171
21172   case X86::VAARG_64:
21173     return EmitVAARG64WithCustomInserter(MI, BB);
21174
21175   case X86::EH_SjLj_SetJmp32:
21176   case X86::EH_SjLj_SetJmp64:
21177     return emitEHSjLjSetJmp(MI, BB);
21178
21179   case X86::EH_SjLj_LongJmp32:
21180   case X86::EH_SjLj_LongJmp64:
21181     return emitEHSjLjLongJmp(MI, BB);
21182
21183   case TargetOpcode::STATEPOINT:
21184     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21185     // this point in the process.  We diverge later.
21186     return emitPatchPoint(MI, BB);
21187
21188   case TargetOpcode::STACKMAP:
21189   case TargetOpcode::PATCHPOINT:
21190     return emitPatchPoint(MI, BB);
21191
21192   case X86::VFMADDPDr213r:
21193   case X86::VFMADDPSr213r:
21194   case X86::VFMADDSDr213r:
21195   case X86::VFMADDSSr213r:
21196   case X86::VFMSUBPDr213r:
21197   case X86::VFMSUBPSr213r:
21198   case X86::VFMSUBSDr213r:
21199   case X86::VFMSUBSSr213r:
21200   case X86::VFNMADDPDr213r:
21201   case X86::VFNMADDPSr213r:
21202   case X86::VFNMADDSDr213r:
21203   case X86::VFNMADDSSr213r:
21204   case X86::VFNMSUBPDr213r:
21205   case X86::VFNMSUBPSr213r:
21206   case X86::VFNMSUBSDr213r:
21207   case X86::VFNMSUBSSr213r:
21208   case X86::VFMADDSUBPDr213r:
21209   case X86::VFMADDSUBPSr213r:
21210   case X86::VFMSUBADDPDr213r:
21211   case X86::VFMSUBADDPSr213r:
21212   case X86::VFMADDPDr213rY:
21213   case X86::VFMADDPSr213rY:
21214   case X86::VFMSUBPDr213rY:
21215   case X86::VFMSUBPSr213rY:
21216   case X86::VFNMADDPDr213rY:
21217   case X86::VFNMADDPSr213rY:
21218   case X86::VFNMSUBPDr213rY:
21219   case X86::VFNMSUBPSr213rY:
21220   case X86::VFMADDSUBPDr213rY:
21221   case X86::VFMADDSUBPSr213rY:
21222   case X86::VFMSUBADDPDr213rY:
21223   case X86::VFMSUBADDPSr213rY:
21224     return emitFMA3Instr(MI, BB);
21225   }
21226 }
21227
21228 //===----------------------------------------------------------------------===//
21229 //                           X86 Optimization Hooks
21230 //===----------------------------------------------------------------------===//
21231
21232 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21233                                                       APInt &KnownZero,
21234                                                       APInt &KnownOne,
21235                                                       const SelectionDAG &DAG,
21236                                                       unsigned Depth) const {
21237   unsigned BitWidth = KnownZero.getBitWidth();
21238   unsigned Opc = Op.getOpcode();
21239   assert((Opc >= ISD::BUILTIN_OP_END ||
21240           Opc == ISD::INTRINSIC_WO_CHAIN ||
21241           Opc == ISD::INTRINSIC_W_CHAIN ||
21242           Opc == ISD::INTRINSIC_VOID) &&
21243          "Should use MaskedValueIsZero if you don't know whether Op"
21244          " is a target node!");
21245
21246   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21247   switch (Opc) {
21248   default: break;
21249   case X86ISD::ADD:
21250   case X86ISD::SUB:
21251   case X86ISD::ADC:
21252   case X86ISD::SBB:
21253   case X86ISD::SMUL:
21254   case X86ISD::UMUL:
21255   case X86ISD::INC:
21256   case X86ISD::DEC:
21257   case X86ISD::OR:
21258   case X86ISD::XOR:
21259   case X86ISD::AND:
21260     // These nodes' second result is a boolean.
21261     if (Op.getResNo() == 0)
21262       break;
21263     // Fallthrough
21264   case X86ISD::SETCC:
21265     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21266     break;
21267   case ISD::INTRINSIC_WO_CHAIN: {
21268     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21269     unsigned NumLoBits = 0;
21270     switch (IntId) {
21271     default: break;
21272     case Intrinsic::x86_sse_movmsk_ps:
21273     case Intrinsic::x86_avx_movmsk_ps_256:
21274     case Intrinsic::x86_sse2_movmsk_pd:
21275     case Intrinsic::x86_avx_movmsk_pd_256:
21276     case Intrinsic::x86_mmx_pmovmskb:
21277     case Intrinsic::x86_sse2_pmovmskb_128:
21278     case Intrinsic::x86_avx2_pmovmskb: {
21279       // High bits of movmskp{s|d}, pmovmskb are known zero.
21280       switch (IntId) {
21281         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21282         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21283         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21284         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21285         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21286         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21287         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21288         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21289       }
21290       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21291       break;
21292     }
21293     }
21294     break;
21295   }
21296   }
21297 }
21298
21299 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21300   SDValue Op,
21301   const SelectionDAG &,
21302   unsigned Depth) const {
21303   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21304   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21305     return Op.getValueType().getScalarType().getSizeInBits();
21306
21307   // Fallback case.
21308   return 1;
21309 }
21310
21311 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21312 /// node is a GlobalAddress + offset.
21313 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21314                                        const GlobalValue* &GA,
21315                                        int64_t &Offset) const {
21316   if (N->getOpcode() == X86ISD::Wrapper) {
21317     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21318       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21319       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21320       return true;
21321     }
21322   }
21323   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21324 }
21325
21326 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21327 /// same as extracting the high 128-bit part of 256-bit vector and then
21328 /// inserting the result into the low part of a new 256-bit vector
21329 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21330   EVT VT = SVOp->getValueType(0);
21331   unsigned NumElems = VT.getVectorNumElements();
21332
21333   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21334   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21335     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21336         SVOp->getMaskElt(j) >= 0)
21337       return false;
21338
21339   return true;
21340 }
21341
21342 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21343 /// same as extracting the low 128-bit part of 256-bit vector and then
21344 /// inserting the result into the high part of a new 256-bit vector
21345 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21346   EVT VT = SVOp->getValueType(0);
21347   unsigned NumElems = VT.getVectorNumElements();
21348
21349   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21350   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21351     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21352         SVOp->getMaskElt(j) >= 0)
21353       return false;
21354
21355   return true;
21356 }
21357
21358 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21359 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21360                                         TargetLowering::DAGCombinerInfo &DCI,
21361                                         const X86Subtarget* Subtarget) {
21362   SDLoc dl(N);
21363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21364   SDValue V1 = SVOp->getOperand(0);
21365   SDValue V2 = SVOp->getOperand(1);
21366   EVT VT = SVOp->getValueType(0);
21367   unsigned NumElems = VT.getVectorNumElements();
21368
21369   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21370       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21371     //
21372     //                   0,0,0,...
21373     //                      |
21374     //    V      UNDEF    BUILD_VECTOR    UNDEF
21375     //     \      /           \           /
21376     //  CONCAT_VECTOR         CONCAT_VECTOR
21377     //         \                  /
21378     //          \                /
21379     //          RESULT: V + zero extended
21380     //
21381     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21382         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21383         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21384       return SDValue();
21385
21386     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21387       return SDValue();
21388
21389     // To match the shuffle mask, the first half of the mask should
21390     // be exactly the first vector, and all the rest a splat with the
21391     // first element of the second one.
21392     for (unsigned i = 0; i != NumElems/2; ++i)
21393       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21394           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21395         return SDValue();
21396
21397     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21398     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21399       if (Ld->hasNUsesOfValue(1, 0)) {
21400         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21401         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21402         SDValue ResNode =
21403           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21404                                   Ld->getMemoryVT(),
21405                                   Ld->getPointerInfo(),
21406                                   Ld->getAlignment(),
21407                                   false/*isVolatile*/, true/*ReadMem*/,
21408                                   false/*WriteMem*/);
21409
21410         // Make sure the newly-created LOAD is in the same position as Ld in
21411         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21412         // and update uses of Ld's output chain to use the TokenFactor.
21413         if (Ld->hasAnyUseOfValue(1)) {
21414           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21415                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21416           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21417           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21418                                  SDValue(ResNode.getNode(), 1));
21419         }
21420
21421         return DAG.getBitcast(VT, ResNode);
21422       }
21423     }
21424
21425     // Emit a zeroed vector and insert the desired subvector on its
21426     // first half.
21427     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21428     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21429     return DCI.CombineTo(N, InsV);
21430   }
21431
21432   //===--------------------------------------------------------------------===//
21433   // Combine some shuffles into subvector extracts and inserts:
21434   //
21435
21436   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21437   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21438     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21439     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21440     return DCI.CombineTo(N, InsV);
21441   }
21442
21443   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21444   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21445     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21446     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21447     return DCI.CombineTo(N, InsV);
21448   }
21449
21450   return SDValue();
21451 }
21452
21453 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21454 /// possible.
21455 ///
21456 /// This is the leaf of the recursive combinine below. When we have found some
21457 /// chain of single-use x86 shuffle instructions and accumulated the combined
21458 /// shuffle mask represented by them, this will try to pattern match that mask
21459 /// into either a single instruction if there is a special purpose instruction
21460 /// for this operation, or into a PSHUFB instruction which is a fully general
21461 /// instruction but should only be used to replace chains over a certain depth.
21462 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21463                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21464                                    TargetLowering::DAGCombinerInfo &DCI,
21465                                    const X86Subtarget *Subtarget) {
21466   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21467
21468   // Find the operand that enters the chain. Note that multiple uses are OK
21469   // here, we're not going to remove the operand we find.
21470   SDValue Input = Op.getOperand(0);
21471   while (Input.getOpcode() == ISD::BITCAST)
21472     Input = Input.getOperand(0);
21473
21474   MVT VT = Input.getSimpleValueType();
21475   MVT RootVT = Root.getSimpleValueType();
21476   SDLoc DL(Root);
21477
21478   // Just remove no-op shuffle masks.
21479   if (Mask.size() == 1) {
21480     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21481                   /*AddTo*/ true);
21482     return true;
21483   }
21484
21485   // Use the float domain if the operand type is a floating point type.
21486   bool FloatDomain = VT.isFloatingPoint();
21487
21488   // For floating point shuffles, we don't have free copies in the shuffle
21489   // instructions or the ability to load as part of the instruction, so
21490   // canonicalize their shuffles to UNPCK or MOV variants.
21491   //
21492   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21493   // vectors because it can have a load folded into it that UNPCK cannot. This
21494   // doesn't preclude something switching to the shorter encoding post-RA.
21495   //
21496   // FIXME: Should teach these routines about AVX vector widths.
21497   if (FloatDomain && VT.getSizeInBits() == 128) {
21498     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21499       bool Lo = Mask.equals({0, 0});
21500       unsigned Shuffle;
21501       MVT ShuffleVT;
21502       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21503       // is no slower than UNPCKLPD but has the option to fold the input operand
21504       // into even an unaligned memory load.
21505       if (Lo && Subtarget->hasSSE3()) {
21506         Shuffle = X86ISD::MOVDDUP;
21507         ShuffleVT = MVT::v2f64;
21508       } else {
21509         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21510         // than the UNPCK variants.
21511         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21512         ShuffleVT = MVT::v4f32;
21513       }
21514       if (Depth == 1 && Root->getOpcode() == Shuffle)
21515         return false; // Nothing to do!
21516       Op = DAG.getBitcast(ShuffleVT, Input);
21517       DCI.AddToWorklist(Op.getNode());
21518       if (Shuffle == X86ISD::MOVDDUP)
21519         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21520       else
21521         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21522       DCI.AddToWorklist(Op.getNode());
21523       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21524                     /*AddTo*/ true);
21525       return true;
21526     }
21527     if (Subtarget->hasSSE3() &&
21528         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21529       bool Lo = Mask.equals({0, 0, 2, 2});
21530       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21531       MVT ShuffleVT = MVT::v4f32;
21532       if (Depth == 1 && Root->getOpcode() == Shuffle)
21533         return false; // Nothing to do!
21534       Op = DAG.getBitcast(ShuffleVT, Input);
21535       DCI.AddToWorklist(Op.getNode());
21536       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21537       DCI.AddToWorklist(Op.getNode());
21538       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21539                     /*AddTo*/ true);
21540       return true;
21541     }
21542     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21543       bool Lo = Mask.equals({0, 0, 1, 1});
21544       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21545       MVT ShuffleVT = MVT::v4f32;
21546       if (Depth == 1 && Root->getOpcode() == Shuffle)
21547         return false; // Nothing to do!
21548       Op = DAG.getBitcast(ShuffleVT, Input);
21549       DCI.AddToWorklist(Op.getNode());
21550       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21551       DCI.AddToWorklist(Op.getNode());
21552       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21553                     /*AddTo*/ true);
21554       return true;
21555     }
21556   }
21557
21558   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21559   // variants as none of these have single-instruction variants that are
21560   // superior to the UNPCK formulation.
21561   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21562       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21563        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21564        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21565        Mask.equals(
21566            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21567     bool Lo = Mask[0] == 0;
21568     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21569     if (Depth == 1 && Root->getOpcode() == Shuffle)
21570       return false; // Nothing to do!
21571     MVT ShuffleVT;
21572     switch (Mask.size()) {
21573     case 8:
21574       ShuffleVT = MVT::v8i16;
21575       break;
21576     case 16:
21577       ShuffleVT = MVT::v16i8;
21578       break;
21579     default:
21580       llvm_unreachable("Impossible mask size!");
21581     };
21582     Op = DAG.getBitcast(ShuffleVT, Input);
21583     DCI.AddToWorklist(Op.getNode());
21584     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21585     DCI.AddToWorklist(Op.getNode());
21586     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21587                   /*AddTo*/ true);
21588     return true;
21589   }
21590
21591   // Don't try to re-form single instruction chains under any circumstances now
21592   // that we've done encoding canonicalization for them.
21593   if (Depth < 2)
21594     return false;
21595
21596   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21597   // can replace them with a single PSHUFB instruction profitably. Intel's
21598   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21599   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21600   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21601     SmallVector<SDValue, 16> PSHUFBMask;
21602     int NumBytes = VT.getSizeInBits() / 8;
21603     int Ratio = NumBytes / Mask.size();
21604     for (int i = 0; i < NumBytes; ++i) {
21605       if (Mask[i / Ratio] == SM_SentinelUndef) {
21606         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21607         continue;
21608       }
21609       int M = Mask[i / Ratio] != SM_SentinelZero
21610                   ? Ratio * Mask[i / Ratio] + i % Ratio
21611                   : 255;
21612       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21613     }
21614     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21615     Op = DAG.getBitcast(ByteVT, Input);
21616     DCI.AddToWorklist(Op.getNode());
21617     SDValue PSHUFBMaskOp =
21618         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21619     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21620     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21621     DCI.AddToWorklist(Op.getNode());
21622     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21623                   /*AddTo*/ true);
21624     return true;
21625   }
21626
21627   // Failed to find any combines.
21628   return false;
21629 }
21630
21631 /// \brief Fully generic combining of x86 shuffle instructions.
21632 ///
21633 /// This should be the last combine run over the x86 shuffle instructions. Once
21634 /// they have been fully optimized, this will recursively consider all chains
21635 /// of single-use shuffle instructions, build a generic model of the cumulative
21636 /// shuffle operation, and check for simpler instructions which implement this
21637 /// operation. We use this primarily for two purposes:
21638 ///
21639 /// 1) Collapse generic shuffles to specialized single instructions when
21640 ///    equivalent. In most cases, this is just an encoding size win, but
21641 ///    sometimes we will collapse multiple generic shuffles into a single
21642 ///    special-purpose shuffle.
21643 /// 2) Look for sequences of shuffle instructions with 3 or more total
21644 ///    instructions, and replace them with the slightly more expensive SSSE3
21645 ///    PSHUFB instruction if available. We do this as the last combining step
21646 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21647 ///    a suitable short sequence of other instructions. The PHUFB will either
21648 ///    use a register or have to read from memory and so is slightly (but only
21649 ///    slightly) more expensive than the other shuffle instructions.
21650 ///
21651 /// Because this is inherently a quadratic operation (for each shuffle in
21652 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21653 /// This should never be an issue in practice as the shuffle lowering doesn't
21654 /// produce sequences of more than 8 instructions.
21655 ///
21656 /// FIXME: We will currently miss some cases where the redundant shuffling
21657 /// would simplify under the threshold for PSHUFB formation because of
21658 /// combine-ordering. To fix this, we should do the redundant instruction
21659 /// combining in this recursive walk.
21660 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21661                                           ArrayRef<int> RootMask,
21662                                           int Depth, bool HasPSHUFB,
21663                                           SelectionDAG &DAG,
21664                                           TargetLowering::DAGCombinerInfo &DCI,
21665                                           const X86Subtarget *Subtarget) {
21666   // Bound the depth of our recursive combine because this is ultimately
21667   // quadratic in nature.
21668   if (Depth > 8)
21669     return false;
21670
21671   // Directly rip through bitcasts to find the underlying operand.
21672   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21673     Op = Op.getOperand(0);
21674
21675   MVT VT = Op.getSimpleValueType();
21676   if (!VT.isVector())
21677     return false; // Bail if we hit a non-vector.
21678
21679   assert(Root.getSimpleValueType().isVector() &&
21680          "Shuffles operate on vector types!");
21681   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21682          "Can only combine shuffles of the same vector register size.");
21683
21684   if (!isTargetShuffle(Op.getOpcode()))
21685     return false;
21686   SmallVector<int, 16> OpMask;
21687   bool IsUnary;
21688   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21689   // We only can combine unary shuffles which we can decode the mask for.
21690   if (!HaveMask || !IsUnary)
21691     return false;
21692
21693   assert(VT.getVectorNumElements() == OpMask.size() &&
21694          "Different mask size from vector size!");
21695   assert(((RootMask.size() > OpMask.size() &&
21696            RootMask.size() % OpMask.size() == 0) ||
21697           (OpMask.size() > RootMask.size() &&
21698            OpMask.size() % RootMask.size() == 0) ||
21699           OpMask.size() == RootMask.size()) &&
21700          "The smaller number of elements must divide the larger.");
21701   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21702   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21703   assert(((RootRatio == 1 && OpRatio == 1) ||
21704           (RootRatio == 1) != (OpRatio == 1)) &&
21705          "Must not have a ratio for both incoming and op masks!");
21706
21707   SmallVector<int, 16> Mask;
21708   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21709
21710   // Merge this shuffle operation's mask into our accumulated mask. Note that
21711   // this shuffle's mask will be the first applied to the input, followed by the
21712   // root mask to get us all the way to the root value arrangement. The reason
21713   // for this order is that we are recursing up the operation chain.
21714   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21715     int RootIdx = i / RootRatio;
21716     if (RootMask[RootIdx] < 0) {
21717       // This is a zero or undef lane, we're done.
21718       Mask.push_back(RootMask[RootIdx]);
21719       continue;
21720     }
21721
21722     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21723     int OpIdx = RootMaskedIdx / OpRatio;
21724     if (OpMask[OpIdx] < 0) {
21725       // The incoming lanes are zero or undef, it doesn't matter which ones we
21726       // are using.
21727       Mask.push_back(OpMask[OpIdx]);
21728       continue;
21729     }
21730
21731     // Ok, we have non-zero lanes, map them through.
21732     Mask.push_back(OpMask[OpIdx] * OpRatio +
21733                    RootMaskedIdx % OpRatio);
21734   }
21735
21736   // See if we can recurse into the operand to combine more things.
21737   switch (Op.getOpcode()) {
21738     case X86ISD::PSHUFB:
21739       HasPSHUFB = true;
21740     case X86ISD::PSHUFD:
21741     case X86ISD::PSHUFHW:
21742     case X86ISD::PSHUFLW:
21743       if (Op.getOperand(0).hasOneUse() &&
21744           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21745                                         HasPSHUFB, DAG, DCI, Subtarget))
21746         return true;
21747       break;
21748
21749     case X86ISD::UNPCKL:
21750     case X86ISD::UNPCKH:
21751       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21752       // We can't check for single use, we have to check that this shuffle is the only user.
21753       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21754           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21755                                         HasPSHUFB, DAG, DCI, Subtarget))
21756           return true;
21757       break;
21758   }
21759
21760   // Minor canonicalization of the accumulated shuffle mask to make it easier
21761   // to match below. All this does is detect masks with squential pairs of
21762   // elements, and shrink them to the half-width mask. It does this in a loop
21763   // so it will reduce the size of the mask to the minimal width mask which
21764   // performs an equivalent shuffle.
21765   SmallVector<int, 16> WidenedMask;
21766   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21767     Mask = std::move(WidenedMask);
21768     WidenedMask.clear();
21769   }
21770
21771   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21772                                 Subtarget);
21773 }
21774
21775 /// \brief Get the PSHUF-style mask from PSHUF node.
21776 ///
21777 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21778 /// PSHUF-style masks that can be reused with such instructions.
21779 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21780   MVT VT = N.getSimpleValueType();
21781   SmallVector<int, 4> Mask;
21782   bool IsUnary;
21783   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21784   (void)HaveMask;
21785   assert(HaveMask);
21786
21787   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21788   // matter. Check that the upper masks are repeats and remove them.
21789   if (VT.getSizeInBits() > 128) {
21790     int LaneElts = 128 / VT.getScalarSizeInBits();
21791 #ifndef NDEBUG
21792     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21793       for (int j = 0; j < LaneElts; ++j)
21794         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21795                "Mask doesn't repeat in high 128-bit lanes!");
21796 #endif
21797     Mask.resize(LaneElts);
21798   }
21799
21800   switch (N.getOpcode()) {
21801   case X86ISD::PSHUFD:
21802     return Mask;
21803   case X86ISD::PSHUFLW:
21804     Mask.resize(4);
21805     return Mask;
21806   case X86ISD::PSHUFHW:
21807     Mask.erase(Mask.begin(), Mask.begin() + 4);
21808     for (int &M : Mask)
21809       M -= 4;
21810     return Mask;
21811   default:
21812     llvm_unreachable("No valid shuffle instruction found!");
21813   }
21814 }
21815
21816 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21817 ///
21818 /// We walk up the chain and look for a combinable shuffle, skipping over
21819 /// shuffles that we could hoist this shuffle's transformation past without
21820 /// altering anything.
21821 static SDValue
21822 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21823                              SelectionDAG &DAG,
21824                              TargetLowering::DAGCombinerInfo &DCI) {
21825   assert(N.getOpcode() == X86ISD::PSHUFD &&
21826          "Called with something other than an x86 128-bit half shuffle!");
21827   SDLoc DL(N);
21828
21829   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21830   // of the shuffles in the chain so that we can form a fresh chain to replace
21831   // this one.
21832   SmallVector<SDValue, 8> Chain;
21833   SDValue V = N.getOperand(0);
21834   for (; V.hasOneUse(); V = V.getOperand(0)) {
21835     switch (V.getOpcode()) {
21836     default:
21837       return SDValue(); // Nothing combined!
21838
21839     case ISD::BITCAST:
21840       // Skip bitcasts as we always know the type for the target specific
21841       // instructions.
21842       continue;
21843
21844     case X86ISD::PSHUFD:
21845       // Found another dword shuffle.
21846       break;
21847
21848     case X86ISD::PSHUFLW:
21849       // Check that the low words (being shuffled) are the identity in the
21850       // dword shuffle, and the high words are self-contained.
21851       if (Mask[0] != 0 || Mask[1] != 1 ||
21852           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21853         return SDValue();
21854
21855       Chain.push_back(V);
21856       continue;
21857
21858     case X86ISD::PSHUFHW:
21859       // Check that the high words (being shuffled) are the identity in the
21860       // dword shuffle, and the low words are self-contained.
21861       if (Mask[2] != 2 || Mask[3] != 3 ||
21862           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21863         return SDValue();
21864
21865       Chain.push_back(V);
21866       continue;
21867
21868     case X86ISD::UNPCKL:
21869     case X86ISD::UNPCKH:
21870       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21871       // shuffle into a preceding word shuffle.
21872       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21873           V.getSimpleValueType().getScalarType() != MVT::i16)
21874         return SDValue();
21875
21876       // Search for a half-shuffle which we can combine with.
21877       unsigned CombineOp =
21878           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21879       if (V.getOperand(0) != V.getOperand(1) ||
21880           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21881         return SDValue();
21882       Chain.push_back(V);
21883       V = V.getOperand(0);
21884       do {
21885         switch (V.getOpcode()) {
21886         default:
21887           return SDValue(); // Nothing to combine.
21888
21889         case X86ISD::PSHUFLW:
21890         case X86ISD::PSHUFHW:
21891           if (V.getOpcode() == CombineOp)
21892             break;
21893
21894           Chain.push_back(V);
21895
21896           // Fallthrough!
21897         case ISD::BITCAST:
21898           V = V.getOperand(0);
21899           continue;
21900         }
21901         break;
21902       } while (V.hasOneUse());
21903       break;
21904     }
21905     // Break out of the loop if we break out of the switch.
21906     break;
21907   }
21908
21909   if (!V.hasOneUse())
21910     // We fell out of the loop without finding a viable combining instruction.
21911     return SDValue();
21912
21913   // Merge this node's mask and our incoming mask.
21914   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21915   for (int &M : Mask)
21916     M = VMask[M];
21917   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21918                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21919
21920   // Rebuild the chain around this new shuffle.
21921   while (!Chain.empty()) {
21922     SDValue W = Chain.pop_back_val();
21923
21924     if (V.getValueType() != W.getOperand(0).getValueType())
21925       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21926
21927     switch (W.getOpcode()) {
21928     default:
21929       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21930
21931     case X86ISD::UNPCKL:
21932     case X86ISD::UNPCKH:
21933       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21934       break;
21935
21936     case X86ISD::PSHUFD:
21937     case X86ISD::PSHUFLW:
21938     case X86ISD::PSHUFHW:
21939       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21940       break;
21941     }
21942   }
21943   if (V.getValueType() != N.getValueType())
21944     V = DAG.getBitcast(N.getValueType(), V);
21945
21946   // Return the new chain to replace N.
21947   return V;
21948 }
21949
21950 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21951 ///
21952 /// We walk up the chain, skipping shuffles of the other half and looking
21953 /// through shuffles which switch halves trying to find a shuffle of the same
21954 /// pair of dwords.
21955 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21956                                         SelectionDAG &DAG,
21957                                         TargetLowering::DAGCombinerInfo &DCI) {
21958   assert(
21959       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21960       "Called with something other than an x86 128-bit half shuffle!");
21961   SDLoc DL(N);
21962   unsigned CombineOpcode = N.getOpcode();
21963
21964   // Walk up a single-use chain looking for a combinable shuffle.
21965   SDValue V = N.getOperand(0);
21966   for (; V.hasOneUse(); V = V.getOperand(0)) {
21967     switch (V.getOpcode()) {
21968     default:
21969       return false; // Nothing combined!
21970
21971     case ISD::BITCAST:
21972       // Skip bitcasts as we always know the type for the target specific
21973       // instructions.
21974       continue;
21975
21976     case X86ISD::PSHUFLW:
21977     case X86ISD::PSHUFHW:
21978       if (V.getOpcode() == CombineOpcode)
21979         break;
21980
21981       // Other-half shuffles are no-ops.
21982       continue;
21983     }
21984     // Break out of the loop if we break out of the switch.
21985     break;
21986   }
21987
21988   if (!V.hasOneUse())
21989     // We fell out of the loop without finding a viable combining instruction.
21990     return false;
21991
21992   // Combine away the bottom node as its shuffle will be accumulated into
21993   // a preceding shuffle.
21994   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21995
21996   // Record the old value.
21997   SDValue Old = V;
21998
21999   // Merge this node's mask and our incoming mask (adjusted to account for all
22000   // the pshufd instructions encountered).
22001   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22002   for (int &M : Mask)
22003     M = VMask[M];
22004   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22005                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22006
22007   // Check that the shuffles didn't cancel each other out. If not, we need to
22008   // combine to the new one.
22009   if (Old != V)
22010     // Replace the combinable shuffle with the combined one, updating all users
22011     // so that we re-evaluate the chain here.
22012     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22013
22014   return true;
22015 }
22016
22017 /// \brief Try to combine x86 target specific shuffles.
22018 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22019                                            TargetLowering::DAGCombinerInfo &DCI,
22020                                            const X86Subtarget *Subtarget) {
22021   SDLoc DL(N);
22022   MVT VT = N.getSimpleValueType();
22023   SmallVector<int, 4> Mask;
22024
22025   switch (N.getOpcode()) {
22026   case X86ISD::PSHUFD:
22027   case X86ISD::PSHUFLW:
22028   case X86ISD::PSHUFHW:
22029     Mask = getPSHUFShuffleMask(N);
22030     assert(Mask.size() == 4);
22031     break;
22032   default:
22033     return SDValue();
22034   }
22035
22036   // Nuke no-op shuffles that show up after combining.
22037   if (isNoopShuffleMask(Mask))
22038     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22039
22040   // Look for simplifications involving one or two shuffle instructions.
22041   SDValue V = N.getOperand(0);
22042   switch (N.getOpcode()) {
22043   default:
22044     break;
22045   case X86ISD::PSHUFLW:
22046   case X86ISD::PSHUFHW:
22047     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22048
22049     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22050       return SDValue(); // We combined away this shuffle, so we're done.
22051
22052     // See if this reduces to a PSHUFD which is no more expensive and can
22053     // combine with more operations. Note that it has to at least flip the
22054     // dwords as otherwise it would have been removed as a no-op.
22055     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22056       int DMask[] = {0, 1, 2, 3};
22057       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22058       DMask[DOffset + 0] = DOffset + 1;
22059       DMask[DOffset + 1] = DOffset + 0;
22060       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22061       V = DAG.getBitcast(DVT, V);
22062       DCI.AddToWorklist(V.getNode());
22063       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22064                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22065       DCI.AddToWorklist(V.getNode());
22066       return DAG.getBitcast(VT, V);
22067     }
22068
22069     // Look for shuffle patterns which can be implemented as a single unpack.
22070     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22071     // only works when we have a PSHUFD followed by two half-shuffles.
22072     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22073         (V.getOpcode() == X86ISD::PSHUFLW ||
22074          V.getOpcode() == X86ISD::PSHUFHW) &&
22075         V.getOpcode() != N.getOpcode() &&
22076         V.hasOneUse()) {
22077       SDValue D = V.getOperand(0);
22078       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22079         D = D.getOperand(0);
22080       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22081         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22082         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22083         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22084         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22085         int WordMask[8];
22086         for (int i = 0; i < 4; ++i) {
22087           WordMask[i + NOffset] = Mask[i] + NOffset;
22088           WordMask[i + VOffset] = VMask[i] + VOffset;
22089         }
22090         // Map the word mask through the DWord mask.
22091         int MappedMask[8];
22092         for (int i = 0; i < 8; ++i)
22093           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22094         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22095             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22096           // We can replace all three shuffles with an unpack.
22097           V = DAG.getBitcast(VT, D.getOperand(0));
22098           DCI.AddToWorklist(V.getNode());
22099           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22100                                                 : X86ISD::UNPCKH,
22101                              DL, VT, V, V);
22102         }
22103       }
22104     }
22105
22106     break;
22107
22108   case X86ISD::PSHUFD:
22109     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22110       return NewN;
22111
22112     break;
22113   }
22114
22115   return SDValue();
22116 }
22117
22118 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22119 ///
22120 /// We combine this directly on the abstract vector shuffle nodes so it is
22121 /// easier to generically match. We also insert dummy vector shuffle nodes for
22122 /// the operands which explicitly discard the lanes which are unused by this
22123 /// operation to try to flow through the rest of the combiner the fact that
22124 /// they're unused.
22125 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22126   SDLoc DL(N);
22127   EVT VT = N->getValueType(0);
22128
22129   // We only handle target-independent shuffles.
22130   // FIXME: It would be easy and harmless to use the target shuffle mask
22131   // extraction tool to support more.
22132   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22133     return SDValue();
22134
22135   auto *SVN = cast<ShuffleVectorSDNode>(N);
22136   ArrayRef<int> Mask = SVN->getMask();
22137   SDValue V1 = N->getOperand(0);
22138   SDValue V2 = N->getOperand(1);
22139
22140   // We require the first shuffle operand to be the SUB node, and the second to
22141   // be the ADD node.
22142   // FIXME: We should support the commuted patterns.
22143   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22144     return SDValue();
22145
22146   // If there are other uses of these operations we can't fold them.
22147   if (!V1->hasOneUse() || !V2->hasOneUse())
22148     return SDValue();
22149
22150   // Ensure that both operations have the same operands. Note that we can
22151   // commute the FADD operands.
22152   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22153   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22154       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22155     return SDValue();
22156
22157   // We're looking for blends between FADD and FSUB nodes. We insist on these
22158   // nodes being lined up in a specific expected pattern.
22159   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22160         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22161         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22162     return SDValue();
22163
22164   // Only specific types are legal at this point, assert so we notice if and
22165   // when these change.
22166   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22167           VT == MVT::v4f64) &&
22168          "Unknown vector type encountered!");
22169
22170   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22171 }
22172
22173 /// PerformShuffleCombine - Performs several different shuffle combines.
22174 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22175                                      TargetLowering::DAGCombinerInfo &DCI,
22176                                      const X86Subtarget *Subtarget) {
22177   SDLoc dl(N);
22178   SDValue N0 = N->getOperand(0);
22179   SDValue N1 = N->getOperand(1);
22180   EVT VT = N->getValueType(0);
22181
22182   // Don't create instructions with illegal types after legalize types has run.
22183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22184   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22185     return SDValue();
22186
22187   // If we have legalized the vector types, look for blends of FADD and FSUB
22188   // nodes that we can fuse into an ADDSUB node.
22189   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22190     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22191       return AddSub;
22192
22193   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22194   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22195       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22196     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22197
22198   // During Type Legalization, when promoting illegal vector types,
22199   // the backend might introduce new shuffle dag nodes and bitcasts.
22200   //
22201   // This code performs the following transformation:
22202   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22203   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22204   //
22205   // We do this only if both the bitcast and the BINOP dag nodes have
22206   // one use. Also, perform this transformation only if the new binary
22207   // operation is legal. This is to avoid introducing dag nodes that
22208   // potentially need to be further expanded (or custom lowered) into a
22209   // less optimal sequence of dag nodes.
22210   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22211       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22212       N0.getOpcode() == ISD::BITCAST) {
22213     SDValue BC0 = N0.getOperand(0);
22214     EVT SVT = BC0.getValueType();
22215     unsigned Opcode = BC0.getOpcode();
22216     unsigned NumElts = VT.getVectorNumElements();
22217
22218     if (BC0.hasOneUse() && SVT.isVector() &&
22219         SVT.getVectorNumElements() * 2 == NumElts &&
22220         TLI.isOperationLegal(Opcode, VT)) {
22221       bool CanFold = false;
22222       switch (Opcode) {
22223       default : break;
22224       case ISD::ADD :
22225       case ISD::FADD :
22226       case ISD::SUB :
22227       case ISD::FSUB :
22228       case ISD::MUL :
22229       case ISD::FMUL :
22230         CanFold = true;
22231       }
22232
22233       unsigned SVTNumElts = SVT.getVectorNumElements();
22234       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22235       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22236         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22237       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22238         CanFold = SVOp->getMaskElt(i) < 0;
22239
22240       if (CanFold) {
22241         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22242         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22243         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22244         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22245       }
22246     }
22247   }
22248
22249   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22250   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22251   // consecutive, non-overlapping, and in the right order.
22252   SmallVector<SDValue, 16> Elts;
22253   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22254     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22255
22256   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22257     return LD;
22258
22259   if (isTargetShuffle(N->getOpcode())) {
22260     SDValue Shuffle =
22261         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22262     if (Shuffle.getNode())
22263       return Shuffle;
22264
22265     // Try recursively combining arbitrary sequences of x86 shuffle
22266     // instructions into higher-order shuffles. We do this after combining
22267     // specific PSHUF instruction sequences into their minimal form so that we
22268     // can evaluate how many specialized shuffle instructions are involved in
22269     // a particular chain.
22270     SmallVector<int, 1> NonceMask; // Just a placeholder.
22271     NonceMask.push_back(0);
22272     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22273                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22274                                       DCI, Subtarget))
22275       return SDValue(); // This routine will use CombineTo to replace N.
22276   }
22277
22278   return SDValue();
22279 }
22280
22281 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22282 /// specific shuffle of a load can be folded into a single element load.
22283 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22284 /// shuffles have been custom lowered so we need to handle those here.
22285 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22286                                          TargetLowering::DAGCombinerInfo &DCI) {
22287   if (DCI.isBeforeLegalizeOps())
22288     return SDValue();
22289
22290   SDValue InVec = N->getOperand(0);
22291   SDValue EltNo = N->getOperand(1);
22292
22293   if (!isa<ConstantSDNode>(EltNo))
22294     return SDValue();
22295
22296   EVT OriginalVT = InVec.getValueType();
22297
22298   if (InVec.getOpcode() == ISD::BITCAST) {
22299     // Don't duplicate a load with other uses.
22300     if (!InVec.hasOneUse())
22301       return SDValue();
22302     EVT BCVT = InVec.getOperand(0).getValueType();
22303     if (!BCVT.isVector() ||
22304         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22305       return SDValue();
22306     InVec = InVec.getOperand(0);
22307   }
22308
22309   EVT CurrentVT = InVec.getValueType();
22310
22311   if (!isTargetShuffle(InVec.getOpcode()))
22312     return SDValue();
22313
22314   // Don't duplicate a load with other uses.
22315   if (!InVec.hasOneUse())
22316     return SDValue();
22317
22318   SmallVector<int, 16> ShuffleMask;
22319   bool UnaryShuffle;
22320   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22321                             ShuffleMask, UnaryShuffle))
22322     return SDValue();
22323
22324   // Select the input vector, guarding against out of range extract vector.
22325   unsigned NumElems = CurrentVT.getVectorNumElements();
22326   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22327   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22328   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22329                                          : InVec.getOperand(1);
22330
22331   // If inputs to shuffle are the same for both ops, then allow 2 uses
22332   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22333                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22334
22335   if (LdNode.getOpcode() == ISD::BITCAST) {
22336     // Don't duplicate a load with other uses.
22337     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22338       return SDValue();
22339
22340     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22341     LdNode = LdNode.getOperand(0);
22342   }
22343
22344   if (!ISD::isNormalLoad(LdNode.getNode()))
22345     return SDValue();
22346
22347   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22348
22349   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22350     return SDValue();
22351
22352   EVT EltVT = N->getValueType(0);
22353   // If there's a bitcast before the shuffle, check if the load type and
22354   // alignment is valid.
22355   unsigned Align = LN0->getAlignment();
22356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22357   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22358       EltVT.getTypeForEVT(*DAG.getContext()));
22359
22360   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22361     return SDValue();
22362
22363   // All checks match so transform back to vector_shuffle so that DAG combiner
22364   // can finish the job
22365   SDLoc dl(N);
22366
22367   // Create shuffle node taking into account the case that its a unary shuffle
22368   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22369                                    : InVec.getOperand(1);
22370   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22371                                  InVec.getOperand(0), Shuffle,
22372                                  &ShuffleMask[0]);
22373   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22374   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22375                      EltNo);
22376 }
22377
22378 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22379 /// special and don't usually play with other vector types, it's better to
22380 /// handle them early to be sure we emit efficient code by avoiding
22381 /// store-load conversions.
22382 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22383   if (N->getValueType(0) != MVT::x86mmx ||
22384       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22385       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22386     return SDValue();
22387
22388   SDValue V = N->getOperand(0);
22389   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22390   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22391     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22392                        N->getValueType(0), V.getOperand(0));
22393
22394   return SDValue();
22395 }
22396
22397 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22398 /// generation and convert it from being a bunch of shuffles and extracts
22399 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22400 /// storing the value and loading scalars back, while for x64 we should
22401 /// use 64-bit extracts and shifts.
22402 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22403                                          TargetLowering::DAGCombinerInfo &DCI) {
22404   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22405     return NewOp;
22406
22407   SDValue InputVector = N->getOperand(0);
22408   SDLoc dl(InputVector);
22409   // Detect mmx to i32 conversion through a v2i32 elt extract.
22410   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22411       N->getValueType(0) == MVT::i32 &&
22412       InputVector.getValueType() == MVT::v2i32) {
22413
22414     // The bitcast source is a direct mmx result.
22415     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22416     if (MMXSrc.getValueType() == MVT::x86mmx)
22417       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22418                          N->getValueType(0),
22419                          InputVector.getNode()->getOperand(0));
22420
22421     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22422     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22423     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22424         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22425         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22426         MMXSrcOp.getValueType() == MVT::v1i64 &&
22427         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22428       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22429                          N->getValueType(0),
22430                          MMXSrcOp.getOperand(0));
22431   }
22432
22433   EVT VT = N->getValueType(0);
22434
22435   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22436       InputVector.getOpcode() == ISD::BITCAST &&
22437       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22438     uint64_t ExtractedElt =
22439           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22440     uint64_t InputValue =
22441           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22442     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22443     return DAG.getConstant(Res, dl, MVT::i1);
22444   }
22445   // Only operate on vectors of 4 elements, where the alternative shuffling
22446   // gets to be more expensive.
22447   if (InputVector.getValueType() != MVT::v4i32)
22448     return SDValue();
22449
22450   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22451   // single use which is a sign-extend or zero-extend, and all elements are
22452   // used.
22453   SmallVector<SDNode *, 4> Uses;
22454   unsigned ExtractedElements = 0;
22455   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22456        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22457     if (UI.getUse().getResNo() != InputVector.getResNo())
22458       return SDValue();
22459
22460     SDNode *Extract = *UI;
22461     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22462       return SDValue();
22463
22464     if (Extract->getValueType(0) != MVT::i32)
22465       return SDValue();
22466     if (!Extract->hasOneUse())
22467       return SDValue();
22468     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22469         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22470       return SDValue();
22471     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22472       return SDValue();
22473
22474     // Record which element was extracted.
22475     ExtractedElements |=
22476       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22477
22478     Uses.push_back(Extract);
22479   }
22480
22481   // If not all the elements were used, this may not be worthwhile.
22482   if (ExtractedElements != 15)
22483     return SDValue();
22484
22485   // Ok, we've now decided to do the transformation.
22486   // If 64-bit shifts are legal, use the extract-shift sequence,
22487   // otherwise bounce the vector off the cache.
22488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22489   SDValue Vals[4];
22490
22491   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22492     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22493     auto &DL = DAG.getDataLayout();
22494     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22495     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22496       DAG.getConstant(0, dl, VecIdxTy));
22497     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22498       DAG.getConstant(1, dl, VecIdxTy));
22499
22500     SDValue ShAmt = DAG.getConstant(
22501         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22502     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22503     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22504       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22505     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22506     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22507       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22508   } else {
22509     // Store the value to a temporary stack slot.
22510     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22511     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22512       MachinePointerInfo(), false, false, 0);
22513
22514     EVT ElementType = InputVector.getValueType().getVectorElementType();
22515     unsigned EltSize = ElementType.getSizeInBits() / 8;
22516
22517     // Replace each use (extract) with a load of the appropriate element.
22518     for (unsigned i = 0; i < 4; ++i) {
22519       uint64_t Offset = EltSize * i;
22520       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22521       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22522
22523       SDValue ScalarAddr =
22524           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22525
22526       // Load the scalar.
22527       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22528                             ScalarAddr, MachinePointerInfo(),
22529                             false, false, false, 0);
22530
22531     }
22532   }
22533
22534   // Replace the extracts
22535   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22536     UE = Uses.end(); UI != UE; ++UI) {
22537     SDNode *Extract = *UI;
22538
22539     SDValue Idx = Extract->getOperand(1);
22540     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22541     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22542   }
22543
22544   // The replacement was made in place; don't return anything.
22545   return SDValue();
22546 }
22547
22548 static SDValue
22549 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22550                                       const X86Subtarget *Subtarget) {
22551   SDLoc dl(N);
22552   SDValue Cond = N->getOperand(0);
22553   SDValue LHS = N->getOperand(1);
22554   SDValue RHS = N->getOperand(2);
22555
22556   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22557     SDValue CondSrc = Cond->getOperand(0);
22558     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22559       Cond = CondSrc->getOperand(0);
22560   }
22561
22562   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22563     return SDValue();
22564
22565   // A vselect where all conditions and data are constants can be optimized into
22566   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22567   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22568       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22569     return SDValue();
22570
22571   unsigned MaskValue = 0;
22572   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22573     return SDValue();
22574
22575   MVT VT = N->getSimpleValueType(0);
22576   unsigned NumElems = VT.getVectorNumElements();
22577   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22578   for (unsigned i = 0; i < NumElems; ++i) {
22579     // Be sure we emit undef where we can.
22580     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22581       ShuffleMask[i] = -1;
22582     else
22583       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22584   }
22585
22586   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22587   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22588     return SDValue();
22589   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22590 }
22591
22592 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22593 /// nodes.
22594 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22595                                     TargetLowering::DAGCombinerInfo &DCI,
22596                                     const X86Subtarget *Subtarget) {
22597   SDLoc DL(N);
22598   SDValue Cond = N->getOperand(0);
22599   // Get the LHS/RHS of the select.
22600   SDValue LHS = N->getOperand(1);
22601   SDValue RHS = N->getOperand(2);
22602   EVT VT = LHS.getValueType();
22603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22604
22605   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22606   // instructions match the semantics of the common C idiom x<y?x:y but not
22607   // x<=y?x:y, because of how they handle negative zero (which can be
22608   // ignored in unsafe-math mode).
22609   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22610   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22611       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22612       (Subtarget->hasSSE2() ||
22613        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22614     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22615
22616     unsigned Opcode = 0;
22617     // Check for x CC y ? x : y.
22618     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22619         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22620       switch (CC) {
22621       default: break;
22622       case ISD::SETULT:
22623         // Converting this to a min would handle NaNs incorrectly, and swapping
22624         // the operands would cause it to handle comparisons between positive
22625         // and negative zero incorrectly.
22626         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22627           if (!DAG.getTarget().Options.UnsafeFPMath &&
22628               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22629             break;
22630           std::swap(LHS, RHS);
22631         }
22632         Opcode = X86ISD::FMIN;
22633         break;
22634       case ISD::SETOLE:
22635         // Converting this to a min would handle comparisons between positive
22636         // and negative zero incorrectly.
22637         if (!DAG.getTarget().Options.UnsafeFPMath &&
22638             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22639           break;
22640         Opcode = X86ISD::FMIN;
22641         break;
22642       case ISD::SETULE:
22643         // Converting this to a min would handle both negative zeros and NaNs
22644         // incorrectly, but we can swap the operands to fix both.
22645         std::swap(LHS, RHS);
22646       case ISD::SETOLT:
22647       case ISD::SETLT:
22648       case ISD::SETLE:
22649         Opcode = X86ISD::FMIN;
22650         break;
22651
22652       case ISD::SETOGE:
22653         // Converting this to a max would handle comparisons between positive
22654         // and negative zero incorrectly.
22655         if (!DAG.getTarget().Options.UnsafeFPMath &&
22656             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22657           break;
22658         Opcode = X86ISD::FMAX;
22659         break;
22660       case ISD::SETUGT:
22661         // Converting this to a max would handle NaNs incorrectly, and swapping
22662         // the operands would cause it to handle comparisons between positive
22663         // and negative zero incorrectly.
22664         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22665           if (!DAG.getTarget().Options.UnsafeFPMath &&
22666               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22667             break;
22668           std::swap(LHS, RHS);
22669         }
22670         Opcode = X86ISD::FMAX;
22671         break;
22672       case ISD::SETUGE:
22673         // Converting this to a max would handle both negative zeros and NaNs
22674         // incorrectly, but we can swap the operands to fix both.
22675         std::swap(LHS, RHS);
22676       case ISD::SETOGT:
22677       case ISD::SETGT:
22678       case ISD::SETGE:
22679         Opcode = X86ISD::FMAX;
22680         break;
22681       }
22682     // Check for x CC y ? y : x -- a min/max with reversed arms.
22683     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22684                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22685       switch (CC) {
22686       default: break;
22687       case ISD::SETOGE:
22688         // Converting this to a min would handle comparisons between positive
22689         // and negative zero incorrectly, and swapping the operands would
22690         // cause it to handle NaNs incorrectly.
22691         if (!DAG.getTarget().Options.UnsafeFPMath &&
22692             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22693           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22694             break;
22695           std::swap(LHS, RHS);
22696         }
22697         Opcode = X86ISD::FMIN;
22698         break;
22699       case ISD::SETUGT:
22700         // Converting this to a min would handle NaNs incorrectly.
22701         if (!DAG.getTarget().Options.UnsafeFPMath &&
22702             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22703           break;
22704         Opcode = X86ISD::FMIN;
22705         break;
22706       case ISD::SETUGE:
22707         // Converting this to a min would handle both negative zeros and NaNs
22708         // incorrectly, but we can swap the operands to fix both.
22709         std::swap(LHS, RHS);
22710       case ISD::SETOGT:
22711       case ISD::SETGT:
22712       case ISD::SETGE:
22713         Opcode = X86ISD::FMIN;
22714         break;
22715
22716       case ISD::SETULT:
22717         // Converting this to a max would handle NaNs incorrectly.
22718         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22719           break;
22720         Opcode = X86ISD::FMAX;
22721         break;
22722       case ISD::SETOLE:
22723         // Converting this to a max would handle comparisons between positive
22724         // and negative zero incorrectly, and swapping the operands would
22725         // cause it to handle NaNs incorrectly.
22726         if (!DAG.getTarget().Options.UnsafeFPMath &&
22727             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22728           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22729             break;
22730           std::swap(LHS, RHS);
22731         }
22732         Opcode = X86ISD::FMAX;
22733         break;
22734       case ISD::SETULE:
22735         // Converting this to a max would handle both negative zeros and NaNs
22736         // incorrectly, but we can swap the operands to fix both.
22737         std::swap(LHS, RHS);
22738       case ISD::SETOLT:
22739       case ISD::SETLT:
22740       case ISD::SETLE:
22741         Opcode = X86ISD::FMAX;
22742         break;
22743       }
22744     }
22745
22746     if (Opcode)
22747       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22748   }
22749
22750   EVT CondVT = Cond.getValueType();
22751   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22752       CondVT.getVectorElementType() == MVT::i1) {
22753     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22754     // lowering on KNL. In this case we convert it to
22755     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22756     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22757     // Since SKX these selects have a proper lowering.
22758     EVT OpVT = LHS.getValueType();
22759     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22760         (OpVT.getVectorElementType() == MVT::i8 ||
22761          OpVT.getVectorElementType() == MVT::i16) &&
22762         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22763       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22764       DCI.AddToWorklist(Cond.getNode());
22765       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22766     }
22767   }
22768   // If this is a select between two integer constants, try to do some
22769   // optimizations.
22770   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22771     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22772       // Don't do this for crazy integer types.
22773       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22774         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22775         // so that TrueC (the true value) is larger than FalseC.
22776         bool NeedsCondInvert = false;
22777
22778         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22779             // Efficiently invertible.
22780             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22781              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22782               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22783           NeedsCondInvert = true;
22784           std::swap(TrueC, FalseC);
22785         }
22786
22787         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22788         if (FalseC->getAPIntValue() == 0 &&
22789             TrueC->getAPIntValue().isPowerOf2()) {
22790           if (NeedsCondInvert) // Invert the condition if needed.
22791             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22792                                DAG.getConstant(1, DL, Cond.getValueType()));
22793
22794           // Zero extend the condition if needed.
22795           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22796
22797           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22798           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22799                              DAG.getConstant(ShAmt, DL, MVT::i8));
22800         }
22801
22802         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22803         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22804           if (NeedsCondInvert) // Invert the condition if needed.
22805             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22806                                DAG.getConstant(1, DL, Cond.getValueType()));
22807
22808           // Zero extend the condition if needed.
22809           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22810                              FalseC->getValueType(0), Cond);
22811           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22812                              SDValue(FalseC, 0));
22813         }
22814
22815         // Optimize cases that will turn into an LEA instruction.  This requires
22816         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22817         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22818           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22819           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22820
22821           bool isFastMultiplier = false;
22822           if (Diff < 10) {
22823             switch ((unsigned char)Diff) {
22824               default: break;
22825               case 1:  // result = add base, cond
22826               case 2:  // result = lea base(    , cond*2)
22827               case 3:  // result = lea base(cond, cond*2)
22828               case 4:  // result = lea base(    , cond*4)
22829               case 5:  // result = lea base(cond, cond*4)
22830               case 8:  // result = lea base(    , cond*8)
22831               case 9:  // result = lea base(cond, cond*8)
22832                 isFastMultiplier = true;
22833                 break;
22834             }
22835           }
22836
22837           if (isFastMultiplier) {
22838             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22839             if (NeedsCondInvert) // Invert the condition if needed.
22840               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22841                                  DAG.getConstant(1, DL, Cond.getValueType()));
22842
22843             // Zero extend the condition if needed.
22844             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22845                                Cond);
22846             // Scale the condition by the difference.
22847             if (Diff != 1)
22848               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22849                                  DAG.getConstant(Diff, DL,
22850                                                  Cond.getValueType()));
22851
22852             // Add the base if non-zero.
22853             if (FalseC->getAPIntValue() != 0)
22854               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22855                                  SDValue(FalseC, 0));
22856             return Cond;
22857           }
22858         }
22859       }
22860   }
22861
22862   // Canonicalize max and min:
22863   // (x > y) ? x : y -> (x >= y) ? x : y
22864   // (x < y) ? x : y -> (x <= y) ? x : y
22865   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22866   // the need for an extra compare
22867   // against zero. e.g.
22868   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22869   // subl   %esi, %edi
22870   // testl  %edi, %edi
22871   // movl   $0, %eax
22872   // cmovgl %edi, %eax
22873   // =>
22874   // xorl   %eax, %eax
22875   // subl   %esi, $edi
22876   // cmovsl %eax, %edi
22877   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22878       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22879       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22880     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22881     switch (CC) {
22882     default: break;
22883     case ISD::SETLT:
22884     case ISD::SETGT: {
22885       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22886       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22887                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22888       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22889     }
22890     }
22891   }
22892
22893   // Early exit check
22894   if (!TLI.isTypeLegal(VT))
22895     return SDValue();
22896
22897   // Match VSELECTs into subs with unsigned saturation.
22898   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22899       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22900       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22901        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22902     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22903
22904     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22905     // left side invert the predicate to simplify logic below.
22906     SDValue Other;
22907     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22908       Other = RHS;
22909       CC = ISD::getSetCCInverse(CC, true);
22910     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22911       Other = LHS;
22912     }
22913
22914     if (Other.getNode() && Other->getNumOperands() == 2 &&
22915         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22916       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22917       SDValue CondRHS = Cond->getOperand(1);
22918
22919       // Look for a general sub with unsigned saturation first.
22920       // x >= y ? x-y : 0 --> subus x, y
22921       // x >  y ? x-y : 0 --> subus x, y
22922       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22923           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22924         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22925
22926       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22927         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22928           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22929             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22930               // If the RHS is a constant we have to reverse the const
22931               // canonicalization.
22932               // x > C-1 ? x+-C : 0 --> subus x, C
22933               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22934                   CondRHSConst->getAPIntValue() ==
22935                       (-OpRHSConst->getAPIntValue() - 1))
22936                 return DAG.getNode(
22937                     X86ISD::SUBUS, DL, VT, OpLHS,
22938                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22939
22940           // Another special case: If C was a sign bit, the sub has been
22941           // canonicalized into a xor.
22942           // FIXME: Would it be better to use computeKnownBits to determine
22943           //        whether it's safe to decanonicalize the xor?
22944           // x s< 0 ? x^C : 0 --> subus x, C
22945           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22946               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22947               OpRHSConst->getAPIntValue().isSignBit())
22948             // Note that we have to rebuild the RHS constant here to ensure we
22949             // don't rely on particular values of undef lanes.
22950             return DAG.getNode(
22951                 X86ISD::SUBUS, DL, VT, OpLHS,
22952                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22953         }
22954     }
22955   }
22956
22957   // Simplify vector selection if condition value type matches vselect
22958   // operand type
22959   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22960     assert(Cond.getValueType().isVector() &&
22961            "vector select expects a vector selector!");
22962
22963     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22964     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22965
22966     // Try invert the condition if true value is not all 1s and false value
22967     // is not all 0s.
22968     if (!TValIsAllOnes && !FValIsAllZeros &&
22969         // Check if the selector will be produced by CMPP*/PCMP*
22970         Cond.getOpcode() == ISD::SETCC &&
22971         // Check if SETCC has already been promoted
22972         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22973             CondVT) {
22974       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22975       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22976
22977       if (TValIsAllZeros || FValIsAllOnes) {
22978         SDValue CC = Cond.getOperand(2);
22979         ISD::CondCode NewCC =
22980           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22981                                Cond.getOperand(0).getValueType().isInteger());
22982         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22983         std::swap(LHS, RHS);
22984         TValIsAllOnes = FValIsAllOnes;
22985         FValIsAllZeros = TValIsAllZeros;
22986       }
22987     }
22988
22989     if (TValIsAllOnes || FValIsAllZeros) {
22990       SDValue Ret;
22991
22992       if (TValIsAllOnes && FValIsAllZeros)
22993         Ret = Cond;
22994       else if (TValIsAllOnes)
22995         Ret =
22996             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22997       else if (FValIsAllZeros)
22998         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22999                           DAG.getBitcast(CondVT, LHS));
23000
23001       return DAG.getBitcast(VT, Ret);
23002     }
23003   }
23004
23005   // We should generate an X86ISD::BLENDI from a vselect if its argument
23006   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23007   // constants. This specific pattern gets generated when we split a
23008   // selector for a 512 bit vector in a machine without AVX512 (but with
23009   // 256-bit vectors), during legalization:
23010   //
23011   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23012   //
23013   // Iff we find this pattern and the build_vectors are built from
23014   // constants, we translate the vselect into a shuffle_vector that we
23015   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23016   if ((N->getOpcode() == ISD::VSELECT ||
23017        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23018       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23019     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23020     if (Shuffle.getNode())
23021       return Shuffle;
23022   }
23023
23024   // If this is a *dynamic* select (non-constant condition) and we can match
23025   // this node with one of the variable blend instructions, restructure the
23026   // condition so that the blends can use the high bit of each element and use
23027   // SimplifyDemandedBits to simplify the condition operand.
23028   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23029       !DCI.isBeforeLegalize() &&
23030       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23031     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23032
23033     // Don't optimize vector selects that map to mask-registers.
23034     if (BitWidth == 1)
23035       return SDValue();
23036
23037     // We can only handle the cases where VSELECT is directly legal on the
23038     // subtarget. We custom lower VSELECT nodes with constant conditions and
23039     // this makes it hard to see whether a dynamic VSELECT will correctly
23040     // lower, so we both check the operation's status and explicitly handle the
23041     // cases where a *dynamic* blend will fail even though a constant-condition
23042     // blend could be custom lowered.
23043     // FIXME: We should find a better way to handle this class of problems.
23044     // Potentially, we should combine constant-condition vselect nodes
23045     // pre-legalization into shuffles and not mark as many types as custom
23046     // lowered.
23047     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23048       return SDValue();
23049     // FIXME: We don't support i16-element blends currently. We could and
23050     // should support them by making *all* the bits in the condition be set
23051     // rather than just the high bit and using an i8-element blend.
23052     if (VT.getScalarType() == MVT::i16)
23053       return SDValue();
23054     // Dynamic blending was only available from SSE4.1 onward.
23055     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23056       return SDValue();
23057     // Byte blends are only available in AVX2
23058     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23059         !Subtarget->hasAVX2())
23060       return SDValue();
23061
23062     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23063     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23064
23065     APInt KnownZero, KnownOne;
23066     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23067                                           DCI.isBeforeLegalizeOps());
23068     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23069         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23070                                  TLO)) {
23071       // If we changed the computation somewhere in the DAG, this change
23072       // will affect all users of Cond.
23073       // Make sure it is fine and update all the nodes so that we do not
23074       // use the generic VSELECT anymore. Otherwise, we may perform
23075       // wrong optimizations as we messed up with the actual expectation
23076       // for the vector boolean values.
23077       if (Cond != TLO.Old) {
23078         // Check all uses of that condition operand to check whether it will be
23079         // consumed by non-BLEND instructions, which may depend on all bits are
23080         // set properly.
23081         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23082              I != E; ++I)
23083           if (I->getOpcode() != ISD::VSELECT)
23084             // TODO: Add other opcodes eventually lowered into BLEND.
23085             return SDValue();
23086
23087         // Update all the users of the condition, before committing the change,
23088         // so that the VSELECT optimizations that expect the correct vector
23089         // boolean value will not be triggered.
23090         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23091              I != E; ++I)
23092           DAG.ReplaceAllUsesOfValueWith(
23093               SDValue(*I, 0),
23094               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23095                           Cond, I->getOperand(1), I->getOperand(2)));
23096         DCI.CommitTargetLoweringOpt(TLO);
23097         return SDValue();
23098       }
23099       // At this point, only Cond is changed. Change the condition
23100       // just for N to keep the opportunity to optimize all other
23101       // users their own way.
23102       DAG.ReplaceAllUsesOfValueWith(
23103           SDValue(N, 0),
23104           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23105                       TLO.New, N->getOperand(1), N->getOperand(2)));
23106       return SDValue();
23107     }
23108   }
23109
23110   return SDValue();
23111 }
23112
23113 // Check whether a boolean test is testing a boolean value generated by
23114 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23115 // code.
23116 //
23117 // Simplify the following patterns:
23118 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23119 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23120 // to (Op EFLAGS Cond)
23121 //
23122 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23123 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23124 // to (Op EFLAGS !Cond)
23125 //
23126 // where Op could be BRCOND or CMOV.
23127 //
23128 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23129   // Quit if not CMP and SUB with its value result used.
23130   if (Cmp.getOpcode() != X86ISD::CMP &&
23131       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23132       return SDValue();
23133
23134   // Quit if not used as a boolean value.
23135   if (CC != X86::COND_E && CC != X86::COND_NE)
23136     return SDValue();
23137
23138   // Check CMP operands. One of them should be 0 or 1 and the other should be
23139   // an SetCC or extended from it.
23140   SDValue Op1 = Cmp.getOperand(0);
23141   SDValue Op2 = Cmp.getOperand(1);
23142
23143   SDValue SetCC;
23144   const ConstantSDNode* C = nullptr;
23145   bool needOppositeCond = (CC == X86::COND_E);
23146   bool checkAgainstTrue = false; // Is it a comparison against 1?
23147
23148   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23149     SetCC = Op2;
23150   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23151     SetCC = Op1;
23152   else // Quit if all operands are not constants.
23153     return SDValue();
23154
23155   if (C->getZExtValue() == 1) {
23156     needOppositeCond = !needOppositeCond;
23157     checkAgainstTrue = true;
23158   } else if (C->getZExtValue() != 0)
23159     // Quit if the constant is neither 0 or 1.
23160     return SDValue();
23161
23162   bool truncatedToBoolWithAnd = false;
23163   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23164   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23165          SetCC.getOpcode() == ISD::TRUNCATE ||
23166          SetCC.getOpcode() == ISD::AND) {
23167     if (SetCC.getOpcode() == ISD::AND) {
23168       int OpIdx = -1;
23169       ConstantSDNode *CS;
23170       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23171           CS->getZExtValue() == 1)
23172         OpIdx = 1;
23173       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23174           CS->getZExtValue() == 1)
23175         OpIdx = 0;
23176       if (OpIdx == -1)
23177         break;
23178       SetCC = SetCC.getOperand(OpIdx);
23179       truncatedToBoolWithAnd = true;
23180     } else
23181       SetCC = SetCC.getOperand(0);
23182   }
23183
23184   switch (SetCC.getOpcode()) {
23185   case X86ISD::SETCC_CARRY:
23186     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23187     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23188     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23189     // truncated to i1 using 'and'.
23190     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23191       break;
23192     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23193            "Invalid use of SETCC_CARRY!");
23194     // FALL THROUGH
23195   case X86ISD::SETCC:
23196     // Set the condition code or opposite one if necessary.
23197     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23198     if (needOppositeCond)
23199       CC = X86::GetOppositeBranchCondition(CC);
23200     return SetCC.getOperand(1);
23201   case X86ISD::CMOV: {
23202     // Check whether false/true value has canonical one, i.e. 0 or 1.
23203     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23204     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23205     // Quit if true value is not a constant.
23206     if (!TVal)
23207       return SDValue();
23208     // Quit if false value is not a constant.
23209     if (!FVal) {
23210       SDValue Op = SetCC.getOperand(0);
23211       // Skip 'zext' or 'trunc' node.
23212       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23213           Op.getOpcode() == ISD::TRUNCATE)
23214         Op = Op.getOperand(0);
23215       // A special case for rdrand/rdseed, where 0 is set if false cond is
23216       // found.
23217       if ((Op.getOpcode() != X86ISD::RDRAND &&
23218            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23219         return SDValue();
23220     }
23221     // Quit if false value is not the constant 0 or 1.
23222     bool FValIsFalse = true;
23223     if (FVal && FVal->getZExtValue() != 0) {
23224       if (FVal->getZExtValue() != 1)
23225         return SDValue();
23226       // If FVal is 1, opposite cond is needed.
23227       needOppositeCond = !needOppositeCond;
23228       FValIsFalse = false;
23229     }
23230     // Quit if TVal is not the constant opposite of FVal.
23231     if (FValIsFalse && TVal->getZExtValue() != 1)
23232       return SDValue();
23233     if (!FValIsFalse && TVal->getZExtValue() != 0)
23234       return SDValue();
23235     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23236     if (needOppositeCond)
23237       CC = X86::GetOppositeBranchCondition(CC);
23238     return SetCC.getOperand(3);
23239   }
23240   }
23241
23242   return SDValue();
23243 }
23244
23245 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23246 /// Match:
23247 ///   (X86or (X86setcc) (X86setcc))
23248 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23249 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23250                                            X86::CondCode &CC1, SDValue &Flags,
23251                                            bool &isAnd) {
23252   if (Cond->getOpcode() == X86ISD::CMP) {
23253     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23254     if (!CondOp1C || !CondOp1C->isNullValue())
23255       return false;
23256
23257     Cond = Cond->getOperand(0);
23258   }
23259
23260   isAnd = false;
23261
23262   SDValue SetCC0, SetCC1;
23263   switch (Cond->getOpcode()) {
23264   default: return false;
23265   case ISD::AND:
23266   case X86ISD::AND:
23267     isAnd = true;
23268     // fallthru
23269   case ISD::OR:
23270   case X86ISD::OR:
23271     SetCC0 = Cond->getOperand(0);
23272     SetCC1 = Cond->getOperand(1);
23273     break;
23274   };
23275
23276   // Make sure we have SETCC nodes, using the same flags value.
23277   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23278       SetCC1.getOpcode() != X86ISD::SETCC ||
23279       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23280     return false;
23281
23282   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23283   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23284   Flags = SetCC0->getOperand(1);
23285   return true;
23286 }
23287
23288 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23289 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23290                                   TargetLowering::DAGCombinerInfo &DCI,
23291                                   const X86Subtarget *Subtarget) {
23292   SDLoc DL(N);
23293
23294   // If the flag operand isn't dead, don't touch this CMOV.
23295   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23296     return SDValue();
23297
23298   SDValue FalseOp = N->getOperand(0);
23299   SDValue TrueOp = N->getOperand(1);
23300   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23301   SDValue Cond = N->getOperand(3);
23302
23303   if (CC == X86::COND_E || CC == X86::COND_NE) {
23304     switch (Cond.getOpcode()) {
23305     default: break;
23306     case X86ISD::BSR:
23307     case X86ISD::BSF:
23308       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23309       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23310         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23311     }
23312   }
23313
23314   SDValue Flags;
23315
23316   Flags = checkBoolTestSetCCCombine(Cond, CC);
23317   if (Flags.getNode() &&
23318       // Extra check as FCMOV only supports a subset of X86 cond.
23319       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23320     SDValue Ops[] = { FalseOp, TrueOp,
23321                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23322     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23323   }
23324
23325   // If this is a select between two integer constants, try to do some
23326   // optimizations.  Note that the operands are ordered the opposite of SELECT
23327   // operands.
23328   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23329     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23330       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23331       // larger than FalseC (the false value).
23332       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23333         CC = X86::GetOppositeBranchCondition(CC);
23334         std::swap(TrueC, FalseC);
23335         std::swap(TrueOp, FalseOp);
23336       }
23337
23338       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23339       // This is efficient for any integer data type (including i8/i16) and
23340       // shift amount.
23341       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23342         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23343                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23344
23345         // Zero extend the condition if needed.
23346         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23347
23348         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23349         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23350                            DAG.getConstant(ShAmt, DL, MVT::i8));
23351         if (N->getNumValues() == 2)  // Dead flag value?
23352           return DCI.CombineTo(N, Cond, SDValue());
23353         return Cond;
23354       }
23355
23356       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23357       // for any integer data type, including i8/i16.
23358       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23359         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23360                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23361
23362         // Zero extend the condition if needed.
23363         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23364                            FalseC->getValueType(0), Cond);
23365         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23366                            SDValue(FalseC, 0));
23367
23368         if (N->getNumValues() == 2)  // Dead flag value?
23369           return DCI.CombineTo(N, Cond, SDValue());
23370         return Cond;
23371       }
23372
23373       // Optimize cases that will turn into an LEA instruction.  This requires
23374       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23375       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23376         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23377         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23378
23379         bool isFastMultiplier = false;
23380         if (Diff < 10) {
23381           switch ((unsigned char)Diff) {
23382           default: break;
23383           case 1:  // result = add base, cond
23384           case 2:  // result = lea base(    , cond*2)
23385           case 3:  // result = lea base(cond, cond*2)
23386           case 4:  // result = lea base(    , cond*4)
23387           case 5:  // result = lea base(cond, cond*4)
23388           case 8:  // result = lea base(    , cond*8)
23389           case 9:  // result = lea base(cond, cond*8)
23390             isFastMultiplier = true;
23391             break;
23392           }
23393         }
23394
23395         if (isFastMultiplier) {
23396           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23397           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23398                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23399           // Zero extend the condition if needed.
23400           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23401                              Cond);
23402           // Scale the condition by the difference.
23403           if (Diff != 1)
23404             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23405                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23406
23407           // Add the base if non-zero.
23408           if (FalseC->getAPIntValue() != 0)
23409             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23410                                SDValue(FalseC, 0));
23411           if (N->getNumValues() == 2)  // Dead flag value?
23412             return DCI.CombineTo(N, Cond, SDValue());
23413           return Cond;
23414         }
23415       }
23416     }
23417   }
23418
23419   // Handle these cases:
23420   //   (select (x != c), e, c) -> select (x != c), e, x),
23421   //   (select (x == c), c, e) -> select (x == c), x, e)
23422   // where the c is an integer constant, and the "select" is the combination
23423   // of CMOV and CMP.
23424   //
23425   // The rationale for this change is that the conditional-move from a constant
23426   // needs two instructions, however, conditional-move from a register needs
23427   // only one instruction.
23428   //
23429   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23430   //  some instruction-combining opportunities. This opt needs to be
23431   //  postponed as late as possible.
23432   //
23433   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23434     // the DCI.xxxx conditions are provided to postpone the optimization as
23435     // late as possible.
23436
23437     ConstantSDNode *CmpAgainst = nullptr;
23438     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23439         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23440         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23441
23442       if (CC == X86::COND_NE &&
23443           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23444         CC = X86::GetOppositeBranchCondition(CC);
23445         std::swap(TrueOp, FalseOp);
23446       }
23447
23448       if (CC == X86::COND_E &&
23449           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23450         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23451                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23452         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23453       }
23454     }
23455   }
23456
23457   // Fold and/or of setcc's to double CMOV:
23458   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23459   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23460   //
23461   // This combine lets us generate:
23462   //   cmovcc1 (jcc1 if we don't have CMOV)
23463   //   cmovcc2 (same)
23464   // instead of:
23465   //   setcc1
23466   //   setcc2
23467   //   and/or
23468   //   cmovne (jne if we don't have CMOV)
23469   // When we can't use the CMOV instruction, it might increase branch
23470   // mispredicts.
23471   // When we can use CMOV, or when there is no mispredict, this improves
23472   // throughput and reduces register pressure.
23473   //
23474   if (CC == X86::COND_NE) {
23475     SDValue Flags;
23476     X86::CondCode CC0, CC1;
23477     bool isAndSetCC;
23478     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23479       if (isAndSetCC) {
23480         std::swap(FalseOp, TrueOp);
23481         CC0 = X86::GetOppositeBranchCondition(CC0);
23482         CC1 = X86::GetOppositeBranchCondition(CC1);
23483       }
23484
23485       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23486         Flags};
23487       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23488       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23489       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23490       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23491       return CMOV;
23492     }
23493   }
23494
23495   return SDValue();
23496 }
23497
23498 /// PerformMulCombine - Optimize a single multiply with constant into two
23499 /// in order to implement it with two cheaper instructions, e.g.
23500 /// LEA + SHL, LEA + LEA.
23501 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23502                                  TargetLowering::DAGCombinerInfo &DCI) {
23503   // An imul is usually smaller than the alternative sequence.
23504   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23505     return SDValue();
23506
23507   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23508     return SDValue();
23509
23510   EVT VT = N->getValueType(0);
23511   if (VT != MVT::i64 && VT != MVT::i32)
23512     return SDValue();
23513
23514   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23515   if (!C)
23516     return SDValue();
23517   uint64_t MulAmt = C->getZExtValue();
23518   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23519     return SDValue();
23520
23521   uint64_t MulAmt1 = 0;
23522   uint64_t MulAmt2 = 0;
23523   if ((MulAmt % 9) == 0) {
23524     MulAmt1 = 9;
23525     MulAmt2 = MulAmt / 9;
23526   } else if ((MulAmt % 5) == 0) {
23527     MulAmt1 = 5;
23528     MulAmt2 = MulAmt / 5;
23529   } else if ((MulAmt % 3) == 0) {
23530     MulAmt1 = 3;
23531     MulAmt2 = MulAmt / 3;
23532   }
23533   if (MulAmt2 &&
23534       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23535     SDLoc DL(N);
23536
23537     if (isPowerOf2_64(MulAmt2) &&
23538         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23539       // If second multiplifer is pow2, issue it first. We want the multiply by
23540       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23541       // is an add.
23542       std::swap(MulAmt1, MulAmt2);
23543
23544     SDValue NewMul;
23545     if (isPowerOf2_64(MulAmt1))
23546       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23547                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23548     else
23549       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23550                            DAG.getConstant(MulAmt1, DL, VT));
23551
23552     if (isPowerOf2_64(MulAmt2))
23553       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23554                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23555     else
23556       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23557                            DAG.getConstant(MulAmt2, DL, VT));
23558
23559     // Do not add new nodes to DAG combiner worklist.
23560     DCI.CombineTo(N, NewMul, false);
23561   }
23562   return SDValue();
23563 }
23564
23565 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23566   SDValue N0 = N->getOperand(0);
23567   SDValue N1 = N->getOperand(1);
23568   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23569   EVT VT = N0.getValueType();
23570
23571   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23572   // since the result of setcc_c is all zero's or all ones.
23573   if (VT.isInteger() && !VT.isVector() &&
23574       N1C && N0.getOpcode() == ISD::AND &&
23575       N0.getOperand(1).getOpcode() == ISD::Constant) {
23576     SDValue N00 = N0.getOperand(0);
23577     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23578     APInt ShAmt = N1C->getAPIntValue();
23579     Mask = Mask.shl(ShAmt);
23580     bool MaskOK = false;
23581     // We can handle cases concerning bit-widening nodes containing setcc_c if
23582     // we carefully interrogate the mask to make sure we are semantics
23583     // preserving.
23584     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23585     // of the underlying setcc_c operation if the setcc_c was zero extended.
23586     // Consider the following example:
23587     //   zext(setcc_c)                 -> i32 0x0000FFFF
23588     //   c1                            -> i32 0x0000FFFF
23589     //   c2                            -> i32 0x00000001
23590     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23591     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23592     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23593       MaskOK = true;
23594     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23595                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23596       MaskOK = true;
23597     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23598                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23599                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23600       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23601     }
23602     if (MaskOK && Mask != 0) {
23603       SDLoc DL(N);
23604       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23605     }
23606   }
23607
23608   // Hardware support for vector shifts is sparse which makes us scalarize the
23609   // vector operations in many cases. Also, on sandybridge ADD is faster than
23610   // shl.
23611   // (shl V, 1) -> add V,V
23612   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23613     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23614       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23615       // We shift all of the values by one. In many cases we do not have
23616       // hardware support for this operation. This is better expressed as an ADD
23617       // of two values.
23618       if (N1SplatC->getAPIntValue() == 1)
23619         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23620     }
23621
23622   return SDValue();
23623 }
23624
23625 /// \brief Returns a vector of 0s if the node in input is a vector logical
23626 /// shift by a constant amount which is known to be bigger than or equal
23627 /// to the vector element size in bits.
23628 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23629                                       const X86Subtarget *Subtarget) {
23630   EVT VT = N->getValueType(0);
23631
23632   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23633       (!Subtarget->hasInt256() ||
23634        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23635     return SDValue();
23636
23637   SDValue Amt = N->getOperand(1);
23638   SDLoc DL(N);
23639   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23640     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23641       APInt ShiftAmt = AmtSplat->getAPIntValue();
23642       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23643
23644       // SSE2/AVX2 logical shifts always return a vector of 0s
23645       // if the shift amount is bigger than or equal to
23646       // the element size. The constant shift amount will be
23647       // encoded as a 8-bit immediate.
23648       if (ShiftAmt.trunc(8).uge(MaxAmount))
23649         return getZeroVector(VT, Subtarget, DAG, DL);
23650     }
23651
23652   return SDValue();
23653 }
23654
23655 /// PerformShiftCombine - Combine shifts.
23656 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23657                                    TargetLowering::DAGCombinerInfo &DCI,
23658                                    const X86Subtarget *Subtarget) {
23659   if (N->getOpcode() == ISD::SHL)
23660     if (SDValue V = PerformSHLCombine(N, DAG))
23661       return V;
23662
23663   // Try to fold this logical shift into a zero vector.
23664   if (N->getOpcode() != ISD::SRA)
23665     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23666       return V;
23667
23668   return SDValue();
23669 }
23670
23671 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23672 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23673 // and friends.  Likewise for OR -> CMPNEQSS.
23674 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23675                             TargetLowering::DAGCombinerInfo &DCI,
23676                             const X86Subtarget *Subtarget) {
23677   unsigned opcode;
23678
23679   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23680   // we're requiring SSE2 for both.
23681   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23682     SDValue N0 = N->getOperand(0);
23683     SDValue N1 = N->getOperand(1);
23684     SDValue CMP0 = N0->getOperand(1);
23685     SDValue CMP1 = N1->getOperand(1);
23686     SDLoc DL(N);
23687
23688     // The SETCCs should both refer to the same CMP.
23689     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23690       return SDValue();
23691
23692     SDValue CMP00 = CMP0->getOperand(0);
23693     SDValue CMP01 = CMP0->getOperand(1);
23694     EVT     VT    = CMP00.getValueType();
23695
23696     if (VT == MVT::f32 || VT == MVT::f64) {
23697       bool ExpectingFlags = false;
23698       // Check for any users that want flags:
23699       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23700            !ExpectingFlags && UI != UE; ++UI)
23701         switch (UI->getOpcode()) {
23702         default:
23703         case ISD::BR_CC:
23704         case ISD::BRCOND:
23705         case ISD::SELECT:
23706           ExpectingFlags = true;
23707           break;
23708         case ISD::CopyToReg:
23709         case ISD::SIGN_EXTEND:
23710         case ISD::ZERO_EXTEND:
23711         case ISD::ANY_EXTEND:
23712           break;
23713         }
23714
23715       if (!ExpectingFlags) {
23716         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23717         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23718
23719         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23720           X86::CondCode tmp = cc0;
23721           cc0 = cc1;
23722           cc1 = tmp;
23723         }
23724
23725         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23726             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23727           // FIXME: need symbolic constants for these magic numbers.
23728           // See X86ATTInstPrinter.cpp:printSSECC().
23729           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23730           if (Subtarget->hasAVX512()) {
23731             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23732                                          CMP01,
23733                                          DAG.getConstant(x86cc, DL, MVT::i8));
23734             if (N->getValueType(0) != MVT::i1)
23735               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23736                                  FSetCC);
23737             return FSetCC;
23738           }
23739           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23740                                               CMP00.getValueType(), CMP00, CMP01,
23741                                               DAG.getConstant(x86cc, DL,
23742                                                               MVT::i8));
23743
23744           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23745           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23746
23747           if (is64BitFP && !Subtarget->is64Bit()) {
23748             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23749             // 64-bit integer, since that's not a legal type. Since
23750             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23751             // bits, but can do this little dance to extract the lowest 32 bits
23752             // and work with those going forward.
23753             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23754                                            OnesOrZeroesF);
23755             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23756             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23757                                         Vector32, DAG.getIntPtrConstant(0, DL));
23758             IntVT = MVT::i32;
23759           }
23760
23761           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23762           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23763                                       DAG.getConstant(1, DL, IntVT));
23764           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23765                                               ANDed);
23766           return OneBitOfTruth;
23767         }
23768       }
23769     }
23770   }
23771   return SDValue();
23772 }
23773
23774 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23775 /// so it can be folded inside ANDNP.
23776 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23777   EVT VT = N->getValueType(0);
23778
23779   // Match direct AllOnes for 128 and 256-bit vectors
23780   if (ISD::isBuildVectorAllOnes(N))
23781     return true;
23782
23783   // Look through a bit convert.
23784   if (N->getOpcode() == ISD::BITCAST)
23785     N = N->getOperand(0).getNode();
23786
23787   // Sometimes the operand may come from a insert_subvector building a 256-bit
23788   // allones vector
23789   if (VT.is256BitVector() &&
23790       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23791     SDValue V1 = N->getOperand(0);
23792     SDValue V2 = N->getOperand(1);
23793
23794     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23795         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23796         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23797         ISD::isBuildVectorAllOnes(V2.getNode()))
23798       return true;
23799   }
23800
23801   return false;
23802 }
23803
23804 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23805 // register. In most cases we actually compare or select YMM-sized registers
23806 // and mixing the two types creates horrible code. This method optimizes
23807 // some of the transition sequences.
23808 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23809                                  TargetLowering::DAGCombinerInfo &DCI,
23810                                  const X86Subtarget *Subtarget) {
23811   EVT VT = N->getValueType(0);
23812   if (!VT.is256BitVector())
23813     return SDValue();
23814
23815   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23816           N->getOpcode() == ISD::ZERO_EXTEND ||
23817           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23818
23819   SDValue Narrow = N->getOperand(0);
23820   EVT NarrowVT = Narrow->getValueType(0);
23821   if (!NarrowVT.is128BitVector())
23822     return SDValue();
23823
23824   if (Narrow->getOpcode() != ISD::XOR &&
23825       Narrow->getOpcode() != ISD::AND &&
23826       Narrow->getOpcode() != ISD::OR)
23827     return SDValue();
23828
23829   SDValue N0  = Narrow->getOperand(0);
23830   SDValue N1  = Narrow->getOperand(1);
23831   SDLoc DL(Narrow);
23832
23833   // The Left side has to be a trunc.
23834   if (N0.getOpcode() != ISD::TRUNCATE)
23835     return SDValue();
23836
23837   // The type of the truncated inputs.
23838   EVT WideVT = N0->getOperand(0)->getValueType(0);
23839   if (WideVT != VT)
23840     return SDValue();
23841
23842   // The right side has to be a 'trunc' or a constant vector.
23843   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23844   ConstantSDNode *RHSConstSplat = nullptr;
23845   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23846     RHSConstSplat = RHSBV->getConstantSplatNode();
23847   if (!RHSTrunc && !RHSConstSplat)
23848     return SDValue();
23849
23850   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23851
23852   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23853     return SDValue();
23854
23855   // Set N0 and N1 to hold the inputs to the new wide operation.
23856   N0 = N0->getOperand(0);
23857   if (RHSConstSplat) {
23858     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23859                      SDValue(RHSConstSplat, 0));
23860     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23861     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23862   } else if (RHSTrunc) {
23863     N1 = N1->getOperand(0);
23864   }
23865
23866   // Generate the wide operation.
23867   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23868   unsigned Opcode = N->getOpcode();
23869   switch (Opcode) {
23870   case ISD::ANY_EXTEND:
23871     return Op;
23872   case ISD::ZERO_EXTEND: {
23873     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23874     APInt Mask = APInt::getAllOnesValue(InBits);
23875     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23876     return DAG.getNode(ISD::AND, DL, VT,
23877                        Op, DAG.getConstant(Mask, DL, VT));
23878   }
23879   case ISD::SIGN_EXTEND:
23880     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23881                        Op, DAG.getValueType(NarrowVT));
23882   default:
23883     llvm_unreachable("Unexpected opcode");
23884   }
23885 }
23886
23887 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23888                                  TargetLowering::DAGCombinerInfo &DCI,
23889                                  const X86Subtarget *Subtarget) {
23890   SDValue N0 = N->getOperand(0);
23891   SDValue N1 = N->getOperand(1);
23892   SDLoc DL(N);
23893
23894   // A vector zext_in_reg may be represented as a shuffle,
23895   // feeding into a bitcast (this represents anyext) feeding into
23896   // an and with a mask.
23897   // We'd like to try to combine that into a shuffle with zero
23898   // plus a bitcast, removing the and.
23899   if (N0.getOpcode() != ISD::BITCAST ||
23900       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23901     return SDValue();
23902
23903   // The other side of the AND should be a splat of 2^C, where C
23904   // is the number of bits in the source type.
23905   if (N1.getOpcode() == ISD::BITCAST)
23906     N1 = N1.getOperand(0);
23907   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23908     return SDValue();
23909   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23910
23911   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23912   EVT SrcType = Shuffle->getValueType(0);
23913
23914   // We expect a single-source shuffle
23915   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23916     return SDValue();
23917
23918   unsigned SrcSize = SrcType.getScalarSizeInBits();
23919
23920   APInt SplatValue, SplatUndef;
23921   unsigned SplatBitSize;
23922   bool HasAnyUndefs;
23923   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23924                                 SplatBitSize, HasAnyUndefs))
23925     return SDValue();
23926
23927   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23928   // Make sure the splat matches the mask we expect
23929   if (SplatBitSize > ResSize ||
23930       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23931     return SDValue();
23932
23933   // Make sure the input and output size make sense
23934   if (SrcSize >= ResSize || ResSize % SrcSize)
23935     return SDValue();
23936
23937   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23938   // The number of u's between each two values depends on the ratio between
23939   // the source and dest type.
23940   unsigned ZextRatio = ResSize / SrcSize;
23941   bool IsZext = true;
23942   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23943     if (i % ZextRatio) {
23944       if (Shuffle->getMaskElt(i) > 0) {
23945         // Expected undef
23946         IsZext = false;
23947         break;
23948       }
23949     } else {
23950       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23951         // Expected element number
23952         IsZext = false;
23953         break;
23954       }
23955     }
23956   }
23957
23958   if (!IsZext)
23959     return SDValue();
23960
23961   // Ok, perform the transformation - replace the shuffle with
23962   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23963   // (instead of undef) where the k elements come from the zero vector.
23964   SmallVector<int, 8> Mask;
23965   unsigned NumElems = SrcType.getVectorNumElements();
23966   for (unsigned i = 0; i < NumElems; ++i)
23967     if (i % ZextRatio)
23968       Mask.push_back(NumElems);
23969     else
23970       Mask.push_back(i / ZextRatio);
23971
23972   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23973     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23974   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23975 }
23976
23977 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23978                                  TargetLowering::DAGCombinerInfo &DCI,
23979                                  const X86Subtarget *Subtarget) {
23980   if (DCI.isBeforeLegalizeOps())
23981     return SDValue();
23982
23983   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23984     return Zext;
23985
23986   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23987     return R;
23988
23989   EVT VT = N->getValueType(0);
23990   SDValue N0 = N->getOperand(0);
23991   SDValue N1 = N->getOperand(1);
23992   SDLoc DL(N);
23993
23994   // Create BEXTR instructions
23995   // BEXTR is ((X >> imm) & (2**size-1))
23996   if (VT == MVT::i32 || VT == MVT::i64) {
23997     // Check for BEXTR.
23998     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23999         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24000       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24001       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24002       if (MaskNode && ShiftNode) {
24003         uint64_t Mask = MaskNode->getZExtValue();
24004         uint64_t Shift = ShiftNode->getZExtValue();
24005         if (isMask_64(Mask)) {
24006           uint64_t MaskSize = countPopulation(Mask);
24007           if (Shift + MaskSize <= VT.getSizeInBits())
24008             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24009                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24010                                                VT));
24011         }
24012       }
24013     } // BEXTR
24014
24015     return SDValue();
24016   }
24017
24018   // Want to form ANDNP nodes:
24019   // 1) In the hopes of then easily combining them with OR and AND nodes
24020   //    to form PBLEND/PSIGN.
24021   // 2) To match ANDN packed intrinsics
24022   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24023     return SDValue();
24024
24025   // Check LHS for vnot
24026   if (N0.getOpcode() == ISD::XOR &&
24027       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24028       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24029     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24030
24031   // Check RHS for vnot
24032   if (N1.getOpcode() == ISD::XOR &&
24033       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24034       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24035     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24036
24037   return SDValue();
24038 }
24039
24040 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24041                                 TargetLowering::DAGCombinerInfo &DCI,
24042                                 const X86Subtarget *Subtarget) {
24043   if (DCI.isBeforeLegalizeOps())
24044     return SDValue();
24045
24046   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24047     return R;
24048
24049   SDValue N0 = N->getOperand(0);
24050   SDValue N1 = N->getOperand(1);
24051   EVT VT = N->getValueType(0);
24052
24053   // look for psign/blend
24054   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24055     if (!Subtarget->hasSSSE3() ||
24056         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24057       return SDValue();
24058
24059     // Canonicalize pandn to RHS
24060     if (N0.getOpcode() == X86ISD::ANDNP)
24061       std::swap(N0, N1);
24062     // or (and (m, y), (pandn m, x))
24063     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24064       SDValue Mask = N1.getOperand(0);
24065       SDValue X    = N1.getOperand(1);
24066       SDValue Y;
24067       if (N0.getOperand(0) == Mask)
24068         Y = N0.getOperand(1);
24069       if (N0.getOperand(1) == Mask)
24070         Y = N0.getOperand(0);
24071
24072       // Check to see if the mask appeared in both the AND and ANDNP and
24073       if (!Y.getNode())
24074         return SDValue();
24075
24076       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24077       // Look through mask bitcast.
24078       if (Mask.getOpcode() == ISD::BITCAST)
24079         Mask = Mask.getOperand(0);
24080       if (X.getOpcode() == ISD::BITCAST)
24081         X = X.getOperand(0);
24082       if (Y.getOpcode() == ISD::BITCAST)
24083         Y = Y.getOperand(0);
24084
24085       EVT MaskVT = Mask.getValueType();
24086
24087       // Validate that the Mask operand is a vector sra node.
24088       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24089       // there is no psrai.b
24090       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24091       unsigned SraAmt = ~0;
24092       if (Mask.getOpcode() == ISD::SRA) {
24093         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24094           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24095             SraAmt = AmtConst->getZExtValue();
24096       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24097         SDValue SraC = Mask.getOperand(1);
24098         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24099       }
24100       if ((SraAmt + 1) != EltBits)
24101         return SDValue();
24102
24103       SDLoc DL(N);
24104
24105       // Now we know we at least have a plendvb with the mask val.  See if
24106       // we can form a psignb/w/d.
24107       // psign = x.type == y.type == mask.type && y = sub(0, x);
24108       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24109           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24110           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24111         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24112                "Unsupported VT for PSIGN");
24113         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24114         return DAG.getBitcast(VT, Mask);
24115       }
24116       // PBLENDVB only available on SSE 4.1
24117       if (!Subtarget->hasSSE41())
24118         return SDValue();
24119
24120       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24121
24122       X = DAG.getBitcast(BlendVT, X);
24123       Y = DAG.getBitcast(BlendVT, Y);
24124       Mask = DAG.getBitcast(BlendVT, Mask);
24125       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24126       return DAG.getBitcast(VT, Mask);
24127     }
24128   }
24129
24130   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24131     return SDValue();
24132
24133   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24134   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24135
24136   // SHLD/SHRD instructions have lower register pressure, but on some
24137   // platforms they have higher latency than the equivalent
24138   // series of shifts/or that would otherwise be generated.
24139   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24140   // have higher latencies and we are not optimizing for size.
24141   if (!OptForSize && Subtarget->isSHLDSlow())
24142     return SDValue();
24143
24144   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24145     std::swap(N0, N1);
24146   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24147     return SDValue();
24148   if (!N0.hasOneUse() || !N1.hasOneUse())
24149     return SDValue();
24150
24151   SDValue ShAmt0 = N0.getOperand(1);
24152   if (ShAmt0.getValueType() != MVT::i8)
24153     return SDValue();
24154   SDValue ShAmt1 = N1.getOperand(1);
24155   if (ShAmt1.getValueType() != MVT::i8)
24156     return SDValue();
24157   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24158     ShAmt0 = ShAmt0.getOperand(0);
24159   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24160     ShAmt1 = ShAmt1.getOperand(0);
24161
24162   SDLoc DL(N);
24163   unsigned Opc = X86ISD::SHLD;
24164   SDValue Op0 = N0.getOperand(0);
24165   SDValue Op1 = N1.getOperand(0);
24166   if (ShAmt0.getOpcode() == ISD::SUB) {
24167     Opc = X86ISD::SHRD;
24168     std::swap(Op0, Op1);
24169     std::swap(ShAmt0, ShAmt1);
24170   }
24171
24172   unsigned Bits = VT.getSizeInBits();
24173   if (ShAmt1.getOpcode() == ISD::SUB) {
24174     SDValue Sum = ShAmt1.getOperand(0);
24175     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24176       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24177       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24178         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24179       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24180         return DAG.getNode(Opc, DL, VT,
24181                            Op0, Op1,
24182                            DAG.getNode(ISD::TRUNCATE, DL,
24183                                        MVT::i8, ShAmt0));
24184     }
24185   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24186     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24187     if (ShAmt0C &&
24188         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24189       return DAG.getNode(Opc, DL, VT,
24190                          N0.getOperand(0), N1.getOperand(0),
24191                          DAG.getNode(ISD::TRUNCATE, DL,
24192                                        MVT::i8, ShAmt0));
24193   }
24194
24195   return SDValue();
24196 }
24197
24198 // Generate NEG and CMOV for integer abs.
24199 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24200   EVT VT = N->getValueType(0);
24201
24202   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24203   // 8-bit integer abs to NEG and CMOV.
24204   if (VT.isInteger() && VT.getSizeInBits() == 8)
24205     return SDValue();
24206
24207   SDValue N0 = N->getOperand(0);
24208   SDValue N1 = N->getOperand(1);
24209   SDLoc DL(N);
24210
24211   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24212   // and change it to SUB and CMOV.
24213   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24214       N0.getOpcode() == ISD::ADD &&
24215       N0.getOperand(1) == N1 &&
24216       N1.getOpcode() == ISD::SRA &&
24217       N1.getOperand(0) == N0.getOperand(0))
24218     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24219       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24220         // Generate SUB & CMOV.
24221         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24222                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24223
24224         SDValue Ops[] = { N0.getOperand(0), Neg,
24225                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24226                           SDValue(Neg.getNode(), 1) };
24227         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24228       }
24229   return SDValue();
24230 }
24231
24232 // Try to turn tests against the signbit in the form of:
24233 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24234 // into:
24235 //   SETGT(X, -1)
24236 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24237   // This is only worth doing if the output type is i8.
24238   if (N->getValueType(0) != MVT::i8)
24239     return SDValue();
24240
24241   SDValue N0 = N->getOperand(0);
24242   SDValue N1 = N->getOperand(1);
24243
24244   // We should be performing an xor against a truncated shift.
24245   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24246     return SDValue();
24247
24248   // Make sure we are performing an xor against one.
24249   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24250     return SDValue();
24251
24252   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24253   SDValue Shift = N0.getOperand(0);
24254   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24255     return SDValue();
24256
24257   // Make sure we are truncating from one of i16, i32 or i64.
24258   EVT ShiftTy = Shift.getValueType();
24259   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24260     return SDValue();
24261
24262   // Make sure the shift amount extracts the sign bit.
24263   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24264       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24265     return SDValue();
24266
24267   // Create a greater-than comparison against -1.
24268   // N.B. Using SETGE against 0 works but we want a canonical looking
24269   // comparison, using SETGT matches up with what TranslateX86CC.
24270   SDLoc DL(N);
24271   SDValue ShiftOp = Shift.getOperand(0);
24272   EVT ShiftOpTy = ShiftOp.getValueType();
24273   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24274                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24275   return Cond;
24276 }
24277
24278 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24279                                  TargetLowering::DAGCombinerInfo &DCI,
24280                                  const X86Subtarget *Subtarget) {
24281   if (DCI.isBeforeLegalizeOps())
24282     return SDValue();
24283
24284   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24285     return RV;
24286
24287   if (Subtarget->hasCMov())
24288     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24289       return RV;
24290
24291   return SDValue();
24292 }
24293
24294 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24295 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24296                                   TargetLowering::DAGCombinerInfo &DCI,
24297                                   const X86Subtarget *Subtarget) {
24298   LoadSDNode *Ld = cast<LoadSDNode>(N);
24299   EVT RegVT = Ld->getValueType(0);
24300   EVT MemVT = Ld->getMemoryVT();
24301   SDLoc dl(Ld);
24302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24303
24304   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24305   // into two 16-byte operations.
24306   ISD::LoadExtType Ext = Ld->getExtensionType();
24307   bool Fast;
24308   unsigned AddressSpace = Ld->getAddressSpace();
24309   unsigned Alignment = Ld->getAlignment();
24310   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24311       Ext == ISD::NON_EXTLOAD &&
24312       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24313                              AddressSpace, Alignment, &Fast) && !Fast) {
24314     unsigned NumElems = RegVT.getVectorNumElements();
24315     if (NumElems < 2)
24316       return SDValue();
24317
24318     SDValue Ptr = Ld->getBasePtr();
24319     SDValue Increment =
24320         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24321
24322     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24323                                   NumElems/2);
24324     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24325                                 Ld->getPointerInfo(), Ld->isVolatile(),
24326                                 Ld->isNonTemporal(), Ld->isInvariant(),
24327                                 Alignment);
24328     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24329     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24330                                 Ld->getPointerInfo(), Ld->isVolatile(),
24331                                 Ld->isNonTemporal(), Ld->isInvariant(),
24332                                 std::min(16U, Alignment));
24333     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24334                              Load1.getValue(1),
24335                              Load2.getValue(1));
24336
24337     SDValue NewVec = DAG.getUNDEF(RegVT);
24338     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24339     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24340     return DCI.CombineTo(N, NewVec, TF, true);
24341   }
24342
24343   return SDValue();
24344 }
24345
24346 /// PerformMLOADCombine - Resolve extending loads
24347 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24348                                    TargetLowering::DAGCombinerInfo &DCI,
24349                                    const X86Subtarget *Subtarget) {
24350   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24351   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24352     return SDValue();
24353
24354   EVT VT = Mld->getValueType(0);
24355   unsigned NumElems = VT.getVectorNumElements();
24356   EVT LdVT = Mld->getMemoryVT();
24357   SDLoc dl(Mld);
24358
24359   assert(LdVT != VT && "Cannot extend to the same type");
24360   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24361   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24362   // From, To sizes and ElemCount must be pow of two
24363   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24364     "Unexpected size for extending masked load");
24365
24366   unsigned SizeRatio  = ToSz / FromSz;
24367   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24368
24369   // Create a type on which we perform the shuffle
24370   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24371           LdVT.getScalarType(), NumElems*SizeRatio);
24372   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24373
24374   // Convert Src0 value
24375   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24376   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24377     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24378     for (unsigned i = 0; i != NumElems; ++i)
24379       ShuffleVec[i] = i * SizeRatio;
24380
24381     // Can't shuffle using an illegal type.
24382     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24383             && "WideVecVT should be legal");
24384     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24385                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24386   }
24387   // Prepare the new mask
24388   SDValue NewMask;
24389   SDValue Mask = Mld->getMask();
24390   if (Mask.getValueType() == VT) {
24391     // Mask and original value have the same type
24392     NewMask = DAG.getBitcast(WideVecVT, Mask);
24393     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24394     for (unsigned i = 0; i != NumElems; ++i)
24395       ShuffleVec[i] = i * SizeRatio;
24396     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24397       ShuffleVec[i] = NumElems*SizeRatio;
24398     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24399                                    DAG.getConstant(0, dl, WideVecVT),
24400                                    &ShuffleVec[0]);
24401   }
24402   else {
24403     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24404     unsigned WidenNumElts = NumElems*SizeRatio;
24405     unsigned MaskNumElts = VT.getVectorNumElements();
24406     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24407                                      WidenNumElts);
24408
24409     unsigned NumConcat = WidenNumElts / MaskNumElts;
24410     SmallVector<SDValue, 16> Ops(NumConcat);
24411     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24412     Ops[0] = Mask;
24413     for (unsigned i = 1; i != NumConcat; ++i)
24414       Ops[i] = ZeroVal;
24415
24416     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24417   }
24418
24419   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24420                                      Mld->getBasePtr(), NewMask, WideSrc0,
24421                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24422                                      ISD::NON_EXTLOAD);
24423   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24424   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24425
24426 }
24427 /// PerformMSTORECombine - Resolve truncating stores
24428 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24429                                     const X86Subtarget *Subtarget) {
24430   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24431   if (!Mst->isTruncatingStore())
24432     return SDValue();
24433
24434   EVT VT = Mst->getValue().getValueType();
24435   unsigned NumElems = VT.getVectorNumElements();
24436   EVT StVT = Mst->getMemoryVT();
24437   SDLoc dl(Mst);
24438
24439   assert(StVT != VT && "Cannot truncate to the same type");
24440   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24441   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24442
24443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24444
24445   // The truncating store is legal in some cases. For example
24446   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24447   // are designated for truncate store.
24448   // In this case we don't need any further transformations.
24449   if (TLI.isTruncStoreLegal(VT, StVT))
24450     return SDValue();
24451
24452   // From, To sizes and ElemCount must be pow of two
24453   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24454     "Unexpected size for truncating masked store");
24455   // We are going to use the original vector elt for storing.
24456   // Accumulated smaller vector elements must be a multiple of the store size.
24457   assert (((NumElems * FromSz) % ToSz) == 0 &&
24458           "Unexpected ratio for truncating masked store");
24459
24460   unsigned SizeRatio  = FromSz / ToSz;
24461   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24462
24463   // Create a type on which we perform the shuffle
24464   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24465           StVT.getScalarType(), NumElems*SizeRatio);
24466
24467   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24468
24469   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24470   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24471   for (unsigned i = 0; i != NumElems; ++i)
24472     ShuffleVec[i] = i * SizeRatio;
24473
24474   // Can't shuffle using an illegal type.
24475   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24476           && "WideVecVT should be legal");
24477
24478   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24479                                         DAG.getUNDEF(WideVecVT),
24480                                         &ShuffleVec[0]);
24481
24482   SDValue NewMask;
24483   SDValue Mask = Mst->getMask();
24484   if (Mask.getValueType() == VT) {
24485     // Mask and original value have the same type
24486     NewMask = DAG.getBitcast(WideVecVT, Mask);
24487     for (unsigned i = 0; i != NumElems; ++i)
24488       ShuffleVec[i] = i * SizeRatio;
24489     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24490       ShuffleVec[i] = NumElems*SizeRatio;
24491     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24492                                    DAG.getConstant(0, dl, WideVecVT),
24493                                    &ShuffleVec[0]);
24494   }
24495   else {
24496     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24497     unsigned WidenNumElts = NumElems*SizeRatio;
24498     unsigned MaskNumElts = VT.getVectorNumElements();
24499     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24500                                      WidenNumElts);
24501
24502     unsigned NumConcat = WidenNumElts / MaskNumElts;
24503     SmallVector<SDValue, 16> Ops(NumConcat);
24504     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24505     Ops[0] = Mask;
24506     for (unsigned i = 1; i != NumConcat; ++i)
24507       Ops[i] = ZeroVal;
24508
24509     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24510   }
24511
24512   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24513                             NewMask, StVT, Mst->getMemOperand(), false);
24514 }
24515 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24516 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24517                                    const X86Subtarget *Subtarget) {
24518   StoreSDNode *St = cast<StoreSDNode>(N);
24519   EVT VT = St->getValue().getValueType();
24520   EVT StVT = St->getMemoryVT();
24521   SDLoc dl(St);
24522   SDValue StoredVal = St->getOperand(1);
24523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24524
24525   // If we are saving a concatenation of two XMM registers and 32-byte stores
24526   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24527   bool Fast;
24528   unsigned AddressSpace = St->getAddressSpace();
24529   unsigned Alignment = St->getAlignment();
24530   if (VT.is256BitVector() && StVT == VT &&
24531       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24532                              AddressSpace, Alignment, &Fast) && !Fast) {
24533     unsigned NumElems = VT.getVectorNumElements();
24534     if (NumElems < 2)
24535       return SDValue();
24536
24537     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24538     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24539
24540     SDValue Stride =
24541         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24542     SDValue Ptr0 = St->getBasePtr();
24543     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24544
24545     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24546                                 St->getPointerInfo(), St->isVolatile(),
24547                                 St->isNonTemporal(), Alignment);
24548     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24549                                 St->getPointerInfo(), St->isVolatile(),
24550                                 St->isNonTemporal(),
24551                                 std::min(16U, Alignment));
24552     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24553   }
24554
24555   // Optimize trunc store (of multiple scalars) to shuffle and store.
24556   // First, pack all of the elements in one place. Next, store to memory
24557   // in fewer chunks.
24558   if (St->isTruncatingStore() && VT.isVector()) {
24559     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24560     unsigned NumElems = VT.getVectorNumElements();
24561     assert(StVT != VT && "Cannot truncate to the same type");
24562     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24563     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24564
24565     // The truncating store is legal in some cases. For example
24566     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24567     // are designated for truncate store.
24568     // In this case we don't need any further transformations.
24569     if (TLI.isTruncStoreLegal(VT, StVT))
24570       return SDValue();
24571
24572     // From, To sizes and ElemCount must be pow of two
24573     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24574     // We are going to use the original vector elt for storing.
24575     // Accumulated smaller vector elements must be a multiple of the store size.
24576     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24577
24578     unsigned SizeRatio  = FromSz / ToSz;
24579
24580     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24581
24582     // Create a type on which we perform the shuffle
24583     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24584             StVT.getScalarType(), NumElems*SizeRatio);
24585
24586     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24587
24588     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24589     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24590     for (unsigned i = 0; i != NumElems; ++i)
24591       ShuffleVec[i] = i * SizeRatio;
24592
24593     // Can't shuffle using an illegal type.
24594     if (!TLI.isTypeLegal(WideVecVT))
24595       return SDValue();
24596
24597     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24598                                          DAG.getUNDEF(WideVecVT),
24599                                          &ShuffleVec[0]);
24600     // At this point all of the data is stored at the bottom of the
24601     // register. We now need to save it to mem.
24602
24603     // Find the largest store unit
24604     MVT StoreType = MVT::i8;
24605     for (MVT Tp : MVT::integer_valuetypes()) {
24606       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24607         StoreType = Tp;
24608     }
24609
24610     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24611     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24612         (64 <= NumElems * ToSz))
24613       StoreType = MVT::f64;
24614
24615     // Bitcast the original vector into a vector of store-size units
24616     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24617             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24618     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24619     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24620     SmallVector<SDValue, 8> Chains;
24621     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24622                                         TLI.getPointerTy(DAG.getDataLayout()));
24623     SDValue Ptr = St->getBasePtr();
24624
24625     // Perform one or more big stores into memory.
24626     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24627       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24628                                    StoreType, ShuffWide,
24629                                    DAG.getIntPtrConstant(i, dl));
24630       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24631                                 St->getPointerInfo(), St->isVolatile(),
24632                                 St->isNonTemporal(), St->getAlignment());
24633       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24634       Chains.push_back(Ch);
24635     }
24636
24637     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24638   }
24639
24640   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24641   // the FP state in cases where an emms may be missing.
24642   // A preferable solution to the general problem is to figure out the right
24643   // places to insert EMMS.  This qualifies as a quick hack.
24644
24645   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24646   if (VT.getSizeInBits() != 64)
24647     return SDValue();
24648
24649   const Function *F = DAG.getMachineFunction().getFunction();
24650   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24651   bool F64IsLegal =
24652       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24653   if ((VT.isVector() ||
24654        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24655       isa<LoadSDNode>(St->getValue()) &&
24656       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24657       St->getChain().hasOneUse() && !St->isVolatile()) {
24658     SDNode* LdVal = St->getValue().getNode();
24659     LoadSDNode *Ld = nullptr;
24660     int TokenFactorIndex = -1;
24661     SmallVector<SDValue, 8> Ops;
24662     SDNode* ChainVal = St->getChain().getNode();
24663     // Must be a store of a load.  We currently handle two cases:  the load
24664     // is a direct child, and it's under an intervening TokenFactor.  It is
24665     // possible to dig deeper under nested TokenFactors.
24666     if (ChainVal == LdVal)
24667       Ld = cast<LoadSDNode>(St->getChain());
24668     else if (St->getValue().hasOneUse() &&
24669              ChainVal->getOpcode() == ISD::TokenFactor) {
24670       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24671         if (ChainVal->getOperand(i).getNode() == LdVal) {
24672           TokenFactorIndex = i;
24673           Ld = cast<LoadSDNode>(St->getValue());
24674         } else
24675           Ops.push_back(ChainVal->getOperand(i));
24676       }
24677     }
24678
24679     if (!Ld || !ISD::isNormalLoad(Ld))
24680       return SDValue();
24681
24682     // If this is not the MMX case, i.e. we are just turning i64 load/store
24683     // into f64 load/store, avoid the transformation if there are multiple
24684     // uses of the loaded value.
24685     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24686       return SDValue();
24687
24688     SDLoc LdDL(Ld);
24689     SDLoc StDL(N);
24690     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24691     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24692     // pair instead.
24693     if (Subtarget->is64Bit() || F64IsLegal) {
24694       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24695       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24696                                   Ld->getPointerInfo(), Ld->isVolatile(),
24697                                   Ld->isNonTemporal(), Ld->isInvariant(),
24698                                   Ld->getAlignment());
24699       SDValue NewChain = NewLd.getValue(1);
24700       if (TokenFactorIndex != -1) {
24701         Ops.push_back(NewChain);
24702         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24703       }
24704       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24705                           St->getPointerInfo(),
24706                           St->isVolatile(), St->isNonTemporal(),
24707                           St->getAlignment());
24708     }
24709
24710     // Otherwise, lower to two pairs of 32-bit loads / stores.
24711     SDValue LoAddr = Ld->getBasePtr();
24712     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24713                                  DAG.getConstant(4, LdDL, MVT::i32));
24714
24715     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24716                                Ld->getPointerInfo(),
24717                                Ld->isVolatile(), Ld->isNonTemporal(),
24718                                Ld->isInvariant(), Ld->getAlignment());
24719     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24720                                Ld->getPointerInfo().getWithOffset(4),
24721                                Ld->isVolatile(), Ld->isNonTemporal(),
24722                                Ld->isInvariant(),
24723                                MinAlign(Ld->getAlignment(), 4));
24724
24725     SDValue NewChain = LoLd.getValue(1);
24726     if (TokenFactorIndex != -1) {
24727       Ops.push_back(LoLd);
24728       Ops.push_back(HiLd);
24729       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24730     }
24731
24732     LoAddr = St->getBasePtr();
24733     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24734                          DAG.getConstant(4, StDL, MVT::i32));
24735
24736     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24737                                 St->getPointerInfo(),
24738                                 St->isVolatile(), St->isNonTemporal(),
24739                                 St->getAlignment());
24740     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24741                                 St->getPointerInfo().getWithOffset(4),
24742                                 St->isVolatile(),
24743                                 St->isNonTemporal(),
24744                                 MinAlign(St->getAlignment(), 4));
24745     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24746   }
24747
24748   // This is similar to the above case, but here we handle a scalar 64-bit
24749   // integer store that is extracted from a vector on a 32-bit target.
24750   // If we have SSE2, then we can treat it like a floating-point double
24751   // to get past legalization. The execution dependencies fixup pass will
24752   // choose the optimal machine instruction for the store if this really is
24753   // an integer or v2f32 rather than an f64.
24754   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24755       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24756     SDValue OldExtract = St->getOperand(1);
24757     SDValue ExtOp0 = OldExtract.getOperand(0);
24758     unsigned VecSize = ExtOp0.getValueSizeInBits();
24759     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24760     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24761     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24762                                      BitCast, OldExtract.getOperand(1));
24763     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24764                         St->getPointerInfo(), St->isVolatile(),
24765                         St->isNonTemporal(), St->getAlignment());
24766   }
24767
24768   return SDValue();
24769 }
24770
24771 /// Return 'true' if this vector operation is "horizontal"
24772 /// and return the operands for the horizontal operation in LHS and RHS.  A
24773 /// horizontal operation performs the binary operation on successive elements
24774 /// of its first operand, then on successive elements of its second operand,
24775 /// returning the resulting values in a vector.  For example, if
24776 ///   A = < float a0, float a1, float a2, float a3 >
24777 /// and
24778 ///   B = < float b0, float b1, float b2, float b3 >
24779 /// then the result of doing a horizontal operation on A and B is
24780 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24781 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24782 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24783 /// set to A, RHS to B, and the routine returns 'true'.
24784 /// Note that the binary operation should have the property that if one of the
24785 /// operands is UNDEF then the result is UNDEF.
24786 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24787   // Look for the following pattern: if
24788   //   A = < float a0, float a1, float a2, float a3 >
24789   //   B = < float b0, float b1, float b2, float b3 >
24790   // and
24791   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24792   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24793   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24794   // which is A horizontal-op B.
24795
24796   // At least one of the operands should be a vector shuffle.
24797   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24798       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24799     return false;
24800
24801   MVT VT = LHS.getSimpleValueType();
24802
24803   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24804          "Unsupported vector type for horizontal add/sub");
24805
24806   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24807   // operate independently on 128-bit lanes.
24808   unsigned NumElts = VT.getVectorNumElements();
24809   unsigned NumLanes = VT.getSizeInBits()/128;
24810   unsigned NumLaneElts = NumElts / NumLanes;
24811   assert((NumLaneElts % 2 == 0) &&
24812          "Vector type should have an even number of elements in each lane");
24813   unsigned HalfLaneElts = NumLaneElts/2;
24814
24815   // View LHS in the form
24816   //   LHS = VECTOR_SHUFFLE A, B, LMask
24817   // If LHS is not a shuffle then pretend it is the shuffle
24818   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24819   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24820   // type VT.
24821   SDValue A, B;
24822   SmallVector<int, 16> LMask(NumElts);
24823   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24824     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24825       A = LHS.getOperand(0);
24826     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24827       B = LHS.getOperand(1);
24828     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24829     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24830   } else {
24831     if (LHS.getOpcode() != ISD::UNDEF)
24832       A = LHS;
24833     for (unsigned i = 0; i != NumElts; ++i)
24834       LMask[i] = i;
24835   }
24836
24837   // Likewise, view RHS in the form
24838   //   RHS = VECTOR_SHUFFLE C, D, RMask
24839   SDValue C, D;
24840   SmallVector<int, 16> RMask(NumElts);
24841   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24842     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24843       C = RHS.getOperand(0);
24844     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24845       D = RHS.getOperand(1);
24846     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24847     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24848   } else {
24849     if (RHS.getOpcode() != ISD::UNDEF)
24850       C = RHS;
24851     for (unsigned i = 0; i != NumElts; ++i)
24852       RMask[i] = i;
24853   }
24854
24855   // Check that the shuffles are both shuffling the same vectors.
24856   if (!(A == C && B == D) && !(A == D && B == C))
24857     return false;
24858
24859   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24860   if (!A.getNode() && !B.getNode())
24861     return false;
24862
24863   // If A and B occur in reverse order in RHS, then "swap" them (which means
24864   // rewriting the mask).
24865   if (A != C)
24866     ShuffleVectorSDNode::commuteMask(RMask);
24867
24868   // At this point LHS and RHS are equivalent to
24869   //   LHS = VECTOR_SHUFFLE A, B, LMask
24870   //   RHS = VECTOR_SHUFFLE A, B, RMask
24871   // Check that the masks correspond to performing a horizontal operation.
24872   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24873     for (unsigned i = 0; i != NumLaneElts; ++i) {
24874       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24875
24876       // Ignore any UNDEF components.
24877       if (LIdx < 0 || RIdx < 0 ||
24878           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24879           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24880         continue;
24881
24882       // Check that successive elements are being operated on.  If not, this is
24883       // not a horizontal operation.
24884       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24885       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24886       if (!(LIdx == Index && RIdx == Index + 1) &&
24887           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24888         return false;
24889     }
24890   }
24891
24892   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24893   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24894   return true;
24895 }
24896
24897 /// Do target-specific dag combines on floating point adds.
24898 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24899                                   const X86Subtarget *Subtarget) {
24900   EVT VT = N->getValueType(0);
24901   SDValue LHS = N->getOperand(0);
24902   SDValue RHS = N->getOperand(1);
24903
24904   // Try to synthesize horizontal adds from adds of shuffles.
24905   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24906        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24907       isHorizontalBinOp(LHS, RHS, true))
24908     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24909   return SDValue();
24910 }
24911
24912 /// Do target-specific dag combines on floating point subs.
24913 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24914                                   const X86Subtarget *Subtarget) {
24915   EVT VT = N->getValueType(0);
24916   SDValue LHS = N->getOperand(0);
24917   SDValue RHS = N->getOperand(1);
24918
24919   // Try to synthesize horizontal subs from subs of shuffles.
24920   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24921        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24922       isHorizontalBinOp(LHS, RHS, false))
24923     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24924   return SDValue();
24925 }
24926
24927 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24928 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24929   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24930
24931   // F[X]OR(0.0, x) -> x
24932   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24933     if (C->getValueAPF().isPosZero())
24934       return N->getOperand(1);
24935
24936   // F[X]OR(x, 0.0) -> x
24937   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24938     if (C->getValueAPF().isPosZero())
24939       return N->getOperand(0);
24940   return SDValue();
24941 }
24942
24943 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24944 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24945   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24946
24947   // Only perform optimizations if UnsafeMath is used.
24948   if (!DAG.getTarget().Options.UnsafeFPMath)
24949     return SDValue();
24950
24951   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24952   // into FMINC and FMAXC, which are Commutative operations.
24953   unsigned NewOp = 0;
24954   switch (N->getOpcode()) {
24955     default: llvm_unreachable("unknown opcode");
24956     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24957     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24958   }
24959
24960   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24961                      N->getOperand(0), N->getOperand(1));
24962 }
24963
24964 /// Do target-specific dag combines on X86ISD::FAND nodes.
24965 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24966   // FAND(0.0, x) -> 0.0
24967   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24968     if (C->getValueAPF().isPosZero())
24969       return N->getOperand(0);
24970
24971   // FAND(x, 0.0) -> 0.0
24972   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24973     if (C->getValueAPF().isPosZero())
24974       return N->getOperand(1);
24975
24976   return SDValue();
24977 }
24978
24979 /// Do target-specific dag combines on X86ISD::FANDN nodes
24980 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24981   // FANDN(0.0, x) -> x
24982   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24983     if (C->getValueAPF().isPosZero())
24984       return N->getOperand(1);
24985
24986   // FANDN(x, 0.0) -> 0.0
24987   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24988     if (C->getValueAPF().isPosZero())
24989       return N->getOperand(1);
24990
24991   return SDValue();
24992 }
24993
24994 static SDValue PerformBTCombine(SDNode *N,
24995                                 SelectionDAG &DAG,
24996                                 TargetLowering::DAGCombinerInfo &DCI) {
24997   // BT ignores high bits in the bit index operand.
24998   SDValue Op1 = N->getOperand(1);
24999   if (Op1.hasOneUse()) {
25000     unsigned BitWidth = Op1.getValueSizeInBits();
25001     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25002     APInt KnownZero, KnownOne;
25003     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25004                                           !DCI.isBeforeLegalizeOps());
25005     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25006     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25007         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25008       DCI.CommitTargetLoweringOpt(TLO);
25009   }
25010   return SDValue();
25011 }
25012
25013 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25014   SDValue Op = N->getOperand(0);
25015   if (Op.getOpcode() == ISD::BITCAST)
25016     Op = Op.getOperand(0);
25017   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25018   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25019       VT.getVectorElementType().getSizeInBits() ==
25020       OpVT.getVectorElementType().getSizeInBits()) {
25021     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25022   }
25023   return SDValue();
25024 }
25025
25026 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25027                                                const X86Subtarget *Subtarget) {
25028   EVT VT = N->getValueType(0);
25029   if (!VT.isVector())
25030     return SDValue();
25031
25032   SDValue N0 = N->getOperand(0);
25033   SDValue N1 = N->getOperand(1);
25034   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25035   SDLoc dl(N);
25036
25037   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25038   // both SSE and AVX2 since there is no sign-extended shift right
25039   // operation on a vector with 64-bit elements.
25040   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25041   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25042   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25043       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25044     SDValue N00 = N0.getOperand(0);
25045
25046     // EXTLOAD has a better solution on AVX2,
25047     // it may be replaced with X86ISD::VSEXT node.
25048     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25049       if (!ISD::isNormalLoad(N00.getNode()))
25050         return SDValue();
25051
25052     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25053         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25054                                   N00, N1);
25055       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25056     }
25057   }
25058   return SDValue();
25059 }
25060
25061 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25062                                   TargetLowering::DAGCombinerInfo &DCI,
25063                                   const X86Subtarget *Subtarget) {
25064   SDValue N0 = N->getOperand(0);
25065   EVT VT = N->getValueType(0);
25066   EVT SVT = VT.getScalarType();
25067   EVT InVT = N0.getValueType();
25068   EVT InSVT = InVT.getScalarType();
25069   SDLoc DL(N);
25070
25071   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25072   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25073   // This exposes the sext to the sdivrem lowering, so that it directly extends
25074   // from AH (which we otherwise need to do contortions to access).
25075   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25076       InVT == MVT::i8 && VT == MVT::i32) {
25077     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25078     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25079                             N0.getOperand(0), N0.getOperand(1));
25080     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25081     return R.getValue(1);
25082   }
25083
25084   if (!DCI.isBeforeLegalizeOps()) {
25085     if (InVT == MVT::i1) {
25086       SDValue Zero = DAG.getConstant(0, DL, VT);
25087       SDValue AllOnes =
25088         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25089       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25090     }
25091     return SDValue();
25092   }
25093
25094   if (VT.isVector() && Subtarget->hasSSE2()) {
25095     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25096       EVT InVT = N.getValueType();
25097       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25098                                    Size / InVT.getScalarSizeInBits());
25099       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25100                                     DAG.getUNDEF(InVT));
25101       Opnds[0] = N;
25102       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25103     };
25104
25105     // If target-size is less than 128-bits, extend to a type that would extend
25106     // to 128 bits, extend that and extract the original target vector.
25107     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25108         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25109         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25110       unsigned Scale = 128 / VT.getSizeInBits();
25111       EVT ExVT =
25112           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25113       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25114       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25115       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25116                          DAG.getIntPtrConstant(0, DL));
25117     }
25118
25119     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25120     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25121     if (VT.getSizeInBits() == 128 &&
25122         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25123         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25124       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25125       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25126     }
25127
25128     // On pre-AVX2 targets, split into 128-bit nodes of
25129     // ISD::SIGN_EXTEND_VECTOR_INREG.
25130     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25131         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25132         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25133       unsigned NumVecs = VT.getSizeInBits() / 128;
25134       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25135       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25136       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25137
25138       SmallVector<SDValue, 8> Opnds;
25139       for (unsigned i = 0, Offset = 0; i != NumVecs;
25140            ++i, Offset += NumSubElts) {
25141         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25142                                      DAG.getIntPtrConstant(Offset, DL));
25143         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25144         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25145         Opnds.push_back(SrcVec);
25146       }
25147       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25148     }
25149   }
25150
25151   if (!Subtarget->hasFp256())
25152     return SDValue();
25153
25154   if (VT.isVector() && VT.getSizeInBits() == 256)
25155     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25156       return R;
25157
25158   return SDValue();
25159 }
25160
25161 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25162                                  const X86Subtarget* Subtarget) {
25163   SDLoc dl(N);
25164   EVT VT = N->getValueType(0);
25165
25166   // Let legalize expand this if it isn't a legal type yet.
25167   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25168     return SDValue();
25169
25170   EVT ScalarVT = VT.getScalarType();
25171   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25172       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25173        !Subtarget->hasAVX512()))
25174     return SDValue();
25175
25176   SDValue A = N->getOperand(0);
25177   SDValue B = N->getOperand(1);
25178   SDValue C = N->getOperand(2);
25179
25180   bool NegA = (A.getOpcode() == ISD::FNEG);
25181   bool NegB = (B.getOpcode() == ISD::FNEG);
25182   bool NegC = (C.getOpcode() == ISD::FNEG);
25183
25184   // Negative multiplication when NegA xor NegB
25185   bool NegMul = (NegA != NegB);
25186   if (NegA)
25187     A = A.getOperand(0);
25188   if (NegB)
25189     B = B.getOperand(0);
25190   if (NegC)
25191     C = C.getOperand(0);
25192
25193   unsigned Opcode;
25194   if (!NegMul)
25195     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25196   else
25197     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25198
25199   return DAG.getNode(Opcode, dl, VT, A, B, C);
25200 }
25201
25202 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25203                                   TargetLowering::DAGCombinerInfo &DCI,
25204                                   const X86Subtarget *Subtarget) {
25205   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25206   //           (and (i32 x86isd::setcc_carry), 1)
25207   // This eliminates the zext. This transformation is necessary because
25208   // ISD::SETCC is always legalized to i8.
25209   SDLoc dl(N);
25210   SDValue N0 = N->getOperand(0);
25211   EVT VT = N->getValueType(0);
25212
25213   if (N0.getOpcode() == ISD::AND &&
25214       N0.hasOneUse() &&
25215       N0.getOperand(0).hasOneUse()) {
25216     SDValue N00 = N0.getOperand(0);
25217     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25218       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25219       if (!C || C->getZExtValue() != 1)
25220         return SDValue();
25221       return DAG.getNode(ISD::AND, dl, VT,
25222                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25223                                      N00.getOperand(0), N00.getOperand(1)),
25224                          DAG.getConstant(1, dl, VT));
25225     }
25226   }
25227
25228   if (N0.getOpcode() == ISD::TRUNCATE &&
25229       N0.hasOneUse() &&
25230       N0.getOperand(0).hasOneUse()) {
25231     SDValue N00 = N0.getOperand(0);
25232     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25233       return DAG.getNode(ISD::AND, dl, VT,
25234                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25235                                      N00.getOperand(0), N00.getOperand(1)),
25236                          DAG.getConstant(1, dl, VT));
25237     }
25238   }
25239
25240   if (VT.is256BitVector())
25241     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25242       return R;
25243
25244   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25245   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25246   // This exposes the zext to the udivrem lowering, so that it directly extends
25247   // from AH (which we otherwise need to do contortions to access).
25248   if (N0.getOpcode() == ISD::UDIVREM &&
25249       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25250       (VT == MVT::i32 || VT == MVT::i64)) {
25251     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25252     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25253                             N0.getOperand(0), N0.getOperand(1));
25254     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25255     return R.getValue(1);
25256   }
25257
25258   return SDValue();
25259 }
25260
25261 // Optimize x == -y --> x+y == 0
25262 //          x != -y --> x+y != 0
25263 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25264                                       const X86Subtarget* Subtarget) {
25265   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25266   SDValue LHS = N->getOperand(0);
25267   SDValue RHS = N->getOperand(1);
25268   EVT VT = N->getValueType(0);
25269   SDLoc DL(N);
25270
25271   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25273       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25274         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25275                                    LHS.getOperand(1));
25276         return DAG.getSetCC(DL, N->getValueType(0), addV,
25277                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25278       }
25279   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25280     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25281       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25282         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25283                                    RHS.getOperand(1));
25284         return DAG.getSetCC(DL, N->getValueType(0), addV,
25285                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25286       }
25287
25288   if (VT.getScalarType() == MVT::i1 &&
25289       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25290     bool IsSEXT0 =
25291         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25292         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25293     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25294
25295     if (!IsSEXT0 || !IsVZero1) {
25296       // Swap the operands and update the condition code.
25297       std::swap(LHS, RHS);
25298       CC = ISD::getSetCCSwappedOperands(CC);
25299
25300       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25301                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25302       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25303     }
25304
25305     if (IsSEXT0 && IsVZero1) {
25306       assert(VT == LHS.getOperand(0).getValueType() &&
25307              "Uexpected operand type");
25308       if (CC == ISD::SETGT)
25309         return DAG.getConstant(0, DL, VT);
25310       if (CC == ISD::SETLE)
25311         return DAG.getConstant(1, DL, VT);
25312       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25313         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25314
25315       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25316              "Unexpected condition code!");
25317       return LHS.getOperand(0);
25318     }
25319   }
25320
25321   return SDValue();
25322 }
25323
25324 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25325                                          SelectionDAG &DAG) {
25326   SDLoc dl(Load);
25327   MVT VT = Load->getSimpleValueType(0);
25328   MVT EVT = VT.getVectorElementType();
25329   SDValue Addr = Load->getOperand(1);
25330   SDValue NewAddr = DAG.getNode(
25331       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25332       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25333                       Addr.getSimpleValueType()));
25334
25335   SDValue NewLoad =
25336       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25337                   DAG.getMachineFunction().getMachineMemOperand(
25338                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25339   return NewLoad;
25340 }
25341
25342 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25343                                       const X86Subtarget *Subtarget) {
25344   SDLoc dl(N);
25345   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25346   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25347          "X86insertps is only defined for v4x32");
25348
25349   SDValue Ld = N->getOperand(1);
25350   if (MayFoldLoad(Ld)) {
25351     // Extract the countS bits from the immediate so we can get the proper
25352     // address when narrowing the vector load to a specific element.
25353     // When the second source op is a memory address, insertps doesn't use
25354     // countS and just gets an f32 from that address.
25355     unsigned DestIndex =
25356         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25357
25358     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25359
25360     // Create this as a scalar to vector to match the instruction pattern.
25361     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25362     // countS bits are ignored when loading from memory on insertps, which
25363     // means we don't need to explicitly set them to 0.
25364     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25365                        LoadScalarToVector, N->getOperand(2));
25366   }
25367   return SDValue();
25368 }
25369
25370 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25371   SDValue V0 = N->getOperand(0);
25372   SDValue V1 = N->getOperand(1);
25373   SDLoc DL(N);
25374   EVT VT = N->getValueType(0);
25375
25376   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25377   // operands and changing the mask to 1. This saves us a bunch of
25378   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25379   // x86InstrInfo knows how to commute this back after instruction selection
25380   // if it would help register allocation.
25381
25382   // TODO: If optimizing for size or a processor that doesn't suffer from
25383   // partial register update stalls, this should be transformed into a MOVSD
25384   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25385
25386   if (VT == MVT::v2f64)
25387     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25388       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25389         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25390         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25391       }
25392
25393   return SDValue();
25394 }
25395
25396 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25397 // as "sbb reg,reg", since it can be extended without zext and produces
25398 // an all-ones bit which is more useful than 0/1 in some cases.
25399 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25400                                MVT VT) {
25401   if (VT == MVT::i8)
25402     return DAG.getNode(ISD::AND, DL, VT,
25403                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25404                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25405                                    EFLAGS),
25406                        DAG.getConstant(1, DL, VT));
25407   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25408   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25409                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25410                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25411                                  EFLAGS));
25412 }
25413
25414 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25415 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25416                                    TargetLowering::DAGCombinerInfo &DCI,
25417                                    const X86Subtarget *Subtarget) {
25418   SDLoc DL(N);
25419   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25420   SDValue EFLAGS = N->getOperand(1);
25421
25422   if (CC == X86::COND_A) {
25423     // Try to convert COND_A into COND_B in an attempt to facilitate
25424     // materializing "setb reg".
25425     //
25426     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25427     // cannot take an immediate as its first operand.
25428     //
25429     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25430         EFLAGS.getValueType().isInteger() &&
25431         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25432       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25433                                    EFLAGS.getNode()->getVTList(),
25434                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25435       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25436       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25437     }
25438   }
25439
25440   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25441   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25442   // cases.
25443   if (CC == X86::COND_B)
25444     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25445
25446   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25447     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25448     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25449   }
25450
25451   return SDValue();
25452 }
25453
25454 // Optimize branch condition evaluation.
25455 //
25456 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25457                                     TargetLowering::DAGCombinerInfo &DCI,
25458                                     const X86Subtarget *Subtarget) {
25459   SDLoc DL(N);
25460   SDValue Chain = N->getOperand(0);
25461   SDValue Dest = N->getOperand(1);
25462   SDValue EFLAGS = N->getOperand(3);
25463   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25464
25465   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25466     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25467     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25468                        Flags);
25469   }
25470
25471   return SDValue();
25472 }
25473
25474 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25475                                                          SelectionDAG &DAG) {
25476   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25477   // optimize away operation when it's from a constant.
25478   //
25479   // The general transformation is:
25480   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25481   //       AND(VECTOR_CMP(x,y), constant2)
25482   //    constant2 = UNARYOP(constant)
25483
25484   // Early exit if this isn't a vector operation, the operand of the
25485   // unary operation isn't a bitwise AND, or if the sizes of the operations
25486   // aren't the same.
25487   EVT VT = N->getValueType(0);
25488   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25489       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25490       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25491     return SDValue();
25492
25493   // Now check that the other operand of the AND is a constant. We could
25494   // make the transformation for non-constant splats as well, but it's unclear
25495   // that would be a benefit as it would not eliminate any operations, just
25496   // perform one more step in scalar code before moving to the vector unit.
25497   if (BuildVectorSDNode *BV =
25498           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25499     // Bail out if the vector isn't a constant.
25500     if (!BV->isConstant())
25501       return SDValue();
25502
25503     // Everything checks out. Build up the new and improved node.
25504     SDLoc DL(N);
25505     EVT IntVT = BV->getValueType(0);
25506     // Create a new constant of the appropriate type for the transformed
25507     // DAG.
25508     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25509     // The AND node needs bitcasts to/from an integer vector type around it.
25510     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25511     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25512                                  N->getOperand(0)->getOperand(0), MaskConst);
25513     SDValue Res = DAG.getBitcast(VT, NewAnd);
25514     return Res;
25515   }
25516
25517   return SDValue();
25518 }
25519
25520 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25521                                         const X86Subtarget *Subtarget) {
25522   SDValue Op0 = N->getOperand(0);
25523   EVT VT = N->getValueType(0);
25524   EVT InVT = Op0.getValueType();
25525   EVT InSVT = InVT.getScalarType();
25526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25527
25528   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25529   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25530   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25531     SDLoc dl(N);
25532     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25533                                  InVT.getVectorNumElements());
25534     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25535
25536     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25537       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25538
25539     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25540   }
25541
25542   return SDValue();
25543 }
25544
25545 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25546                                         const X86Subtarget *Subtarget) {
25547   // First try to optimize away the conversion entirely when it's
25548   // conditionally from a constant. Vectors only.
25549   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25550     return Res;
25551
25552   // Now move on to more general possibilities.
25553   SDValue Op0 = N->getOperand(0);
25554   EVT VT = N->getValueType(0);
25555   EVT InVT = Op0.getValueType();
25556   EVT InSVT = InVT.getScalarType();
25557
25558   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25559   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25560   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25561     SDLoc dl(N);
25562     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25563                                  InVT.getVectorNumElements());
25564     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25565     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25566   }
25567
25568   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25569   // a 32-bit target where SSE doesn't support i64->FP operations.
25570   if (Op0.getOpcode() == ISD::LOAD) {
25571     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25572     EVT LdVT = Ld->getValueType(0);
25573
25574     // This transformation is not supported if the result type is f16
25575     if (VT == MVT::f16)
25576       return SDValue();
25577
25578     if (!Ld->isVolatile() && !VT.isVector() &&
25579         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25580         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25581       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25582           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25583       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25584       return FILDChain;
25585     }
25586   }
25587   return SDValue();
25588 }
25589
25590 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25591 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25592                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25593   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25594   // the result is either zero or one (depending on the input carry bit).
25595   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25596   if (X86::isZeroNode(N->getOperand(0)) &&
25597       X86::isZeroNode(N->getOperand(1)) &&
25598       // We don't have a good way to replace an EFLAGS use, so only do this when
25599       // dead right now.
25600       SDValue(N, 1).use_empty()) {
25601     SDLoc DL(N);
25602     EVT VT = N->getValueType(0);
25603     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25604     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25605                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25606                                            DAG.getConstant(X86::COND_B, DL,
25607                                                            MVT::i8),
25608                                            N->getOperand(2)),
25609                                DAG.getConstant(1, DL, VT));
25610     return DCI.CombineTo(N, Res1, CarryOut);
25611   }
25612
25613   return SDValue();
25614 }
25615
25616 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25617 //      (add Y, (setne X, 0)) -> sbb -1, Y
25618 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25619 //      (sub (setne X, 0), Y) -> adc -1, Y
25620 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25621   SDLoc DL(N);
25622
25623   // Look through ZExts.
25624   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25625   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25626     return SDValue();
25627
25628   SDValue SetCC = Ext.getOperand(0);
25629   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25630     return SDValue();
25631
25632   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25633   if (CC != X86::COND_E && CC != X86::COND_NE)
25634     return SDValue();
25635
25636   SDValue Cmp = SetCC.getOperand(1);
25637   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25638       !X86::isZeroNode(Cmp.getOperand(1)) ||
25639       !Cmp.getOperand(0).getValueType().isInteger())
25640     return SDValue();
25641
25642   SDValue CmpOp0 = Cmp.getOperand(0);
25643   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25644                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25645
25646   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25647   if (CC == X86::COND_NE)
25648     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25649                        DL, OtherVal.getValueType(), OtherVal,
25650                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25651                        NewCmp);
25652   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25653                      DL, OtherVal.getValueType(), OtherVal,
25654                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25655 }
25656
25657 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25658 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25659                                  const X86Subtarget *Subtarget) {
25660   EVT VT = N->getValueType(0);
25661   SDValue Op0 = N->getOperand(0);
25662   SDValue Op1 = N->getOperand(1);
25663
25664   // Try to synthesize horizontal adds from adds of shuffles.
25665   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25666        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25667       isHorizontalBinOp(Op0, Op1, true))
25668     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25669
25670   return OptimizeConditionalInDecrement(N, DAG);
25671 }
25672
25673 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25674                                  const X86Subtarget *Subtarget) {
25675   SDValue Op0 = N->getOperand(0);
25676   SDValue Op1 = N->getOperand(1);
25677
25678   // X86 can't encode an immediate LHS of a sub. See if we can push the
25679   // negation into a preceding instruction.
25680   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25681     // If the RHS of the sub is a XOR with one use and a constant, invert the
25682     // immediate. Then add one to the LHS of the sub so we can turn
25683     // X-Y -> X+~Y+1, saving one register.
25684     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25685         isa<ConstantSDNode>(Op1.getOperand(1))) {
25686       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25687       EVT VT = Op0.getValueType();
25688       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25689                                    Op1.getOperand(0),
25690                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25691       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25692                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25693     }
25694   }
25695
25696   // Try to synthesize horizontal adds from adds of shuffles.
25697   EVT VT = N->getValueType(0);
25698   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25699        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25700       isHorizontalBinOp(Op0, Op1, true))
25701     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25702
25703   return OptimizeConditionalInDecrement(N, DAG);
25704 }
25705
25706 /// performVZEXTCombine - Performs build vector combines
25707 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25708                                    TargetLowering::DAGCombinerInfo &DCI,
25709                                    const X86Subtarget *Subtarget) {
25710   SDLoc DL(N);
25711   MVT VT = N->getSimpleValueType(0);
25712   SDValue Op = N->getOperand(0);
25713   MVT OpVT = Op.getSimpleValueType();
25714   MVT OpEltVT = OpVT.getVectorElementType();
25715   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25716
25717   // (vzext (bitcast (vzext (x)) -> (vzext x)
25718   SDValue V = Op;
25719   while (V.getOpcode() == ISD::BITCAST)
25720     V = V.getOperand(0);
25721
25722   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25723     MVT InnerVT = V.getSimpleValueType();
25724     MVT InnerEltVT = InnerVT.getVectorElementType();
25725
25726     // If the element sizes match exactly, we can just do one larger vzext. This
25727     // is always an exact type match as vzext operates on integer types.
25728     if (OpEltVT == InnerEltVT) {
25729       assert(OpVT == InnerVT && "Types must match for vzext!");
25730       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25731     }
25732
25733     // The only other way we can combine them is if only a single element of the
25734     // inner vzext is used in the input to the outer vzext.
25735     if (InnerEltVT.getSizeInBits() < InputBits)
25736       return SDValue();
25737
25738     // In this case, the inner vzext is completely dead because we're going to
25739     // only look at bits inside of the low element. Just do the outer vzext on
25740     // a bitcast of the input to the inner.
25741     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25742   }
25743
25744   // Check if we can bypass extracting and re-inserting an element of an input
25745   // vector. Essentially:
25746   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25747   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25748       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25749       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25750     SDValue ExtractedV = V.getOperand(0);
25751     SDValue OrigV = ExtractedV.getOperand(0);
25752     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25753       if (ExtractIdx->getZExtValue() == 0) {
25754         MVT OrigVT = OrigV.getSimpleValueType();
25755         // Extract a subvector if necessary...
25756         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25757           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25758           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25759                                     OrigVT.getVectorNumElements() / Ratio);
25760           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25761                               DAG.getIntPtrConstant(0, DL));
25762         }
25763         Op = DAG.getBitcast(OpVT, OrigV);
25764         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25765       }
25766   }
25767
25768   return SDValue();
25769 }
25770
25771 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25772                                              DAGCombinerInfo &DCI) const {
25773   SelectionDAG &DAG = DCI.DAG;
25774   switch (N->getOpcode()) {
25775   default: break;
25776   case ISD::EXTRACT_VECTOR_ELT:
25777     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25778   case ISD::VSELECT:
25779   case ISD::SELECT:
25780   case X86ISD::SHRUNKBLEND:
25781     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25782   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25783   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25784   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25785   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25786   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25787   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25788   case ISD::SHL:
25789   case ISD::SRA:
25790   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25791   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25792   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25793   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25794   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25795   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25796   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25797   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25798   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25799   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25800   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25801   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25802   case X86ISD::FXOR:
25803   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25804   case X86ISD::FMIN:
25805   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25806   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25807   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25808   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25809   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25810   case ISD::ANY_EXTEND:
25811   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25812   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25813   case ISD::SIGN_EXTEND_INREG:
25814     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25815   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25816   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25817   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25818   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25819   case X86ISD::SHUFP:       // Handle all target specific shuffles
25820   case X86ISD::PALIGNR:
25821   case X86ISD::UNPCKH:
25822   case X86ISD::UNPCKL:
25823   case X86ISD::MOVHLPS:
25824   case X86ISD::MOVLHPS:
25825   case X86ISD::PSHUFB:
25826   case X86ISD::PSHUFD:
25827   case X86ISD::PSHUFHW:
25828   case X86ISD::PSHUFLW:
25829   case X86ISD::MOVSS:
25830   case X86ISD::MOVSD:
25831   case X86ISD::VPERMILPI:
25832   case X86ISD::VPERM2X128:
25833   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25834   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25835   case X86ISD::INSERTPS: {
25836     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25837       return PerformINSERTPSCombine(N, DAG, Subtarget);
25838     break;
25839   }
25840   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25841   }
25842
25843   return SDValue();
25844 }
25845
25846 /// isTypeDesirableForOp - Return true if the target has native support for
25847 /// the specified value type and it is 'desirable' to use the type for the
25848 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25849 /// instruction encodings are longer and some i16 instructions are slow.
25850 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25851   if (!isTypeLegal(VT))
25852     return false;
25853   if (VT != MVT::i16)
25854     return true;
25855
25856   switch (Opc) {
25857   default:
25858     return true;
25859   case ISD::LOAD:
25860   case ISD::SIGN_EXTEND:
25861   case ISD::ZERO_EXTEND:
25862   case ISD::ANY_EXTEND:
25863   case ISD::SHL:
25864   case ISD::SRL:
25865   case ISD::SUB:
25866   case ISD::ADD:
25867   case ISD::MUL:
25868   case ISD::AND:
25869   case ISD::OR:
25870   case ISD::XOR:
25871     return false;
25872   }
25873 }
25874
25875 /// IsDesirableToPromoteOp - This method query the target whether it is
25876 /// beneficial for dag combiner to promote the specified node. If true, it
25877 /// should return the desired promotion type by reference.
25878 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25879   EVT VT = Op.getValueType();
25880   if (VT != MVT::i16)
25881     return false;
25882
25883   bool Promote = false;
25884   bool Commute = false;
25885   switch (Op.getOpcode()) {
25886   default: break;
25887   case ISD::LOAD: {
25888     LoadSDNode *LD = cast<LoadSDNode>(Op);
25889     // If the non-extending load has a single use and it's not live out, then it
25890     // might be folded.
25891     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25892                                                      Op.hasOneUse()*/) {
25893       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25894              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25895         // The only case where we'd want to promote LOAD (rather then it being
25896         // promoted as an operand is when it's only use is liveout.
25897         if (UI->getOpcode() != ISD::CopyToReg)
25898           return false;
25899       }
25900     }
25901     Promote = true;
25902     break;
25903   }
25904   case ISD::SIGN_EXTEND:
25905   case ISD::ZERO_EXTEND:
25906   case ISD::ANY_EXTEND:
25907     Promote = true;
25908     break;
25909   case ISD::SHL:
25910   case ISD::SRL: {
25911     SDValue N0 = Op.getOperand(0);
25912     // Look out for (store (shl (load), x)).
25913     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25914       return false;
25915     Promote = true;
25916     break;
25917   }
25918   case ISD::ADD:
25919   case ISD::MUL:
25920   case ISD::AND:
25921   case ISD::OR:
25922   case ISD::XOR:
25923     Commute = true;
25924     // fallthrough
25925   case ISD::SUB: {
25926     SDValue N0 = Op.getOperand(0);
25927     SDValue N1 = Op.getOperand(1);
25928     if (!Commute && MayFoldLoad(N1))
25929       return false;
25930     // Avoid disabling potential load folding opportunities.
25931     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25932       return false;
25933     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25934       return false;
25935     Promote = true;
25936   }
25937   }
25938
25939   PVT = MVT::i32;
25940   return Promote;
25941 }
25942
25943 //===----------------------------------------------------------------------===//
25944 //                           X86 Inline Assembly Support
25945 //===----------------------------------------------------------------------===//
25946
25947 // Helper to match a string separated by whitespace.
25948 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25949   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25950
25951   for (StringRef Piece : Pieces) {
25952     if (!S.startswith(Piece)) // Check if the piece matches.
25953       return false;
25954
25955     S = S.substr(Piece.size());
25956     StringRef::size_type Pos = S.find_first_not_of(" \t");
25957     if (Pos == 0) // We matched a prefix.
25958       return false;
25959
25960     S = S.substr(Pos);
25961   }
25962
25963   return S.empty();
25964 }
25965
25966 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25967
25968   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25969     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25970         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25971         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25972
25973       if (AsmPieces.size() == 3)
25974         return true;
25975       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25976         return true;
25977     }
25978   }
25979   return false;
25980 }
25981
25982 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25983   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25984
25985   std::string AsmStr = IA->getAsmString();
25986
25987   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25988   if (!Ty || Ty->getBitWidth() % 16 != 0)
25989     return false;
25990
25991   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25992   SmallVector<StringRef, 4> AsmPieces;
25993   SplitString(AsmStr, AsmPieces, ";\n");
25994
25995   switch (AsmPieces.size()) {
25996   default: return false;
25997   case 1:
25998     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25999     // we will turn this bswap into something that will be lowered to logical
26000     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26001     // lower so don't worry about this.
26002     // bswap $0
26003     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26004         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26005         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26006         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26007         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26008         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26009       // No need to check constraints, nothing other than the equivalent of
26010       // "=r,0" would be valid here.
26011       return IntrinsicLowering::LowerToByteSwap(CI);
26012     }
26013
26014     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26015     if (CI->getType()->isIntegerTy(16) &&
26016         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26017         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26018          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26019       AsmPieces.clear();
26020       StringRef ConstraintsStr = IA->getConstraintString();
26021       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26022       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26023       if (clobbersFlagRegisters(AsmPieces))
26024         return IntrinsicLowering::LowerToByteSwap(CI);
26025     }
26026     break;
26027   case 3:
26028     if (CI->getType()->isIntegerTy(32) &&
26029         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26030         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26031         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26032         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26033       AsmPieces.clear();
26034       StringRef ConstraintsStr = IA->getConstraintString();
26035       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26036       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26037       if (clobbersFlagRegisters(AsmPieces))
26038         return IntrinsicLowering::LowerToByteSwap(CI);
26039     }
26040
26041     if (CI->getType()->isIntegerTy(64)) {
26042       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26043       if (Constraints.size() >= 2 &&
26044           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26045           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26046         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26047         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26048             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26049             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26050           return IntrinsicLowering::LowerToByteSwap(CI);
26051       }
26052     }
26053     break;
26054   }
26055   return false;
26056 }
26057
26058 /// getConstraintType - Given a constraint letter, return the type of
26059 /// constraint it is for this target.
26060 X86TargetLowering::ConstraintType
26061 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26062   if (Constraint.size() == 1) {
26063     switch (Constraint[0]) {
26064     case 'R':
26065     case 'q':
26066     case 'Q':
26067     case 'f':
26068     case 't':
26069     case 'u':
26070     case 'y':
26071     case 'x':
26072     case 'Y':
26073     case 'l':
26074       return C_RegisterClass;
26075     case 'a':
26076     case 'b':
26077     case 'c':
26078     case 'd':
26079     case 'S':
26080     case 'D':
26081     case 'A':
26082       return C_Register;
26083     case 'I':
26084     case 'J':
26085     case 'K':
26086     case 'L':
26087     case 'M':
26088     case 'N':
26089     case 'G':
26090     case 'C':
26091     case 'e':
26092     case 'Z':
26093       return C_Other;
26094     default:
26095       break;
26096     }
26097   }
26098   return TargetLowering::getConstraintType(Constraint);
26099 }
26100
26101 /// Examine constraint type and operand type and determine a weight value.
26102 /// This object must already have been set up with the operand type
26103 /// and the current alternative constraint selected.
26104 TargetLowering::ConstraintWeight
26105   X86TargetLowering::getSingleConstraintMatchWeight(
26106     AsmOperandInfo &info, const char *constraint) const {
26107   ConstraintWeight weight = CW_Invalid;
26108   Value *CallOperandVal = info.CallOperandVal;
26109     // If we don't have a value, we can't do a match,
26110     // but allow it at the lowest weight.
26111   if (!CallOperandVal)
26112     return CW_Default;
26113   Type *type = CallOperandVal->getType();
26114   // Look at the constraint type.
26115   switch (*constraint) {
26116   default:
26117     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26118   case 'R':
26119   case 'q':
26120   case 'Q':
26121   case 'a':
26122   case 'b':
26123   case 'c':
26124   case 'd':
26125   case 'S':
26126   case 'D':
26127   case 'A':
26128     if (CallOperandVal->getType()->isIntegerTy())
26129       weight = CW_SpecificReg;
26130     break;
26131   case 'f':
26132   case 't':
26133   case 'u':
26134     if (type->isFloatingPointTy())
26135       weight = CW_SpecificReg;
26136     break;
26137   case 'y':
26138     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26139       weight = CW_SpecificReg;
26140     break;
26141   case 'x':
26142   case 'Y':
26143     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26144         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26145       weight = CW_Register;
26146     break;
26147   case 'I':
26148     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26149       if (C->getZExtValue() <= 31)
26150         weight = CW_Constant;
26151     }
26152     break;
26153   case 'J':
26154     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26155       if (C->getZExtValue() <= 63)
26156         weight = CW_Constant;
26157     }
26158     break;
26159   case 'K':
26160     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26161       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26162         weight = CW_Constant;
26163     }
26164     break;
26165   case 'L':
26166     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26167       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26168         weight = CW_Constant;
26169     }
26170     break;
26171   case 'M':
26172     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26173       if (C->getZExtValue() <= 3)
26174         weight = CW_Constant;
26175     }
26176     break;
26177   case 'N':
26178     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26179       if (C->getZExtValue() <= 0xff)
26180         weight = CW_Constant;
26181     }
26182     break;
26183   case 'G':
26184   case 'C':
26185     if (isa<ConstantFP>(CallOperandVal)) {
26186       weight = CW_Constant;
26187     }
26188     break;
26189   case 'e':
26190     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26191       if ((C->getSExtValue() >= -0x80000000LL) &&
26192           (C->getSExtValue() <= 0x7fffffffLL))
26193         weight = CW_Constant;
26194     }
26195     break;
26196   case 'Z':
26197     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26198       if (C->getZExtValue() <= 0xffffffff)
26199         weight = CW_Constant;
26200     }
26201     break;
26202   }
26203   return weight;
26204 }
26205
26206 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26207 /// with another that has more specific requirements based on the type of the
26208 /// corresponding operand.
26209 const char *X86TargetLowering::
26210 LowerXConstraint(EVT ConstraintVT) const {
26211   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26212   // 'f' like normal targets.
26213   if (ConstraintVT.isFloatingPoint()) {
26214     if (Subtarget->hasSSE2())
26215       return "Y";
26216     if (Subtarget->hasSSE1())
26217       return "x";
26218   }
26219
26220   return TargetLowering::LowerXConstraint(ConstraintVT);
26221 }
26222
26223 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26224 /// vector.  If it is invalid, don't add anything to Ops.
26225 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26226                                                      std::string &Constraint,
26227                                                      std::vector<SDValue>&Ops,
26228                                                      SelectionDAG &DAG) const {
26229   SDValue Result;
26230
26231   // Only support length 1 constraints for now.
26232   if (Constraint.length() > 1) return;
26233
26234   char ConstraintLetter = Constraint[0];
26235   switch (ConstraintLetter) {
26236   default: break;
26237   case 'I':
26238     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26239       if (C->getZExtValue() <= 31) {
26240         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26241                                        Op.getValueType());
26242         break;
26243       }
26244     }
26245     return;
26246   case 'J':
26247     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26248       if (C->getZExtValue() <= 63) {
26249         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26250                                        Op.getValueType());
26251         break;
26252       }
26253     }
26254     return;
26255   case 'K':
26256     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26257       if (isInt<8>(C->getSExtValue())) {
26258         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26259                                        Op.getValueType());
26260         break;
26261       }
26262     }
26263     return;
26264   case 'L':
26265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26266       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26267           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26268         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26269                                        Op.getValueType());
26270         break;
26271       }
26272     }
26273     return;
26274   case 'M':
26275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26276       if (C->getZExtValue() <= 3) {
26277         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26278                                        Op.getValueType());
26279         break;
26280       }
26281     }
26282     return;
26283   case 'N':
26284     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26285       if (C->getZExtValue() <= 255) {
26286         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26287                                        Op.getValueType());
26288         break;
26289       }
26290     }
26291     return;
26292   case 'O':
26293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26294       if (C->getZExtValue() <= 127) {
26295         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26296                                        Op.getValueType());
26297         break;
26298       }
26299     }
26300     return;
26301   case 'e': {
26302     // 32-bit signed value
26303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26304       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26305                                            C->getSExtValue())) {
26306         // Widen to 64 bits here to get it sign extended.
26307         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26308         break;
26309       }
26310     // FIXME gcc accepts some relocatable values here too, but only in certain
26311     // memory models; it's complicated.
26312     }
26313     return;
26314   }
26315   case 'Z': {
26316     // 32-bit unsigned value
26317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26318       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26319                                            C->getZExtValue())) {
26320         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26321                                        Op.getValueType());
26322         break;
26323       }
26324     }
26325     // FIXME gcc accepts some relocatable values here too, but only in certain
26326     // memory models; it's complicated.
26327     return;
26328   }
26329   case 'i': {
26330     // Literal immediates are always ok.
26331     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26332       // Widen to 64 bits here to get it sign extended.
26333       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26334       break;
26335     }
26336
26337     // In any sort of PIC mode addresses need to be computed at runtime by
26338     // adding in a register or some sort of table lookup.  These can't
26339     // be used as immediates.
26340     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26341       return;
26342
26343     // If we are in non-pic codegen mode, we allow the address of a global (with
26344     // an optional displacement) to be used with 'i'.
26345     GlobalAddressSDNode *GA = nullptr;
26346     int64_t Offset = 0;
26347
26348     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26349     while (1) {
26350       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26351         Offset += GA->getOffset();
26352         break;
26353       } else if (Op.getOpcode() == ISD::ADD) {
26354         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26355           Offset += C->getZExtValue();
26356           Op = Op.getOperand(0);
26357           continue;
26358         }
26359       } else if (Op.getOpcode() == ISD::SUB) {
26360         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26361           Offset += -C->getZExtValue();
26362           Op = Op.getOperand(0);
26363           continue;
26364         }
26365       }
26366
26367       // Otherwise, this isn't something we can handle, reject it.
26368       return;
26369     }
26370
26371     const GlobalValue *GV = GA->getGlobal();
26372     // If we require an extra load to get this address, as in PIC mode, we
26373     // can't accept it.
26374     if (isGlobalStubReference(
26375             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26376       return;
26377
26378     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26379                                         GA->getValueType(0), Offset);
26380     break;
26381   }
26382   }
26383
26384   if (Result.getNode()) {
26385     Ops.push_back(Result);
26386     return;
26387   }
26388   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26389 }
26390
26391 std::pair<unsigned, const TargetRegisterClass *>
26392 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26393                                                 StringRef Constraint,
26394                                                 MVT VT) const {
26395   // First, see if this is a constraint that directly corresponds to an LLVM
26396   // register class.
26397   if (Constraint.size() == 1) {
26398     // GCC Constraint Letters
26399     switch (Constraint[0]) {
26400     default: break;
26401       // TODO: Slight differences here in allocation order and leaving
26402       // RIP in the class. Do they matter any more here than they do
26403       // in the normal allocation?
26404     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26405       if (Subtarget->is64Bit()) {
26406         if (VT == MVT::i32 || VT == MVT::f32)
26407           return std::make_pair(0U, &X86::GR32RegClass);
26408         if (VT == MVT::i16)
26409           return std::make_pair(0U, &X86::GR16RegClass);
26410         if (VT == MVT::i8 || VT == MVT::i1)
26411           return std::make_pair(0U, &X86::GR8RegClass);
26412         if (VT == MVT::i64 || VT == MVT::f64)
26413           return std::make_pair(0U, &X86::GR64RegClass);
26414         break;
26415       }
26416       // 32-bit fallthrough
26417     case 'Q':   // Q_REGS
26418       if (VT == MVT::i32 || VT == MVT::f32)
26419         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26420       if (VT == MVT::i16)
26421         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26422       if (VT == MVT::i8 || VT == MVT::i1)
26423         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26424       if (VT == MVT::i64)
26425         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26426       break;
26427     case 'r':   // GENERAL_REGS
26428     case 'l':   // INDEX_REGS
26429       if (VT == MVT::i8 || VT == MVT::i1)
26430         return std::make_pair(0U, &X86::GR8RegClass);
26431       if (VT == MVT::i16)
26432         return std::make_pair(0U, &X86::GR16RegClass);
26433       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26434         return std::make_pair(0U, &X86::GR32RegClass);
26435       return std::make_pair(0U, &X86::GR64RegClass);
26436     case 'R':   // LEGACY_REGS
26437       if (VT == MVT::i8 || VT == MVT::i1)
26438         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26439       if (VT == MVT::i16)
26440         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26441       if (VT == MVT::i32 || !Subtarget->is64Bit())
26442         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26443       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26444     case 'f':  // FP Stack registers.
26445       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26446       // value to the correct fpstack register class.
26447       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26448         return std::make_pair(0U, &X86::RFP32RegClass);
26449       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26450         return std::make_pair(0U, &X86::RFP64RegClass);
26451       return std::make_pair(0U, &X86::RFP80RegClass);
26452     case 'y':   // MMX_REGS if MMX allowed.
26453       if (!Subtarget->hasMMX()) break;
26454       return std::make_pair(0U, &X86::VR64RegClass);
26455     case 'Y':   // SSE_REGS if SSE2 allowed
26456       if (!Subtarget->hasSSE2()) break;
26457       // FALL THROUGH.
26458     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26459       if (!Subtarget->hasSSE1()) break;
26460
26461       switch (VT.SimpleTy) {
26462       default: break;
26463       // Scalar SSE types.
26464       case MVT::f32:
26465       case MVT::i32:
26466         return std::make_pair(0U, &X86::FR32RegClass);
26467       case MVT::f64:
26468       case MVT::i64:
26469         return std::make_pair(0U, &X86::FR64RegClass);
26470       // Vector types.
26471       case MVT::v16i8:
26472       case MVT::v8i16:
26473       case MVT::v4i32:
26474       case MVT::v2i64:
26475       case MVT::v4f32:
26476       case MVT::v2f64:
26477         return std::make_pair(0U, &X86::VR128RegClass);
26478       // AVX types.
26479       case MVT::v32i8:
26480       case MVT::v16i16:
26481       case MVT::v8i32:
26482       case MVT::v4i64:
26483       case MVT::v8f32:
26484       case MVT::v4f64:
26485         return std::make_pair(0U, &X86::VR256RegClass);
26486       case MVT::v8f64:
26487       case MVT::v16f32:
26488       case MVT::v16i32:
26489       case MVT::v8i64:
26490         return std::make_pair(0U, &X86::VR512RegClass);
26491       }
26492       break;
26493     }
26494   }
26495
26496   // Use the default implementation in TargetLowering to convert the register
26497   // constraint into a member of a register class.
26498   std::pair<unsigned, const TargetRegisterClass*> Res;
26499   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26500
26501   // Not found as a standard register?
26502   if (!Res.second) {
26503     // Map st(0) -> st(7) -> ST0
26504     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26505         tolower(Constraint[1]) == 's' &&
26506         tolower(Constraint[2]) == 't' &&
26507         Constraint[3] == '(' &&
26508         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26509         Constraint[5] == ')' &&
26510         Constraint[6] == '}') {
26511
26512       Res.first = X86::FP0+Constraint[4]-'0';
26513       Res.second = &X86::RFP80RegClass;
26514       return Res;
26515     }
26516
26517     // GCC allows "st(0)" to be called just plain "st".
26518     if (StringRef("{st}").equals_lower(Constraint)) {
26519       Res.first = X86::FP0;
26520       Res.second = &X86::RFP80RegClass;
26521       return Res;
26522     }
26523
26524     // flags -> EFLAGS
26525     if (StringRef("{flags}").equals_lower(Constraint)) {
26526       Res.first = X86::EFLAGS;
26527       Res.second = &X86::CCRRegClass;
26528       return Res;
26529     }
26530
26531     // 'A' means EAX + EDX.
26532     if (Constraint == "A") {
26533       Res.first = X86::EAX;
26534       Res.second = &X86::GR32_ADRegClass;
26535       return Res;
26536     }
26537     return Res;
26538   }
26539
26540   // Otherwise, check to see if this is a register class of the wrong value
26541   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26542   // turn into {ax},{dx}.
26543   // MVT::Other is used to specify clobber names.
26544   if (Res.second->hasType(VT) || VT == MVT::Other)
26545     return Res;   // Correct type already, nothing to do.
26546
26547   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26548   // return "eax". This should even work for things like getting 64bit integer
26549   // registers when given an f64 type.
26550   const TargetRegisterClass *Class = Res.second;
26551   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26552       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26553     unsigned Size = VT.getSizeInBits();
26554     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26555                                   : Size == 16 ? MVT::i16
26556                                   : Size == 32 ? MVT::i32
26557                                   : Size == 64 ? MVT::i64
26558                                   : MVT::Other;
26559     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26560     if (DestReg > 0) {
26561       Res.first = DestReg;
26562       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26563                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26564                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26565                  : &X86::GR64RegClass;
26566       assert(Res.second->contains(Res.first) && "Register in register class");
26567     } else {
26568       // No register found/type mismatch.
26569       Res.first = 0;
26570       Res.second = nullptr;
26571     }
26572   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26573              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26574              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26575              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26576              Class == &X86::VR512RegClass) {
26577     // Handle references to XMM physical registers that got mapped into the
26578     // wrong class.  This can happen with constraints like {xmm0} where the
26579     // target independent register mapper will just pick the first match it can
26580     // find, ignoring the required type.
26581
26582     if (VT == MVT::f32 || VT == MVT::i32)
26583       Res.second = &X86::FR32RegClass;
26584     else if (VT == MVT::f64 || VT == MVT::i64)
26585       Res.second = &X86::FR64RegClass;
26586     else if (X86::VR128RegClass.hasType(VT))
26587       Res.second = &X86::VR128RegClass;
26588     else if (X86::VR256RegClass.hasType(VT))
26589       Res.second = &X86::VR256RegClass;
26590     else if (X86::VR512RegClass.hasType(VT))
26591       Res.second = &X86::VR512RegClass;
26592     else {
26593       // Type mismatch and not a clobber: Return an error;
26594       Res.first = 0;
26595       Res.second = nullptr;
26596     }
26597   }
26598
26599   return Res;
26600 }
26601
26602 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26603                                             const AddrMode &AM, Type *Ty,
26604                                             unsigned AS) const {
26605   // Scaling factors are not free at all.
26606   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26607   // will take 2 allocations in the out of order engine instead of 1
26608   // for plain addressing mode, i.e. inst (reg1).
26609   // E.g.,
26610   // vaddps (%rsi,%drx), %ymm0, %ymm1
26611   // Requires two allocations (one for the load, one for the computation)
26612   // whereas:
26613   // vaddps (%rsi), %ymm0, %ymm1
26614   // Requires just 1 allocation, i.e., freeing allocations for other operations
26615   // and having less micro operations to execute.
26616   //
26617   // For some X86 architectures, this is even worse because for instance for
26618   // stores, the complex addressing mode forces the instruction to use the
26619   // "load" ports instead of the dedicated "store" port.
26620   // E.g., on Haswell:
26621   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26622   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26623   if (isLegalAddressingMode(DL, AM, Ty, AS))
26624     // Scale represents reg2 * scale, thus account for 1
26625     // as soon as we use a second register.
26626     return AM.Scale != 0;
26627   return -1;
26628 }
26629
26630 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26631   // Integer division on x86 is expensive. However, when aggressively optimizing
26632   // for code size, we prefer to use a div instruction, as it is usually smaller
26633   // than the alternative sequence.
26634   // The exception to this is vector division. Since x86 doesn't have vector
26635   // integer division, leaving the division as-is is a loss even in terms of
26636   // size, because it will have to be scalarized, while the alternative code
26637   // sequence can be performed in vector form.
26638   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26639                                    Attribute::MinSize);
26640   return OptSize && !VT.isVector();
26641 }