xref: /aosp_15_r20/external/swiftshader/third_party/llvm-10.0/llvm/lib/Target/X86/X86ISelLowering.cpp (revision 03ce13f70fcc45d86ee91b7ee4cab1936a95046e)
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that X86 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86ISelLowering.h"
15 #include "Utils/X86ShuffleDecode.h"
16 #include "X86CallingConv.h"
17 #include "X86FrameLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86IntrinsicsInfo.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/Analysis/BlockFrequencyInfo.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/ProfileSummaryInfo.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/WinEHFuncInfo.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/DiagnosticInfo.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/MC/MCAsmInfo.h"
51 #include "llvm/MC/MCContext.h"
52 #include "llvm/MC/MCExpr.h"
53 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/KnownBits.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Target/TargetOptions.h"
60 #include <algorithm>
61 #include <bitset>
62 #include <cctype>
63 #include <numeric>
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "x86-isel"
67 
68 STATISTIC(NumTailCalls, "Number of tail calls");
69 
70 static cl::opt<int> ExperimentalPrefLoopAlignment(
71     "x86-experimental-pref-loop-alignment", cl::init(4),
72     cl::desc(
73         "Sets the preferable loop alignment for experiments (as log2 bytes)"
74         "(the last x86-experimental-pref-loop-alignment bits"
75         " of the loop header PC will be 0)."),
76     cl::Hidden);
77 
78 // Added in 10.0.
79 static cl::opt<bool> EnableOldKNLABI(
80     "x86-enable-old-knl-abi", cl::init(false),
81     cl::desc("Enables passing v32i16 and v64i8 in 2 YMM registers instead of "
82              "one ZMM register on AVX512F, but not AVX512BW targets."),
83     cl::Hidden);
84 
85 static cl::opt<bool> MulConstantOptimization(
86     "mul-constant-optimization", cl::init(true),
87     cl::desc("Replace 'mul x, Const' with more effective instructions like "
88              "SHIFT, LEA, etc."),
89     cl::Hidden);
90 
91 static cl::opt<bool> ExperimentalUnorderedISEL(
92     "x86-experimental-unordered-atomic-isel", cl::init(false),
93     cl::desc("Use LoadSDNode and StoreSDNode instead of "
94              "AtomicSDNode for unordered atomic loads and "
95              "stores respectively."),
96     cl::Hidden);
97 
98 /// Call this when the user attempts to do something unsupported, like
99 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
100 /// report_fatal_error, so calling code should attempt to recover without
101 /// crashing.
errorUnsupported(SelectionDAG & DAG,const SDLoc & dl,const char * Msg)102 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
103                              const char *Msg) {
104   MachineFunction &MF = DAG.getMachineFunction();
105   DAG.getContext()->diagnose(
106       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
107 }
108 
X86TargetLowering(const X86TargetMachine & TM,const X86Subtarget & STI)109 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
110                                      const X86Subtarget &STI)
111     : TargetLowering(TM), Subtarget(STI) {
112   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
113   X86ScalarSSEf64 = Subtarget.hasSSE2();
114   X86ScalarSSEf32 = Subtarget.hasSSE1();
115   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
116 
117   // Set up the TargetLowering object.
118 
119   // X86 is weird. It always uses i8 for shift amounts and setcc results.
120   setBooleanContents(ZeroOrOneBooleanContent);
121   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
122   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
123 
124   // For 64-bit, since we have so many registers, use the ILP scheduler.
125   // For 32-bit, use the register pressure specific scheduling.
126   // For Atom, always use ILP scheduling.
127   if (Subtarget.isAtom())
128     setSchedulingPreference(Sched::ILP);
129   else if (Subtarget.is64Bit())
130     setSchedulingPreference(Sched::ILP);
131   else
132     setSchedulingPreference(Sched::RegPressure);
133   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
134   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
135 
136   // Bypass expensive divides and use cheaper ones.
137   if (TM.getOptLevel() >= CodeGenOpt::Default) {
138     if (Subtarget.hasSlowDivide32())
139       addBypassSlowDiv(32, 8);
140     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
141       addBypassSlowDiv(64, 32);
142   }
143 
144   if (Subtarget.isTargetWindowsMSVC() ||
145       Subtarget.isTargetWindowsItanium()) {
146     // Setup Windows compiler runtime calls.
147     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
148     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
149     setLibcallName(RTLIB::SREM_I64, "_allrem");
150     setLibcallName(RTLIB::UREM_I64, "_aullrem");
151     setLibcallName(RTLIB::MUL_I64, "_allmul");
152     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
153     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
154     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
155     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
156     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
157   }
158 
159   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
160     // MSVCRT doesn't have powi; fall back to pow
161     setLibcallName(RTLIB::POWI_F32, nullptr);
162     setLibcallName(RTLIB::POWI_F64, nullptr);
163   }
164 
165   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
166   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
167   // FIXME: Should we be limitting the atomic size on other configs? Default is
168   // 1024.
169   if (!Subtarget.hasCmpxchg8b())
170     setMaxAtomicSizeInBitsSupported(32);
171 
172   // Set up the register classes.
173   addRegisterClass(MVT::i8, &X86::GR8RegClass);
174   addRegisterClass(MVT::i16, &X86::GR16RegClass);
175   addRegisterClass(MVT::i32, &X86::GR32RegClass);
176   if (Subtarget.is64Bit())
177     addRegisterClass(MVT::i64, &X86::GR64RegClass);
178 
179   for (MVT VT : MVT::integer_valuetypes())
180     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
181 
182   // We don't accept any truncstore of integer registers.
183   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
184   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
185   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
186   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
187   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
188   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
189 
190   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
191 
192   // SETOEQ and SETUNE require checking two conditions.
193   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
194   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
195   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
196   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
197   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
198   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
199 
200   // Integer absolute.
201   if (Subtarget.hasCMov()) {
202     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
203     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
204   }
205   setOperationAction(ISD::ABS              , MVT::i64  , Custom);
206 
207   // Funnel shifts.
208   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
209     setOperationAction(ShiftOp             , MVT::i16  , Custom);
210     setOperationAction(ShiftOp             , MVT::i32  , Custom);
211     if (Subtarget.is64Bit())
212       setOperationAction(ShiftOp           , MVT::i64  , Custom);
213   }
214 
215   if (!Subtarget.useSoftFloat()) {
216     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
217     // operation.
218     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
219     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
220     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
221     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
222     // We have an algorithm for SSE2, and we turn this into a 64-bit
223     // FILD or VCVTUSI2SS/SD for other targets.
224     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
225     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
226     // We have an algorithm for SSE2->double, and we turn this into a
227     // 64-bit FILD followed by conditional FADD for other targets.
228     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
229     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
230 
231     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
232     // this operation.
233     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
234     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
235     // SSE has no i16 to fp conversion, only i32. We promote in the handler
236     // to allow f80 to use i16 and f64 to use i16 with sse1 only
237     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
238     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
239     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
240     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
241     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
242     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
243     // are Legal, f80 is custom lowered.
244     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
245     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
246 
247     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
248     // this operation.
249     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
250     // FIXME: This doesn't generate invalid exception when it should. PR44019.
251     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
252     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
253     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
254     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
255     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
256     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
257     // are Legal, f80 is custom lowered.
258     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
259     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
260 
261     // Handle FP_TO_UINT by promoting the destination to a larger signed
262     // conversion.
263     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
264     // FIXME: This doesn't generate invalid exception when it should. PR44019.
265     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
266     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
267     // FIXME: This doesn't generate invalid exception when it should. PR44019.
268     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
269     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
270     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
271     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
272     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
273   }
274 
275   // Handle address space casts between mixed sized pointers.
276   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
277   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
278 
279   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
280   if (!X86ScalarSSEf64) {
281     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
282     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
283     if (Subtarget.is64Bit()) {
284       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
285       // Without SSE, i64->f64 goes through memory.
286       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
287     }
288   } else if (!Subtarget.is64Bit())
289     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
290 
291   // Scalar integer divide and remainder are lowered to use operations that
292   // produce two results, to match the available instructions. This exposes
293   // the two-result form to trivial CSE, which is able to combine x/y and x%y
294   // into a single instruction.
295   //
296   // Scalar integer multiply-high is also lowered to use two-result
297   // operations, to match the available instructions. However, plain multiply
298   // (low) operations are left as Legal, as there are single-result
299   // instructions for this in x86. Using the two-result multiply instructions
300   // when both high and low results are needed must be arranged by dagcombine.
301   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
302     setOperationAction(ISD::MULHS, VT, Expand);
303     setOperationAction(ISD::MULHU, VT, Expand);
304     setOperationAction(ISD::SDIV, VT, Expand);
305     setOperationAction(ISD::UDIV, VT, Expand);
306     setOperationAction(ISD::SREM, VT, Expand);
307     setOperationAction(ISD::UREM, VT, Expand);
308   }
309 
310   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
311   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
312   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
313                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
314     setOperationAction(ISD::BR_CC,     VT, Expand);
315     setOperationAction(ISD::SELECT_CC, VT, Expand);
316   }
317   if (Subtarget.is64Bit())
318     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
320   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
321   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
322 
323   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
324   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
325   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
326   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
327   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
328 
329   // Promote the i8 variants and force them on up to i32 which has a shorter
330   // encoding.
331   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
332   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
333   if (!Subtarget.hasBMI()) {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
335     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
336     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
337     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
338     if (Subtarget.is64Bit()) {
339       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
340       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
341     }
342   }
343 
344   if (Subtarget.hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
348     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget.is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361 
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369 
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP16_TO_FP, MVT::f128, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
375   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
376   setOperationAction(ISD::FP_TO_FP16, MVT::f128, Expand);
377 
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
386 
387   if (Subtarget.hasPOPCNT()) {
388     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
389   } else {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
391     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
393     if (Subtarget.is64Bit())
394       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
395     else
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
397   }
398 
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400 
401   if (!Subtarget.hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403 
404   // X86 wants to expand cmov itself.
405   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
406     setOperationAction(ISD::SELECT, VT, Custom);
407     setOperationAction(ISD::SETCC, VT, Custom);
408     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
409     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
410   }
411   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
412     if (VT == MVT::i64 && !Subtarget.is64Bit())
413       continue;
414     setOperationAction(ISD::SELECT, VT, Custom);
415     setOperationAction(ISD::SETCC,  VT, Custom);
416   }
417 
418   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
419   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
420   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
421 
422   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
423   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
424   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
425   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
426   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
427   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
428   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
429     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
430 
431   // Darwin ABI issue.
432   for (auto VT : { MVT::i32, MVT::i64 }) {
433     if (VT == MVT::i64 && !Subtarget.is64Bit())
434       continue;
435     setOperationAction(ISD::ConstantPool    , VT, Custom);
436     setOperationAction(ISD::JumpTable       , VT, Custom);
437     setOperationAction(ISD::GlobalAddress   , VT, Custom);
438     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
439     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
440     setOperationAction(ISD::BlockAddress    , VT, Custom);
441   }
442 
443   // 64-bit shl, sra, srl (iff 32-bit x86)
444   for (auto VT : { MVT::i32, MVT::i64 }) {
445     if (VT == MVT::i64 && !Subtarget.is64Bit())
446       continue;
447     setOperationAction(ISD::SHL_PARTS, VT, Custom);
448     setOperationAction(ISD::SRA_PARTS, VT, Custom);
449     setOperationAction(ISD::SRL_PARTS, VT, Custom);
450   }
451 
452   if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
453     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
454 
455   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
456 
457   // Expand certain atomics
458   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
459     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
460     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
461     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
463     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
464     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
465     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466   }
467 
468   if (!Subtarget.is64Bit())
469     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
470 
471   if (Subtarget.hasCmpxchg16b()) {
472     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
473   }
474 
475   // FIXME - use subtarget debug flags
476   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
477       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
478       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481 
482   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
484 
485   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
486   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
487 
488   setOperationAction(ISD::TRAP, MVT::Other, Legal);
489   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
490 
491   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
492   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
493   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
494   bool Is64Bit = Subtarget.is64Bit();
495   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
496   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
497 
498   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
499   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
500 
501   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
502 
503   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
504   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
505   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
506 
507   if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
508     // f32 and f64 use SSE.
509     // Set up the FP register classes.
510     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
511                                                      : &X86::FR32RegClass);
512     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
513                                                      : &X86::FR64RegClass);
514 
515     // Disable f32->f64 extload as we can only generate this in one instruction
516     // under optsize. So its easier to pattern match (fpext (load)) for that
517     // case instead of needing to emit 2 instructions for extload in the
518     // non-optsize case.
519     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
520 
521     for (auto VT : { MVT::f32, MVT::f64 }) {
522       // Use ANDPD to simulate FABS.
523       setOperationAction(ISD::FABS, VT, Custom);
524 
525       // Use XORP to simulate FNEG.
526       setOperationAction(ISD::FNEG, VT, Custom);
527 
528       // Use ANDPD and ORPD to simulate FCOPYSIGN.
529       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
530 
531       // These might be better off as horizontal vector ops.
532       setOperationAction(ISD::FADD, VT, Custom);
533       setOperationAction(ISD::FSUB, VT, Custom);
534 
535       // We don't support sin/cos/fmod
536       setOperationAction(ISD::FSIN   , VT, Expand);
537       setOperationAction(ISD::FCOS   , VT, Expand);
538       setOperationAction(ISD::FSINCOS, VT, Expand);
539     }
540 
541     // Lower this to MOVMSK plus an AND.
542     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
543     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
544 
545   } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
546     // Use SSE for f32, x87 for f64.
547     // Set up the FP register classes.
548     addRegisterClass(MVT::f32, &X86::FR32RegClass);
549     if (UseX87)
550       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
551 
552     // Use ANDPS to simulate FABS.
553     setOperationAction(ISD::FABS , MVT::f32, Custom);
554 
555     // Use XORP to simulate FNEG.
556     setOperationAction(ISD::FNEG , MVT::f32, Custom);
557 
558     if (UseX87)
559       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
560 
561     // Use ANDPS and ORPS to simulate FCOPYSIGN.
562     if (UseX87)
563       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565 
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570 
571     if (UseX87) {
572       // Always expand sin/cos functions even though x87 has an instruction.
573       setOperationAction(ISD::FSIN, MVT::f64, Expand);
574       setOperationAction(ISD::FCOS, MVT::f64, Expand);
575       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
576     }
577   } else if (UseX87) {
578     // f32 and f64 in x87.
579     // Set up the FP register classes.
580     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
581     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
582 
583     for (auto VT : { MVT::f32, MVT::f64 }) {
584       setOperationAction(ISD::UNDEF,     VT, Expand);
585       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
586 
587       // Always expand sin/cos functions even though x87 has an instruction.
588       setOperationAction(ISD::FSIN   , VT, Expand);
589       setOperationAction(ISD::FCOS   , VT, Expand);
590       setOperationAction(ISD::FSINCOS, VT, Expand);
591     }
592   }
593 
594   // Expand FP32 immediates into loads from the stack, save special cases.
595   if (isTypeLegal(MVT::f32)) {
596     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
597       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
598       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
599       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
600       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
601     } else // SSE immediates.
602       addLegalFPImmediate(APFloat(+0.0f)); // xorps
603   }
604   // Expand FP64 immediates into loads from the stack, save special cases.
605   if (isTypeLegal(MVT::f64)) {
606     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
607       addLegalFPImmediate(APFloat(+0.0)); // FLD0
608       addLegalFPImmediate(APFloat(+1.0)); // FLD1
609       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611     } else // SSE immediates.
612       addLegalFPImmediate(APFloat(+0.0)); // xorpd
613   }
614   // Handle constrained floating-point operations of scalar.
615   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
616   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
617   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
618   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
619   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
620   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
621   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
622   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
623   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
624   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
625   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
626   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
627   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
628 
629   // We don't support FMA.
630   setOperationAction(ISD::FMA, MVT::f64, Expand);
631   setOperationAction(ISD::FMA, MVT::f32, Expand);
632 
633   // f80 always uses X87.
634   if (UseX87) {
635     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
636     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
638     {
639       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
640       addLegalFPImmediate(TmpFlt);  // FLD0
641       TmpFlt.changeSign();
642       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
643 
644       bool ignored;
645       APFloat TmpFlt2(+1.0);
646       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
647                       &ignored);
648       addLegalFPImmediate(TmpFlt2);  // FLD1
649       TmpFlt2.changeSign();
650       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
651     }
652 
653     // Always expand sin/cos functions even though x87 has an instruction.
654     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
655     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
656     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
657 
658     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
659     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
660     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
661     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
662     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
663     setOperationAction(ISD::FMA, MVT::f80, Expand);
664     setOperationAction(ISD::LROUND, MVT::f80, Expand);
665     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
666     setOperationAction(ISD::LRINT, MVT::f80, Expand);
667     setOperationAction(ISD::LLRINT, MVT::f80, Expand);
668 
669     // Handle constrained floating-point operations of scalar.
670     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
671     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
672     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
673     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
674     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
675     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
676     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
677     // as Custom.
678     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
679   }
680 
681   // f128 uses xmm registers, but most operations require libcalls.
682   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
683     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
684                                                    : &X86::VR128RegClass);
685 
686     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
687 
688     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
689     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
690     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
691     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
692     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
693     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
694     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
695     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
696     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
697     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
698 
699     setOperationAction(ISD::FABS, MVT::f128, Custom);
700     setOperationAction(ISD::FNEG, MVT::f128, Custom);
701     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
702 
703     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
704     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
705     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
706     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
707     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
708     // No STRICT_FSINCOS
709     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
710     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
711 
712     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
713     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
714     // We need to custom handle any FP_ROUND with an f128 input, but
715     // LegalizeDAG uses the result type to know when to run a custom handler.
716     // So we have to list all legal floating point result types here.
717     if (isTypeLegal(MVT::f32)) {
718       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
719       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
720     }
721     if (isTypeLegal(MVT::f64)) {
722       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
723       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
724     }
725     if (isTypeLegal(MVT::f80)) {
726       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
727       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
728     }
729 
730     setOperationAction(ISD::SETCC, MVT::f128, Custom);
731 
732     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
733     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
734     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
735     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
736     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
737     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
738   }
739 
740   // Always use a library call for pow.
741   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
742   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
743   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
744   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
745 
746   setOperationAction(ISD::FLOG, MVT::f80, Expand);
747   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
748   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
749   setOperationAction(ISD::FEXP, MVT::f80, Expand);
750   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
751   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
752   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
753 
754   // Some FP actions are always expanded for vector types.
755   for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
756                    MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
757     setOperationAction(ISD::FSIN,      VT, Expand);
758     setOperationAction(ISD::FSINCOS,   VT, Expand);
759     setOperationAction(ISD::FCOS,      VT, Expand);
760     setOperationAction(ISD::FREM,      VT, Expand);
761     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
762     setOperationAction(ISD::FPOW,      VT, Expand);
763     setOperationAction(ISD::FLOG,      VT, Expand);
764     setOperationAction(ISD::FLOG2,     VT, Expand);
765     setOperationAction(ISD::FLOG10,    VT, Expand);
766     setOperationAction(ISD::FEXP,      VT, Expand);
767     setOperationAction(ISD::FEXP2,     VT, Expand);
768   }
769 
770   // First set operation action for all vector types to either promote
771   // (for widening) or expand (for scalarization). Then we will selectively
772   // turn on ones that can be effectively codegen'd.
773   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
774     setOperationAction(ISD::SDIV, VT, Expand);
775     setOperationAction(ISD::UDIV, VT, Expand);
776     setOperationAction(ISD::SREM, VT, Expand);
777     setOperationAction(ISD::UREM, VT, Expand);
778     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
779     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
780     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
781     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
782     setOperationAction(ISD::FMA,  VT, Expand);
783     setOperationAction(ISD::FFLOOR, VT, Expand);
784     setOperationAction(ISD::FCEIL, VT, Expand);
785     setOperationAction(ISD::FTRUNC, VT, Expand);
786     setOperationAction(ISD::FRINT, VT, Expand);
787     setOperationAction(ISD::FNEARBYINT, VT, Expand);
788     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
789     setOperationAction(ISD::MULHS, VT, Expand);
790     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
791     setOperationAction(ISD::MULHU, VT, Expand);
792     setOperationAction(ISD::SDIVREM, VT, Expand);
793     setOperationAction(ISD::UDIVREM, VT, Expand);
794     setOperationAction(ISD::CTPOP, VT, Expand);
795     setOperationAction(ISD::CTTZ, VT, Expand);
796     setOperationAction(ISD::CTLZ, VT, Expand);
797     setOperationAction(ISD::ROTL, VT, Expand);
798     setOperationAction(ISD::ROTR, VT, Expand);
799     setOperationAction(ISD::BSWAP, VT, Expand);
800     setOperationAction(ISD::SETCC, VT, Expand);
801     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
802     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
803     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
804     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
805     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
806     setOperationAction(ISD::TRUNCATE, VT, Expand);
807     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
808     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
809     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
810     setOperationAction(ISD::SELECT_CC, VT, Expand);
811     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
812       setTruncStoreAction(InnerVT, VT, Expand);
813 
814       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
815       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
816 
817       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
818       // types, we have to deal with them whether we ask for Expansion or not.
819       // Setting Expand causes its own optimisation problems though, so leave
820       // them legal.
821       if (VT.getVectorElementType() == MVT::i1)
822         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
823 
824       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
825       // split/scalarized right now.
826       if (VT.getVectorElementType() == MVT::f16)
827         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
828     }
829   }
830 
831   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
832   // with -msoft-float, disable use of MMX as well.
833   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
834     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
835     // No operations on x86mmx supported, everything uses intrinsics.
836   }
837 
838   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
839     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
840                                                     : &X86::VR128RegClass);
841 
842     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
843     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
844     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
845     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
846     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
847     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
848     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
849     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
850 
851     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
852     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
853 
854     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
855     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
856     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
857     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
858     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
859   }
860 
861   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
862     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
863                                                     : &X86::VR128RegClass);
864 
865     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
866     // registers cannot be used even for integer operations.
867     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
868                                                     : &X86::VR128RegClass);
869     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
870                                                     : &X86::VR128RegClass);
871     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
872                                                     : &X86::VR128RegClass);
873     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
874                                                     : &X86::VR128RegClass);
875 
876     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
877                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
878       setOperationAction(ISD::SDIV, VT, Custom);
879       setOperationAction(ISD::SREM, VT, Custom);
880       setOperationAction(ISD::UDIV, VT, Custom);
881       setOperationAction(ISD::UREM, VT, Custom);
882     }
883 
884     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
885     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
886     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
887 
888     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
889     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
890     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
891     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
892     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
893     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
894     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
895     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
896     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
897     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
898     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
899     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
900     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
901 
902     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
903       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
904       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
905       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
906       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
907     }
908 
909     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
910     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
911     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
912     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
913     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
914     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
915     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
916     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
917     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
918     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
919     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
920     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
921 
922     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
923     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
924     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
925 
926     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
927       setOperationAction(ISD::SETCC,              VT, Custom);
928       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
929       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
930       setOperationAction(ISD::CTPOP,              VT, Custom);
931       setOperationAction(ISD::ABS,                VT, Custom);
932 
933       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
934       // setcc all the way to isel and prefer SETGT in some isel patterns.
935       setCondCodeAction(ISD::SETLT, VT, Custom);
936       setCondCodeAction(ISD::SETLE, VT, Custom);
937     }
938 
939     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
940       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
941       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
942       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
943       setOperationAction(ISD::VSELECT,            VT, Custom);
944       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
945     }
946 
947     for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
948       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
949       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
950       setOperationAction(ISD::VSELECT,            VT, Custom);
951 
952       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
953         continue;
954 
955       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
956       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
957     }
958 
959     // Custom lower v2i64 and v2f64 selects.
960     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
961     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
962     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
963     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
964     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
965 
966     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
967     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
968     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Legal);
969     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
970 
971     // Custom legalize these to avoid over promotion or custom promotion.
972     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
973       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
974       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
975       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
976       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
977     }
978 
979     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
980     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Legal);
981     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
982     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
983 
984     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
985     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
986 
987     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
988     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
989 
990     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
991     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
992     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
993     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
994     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
995 
996     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
997     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
998     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
999     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1000 
1001     // We want to legalize this to an f64 load rather than an i64 load on
1002     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1003     // store.
1004     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1005     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1006     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1007     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1008     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1009     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1010 
1011     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1012     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1013     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1014     if (!Subtarget.hasAVX512())
1015       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1016 
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1019     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1020 
1021     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1022 
1023     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1024     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1025     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1026     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1027     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1028     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1029 
1030     // In the customized shift lowering, the legal v4i32/v2i64 cases
1031     // in AVX2 will be recognized.
1032     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1033       setOperationAction(ISD::SRL,              VT, Custom);
1034       setOperationAction(ISD::SHL,              VT, Custom);
1035       setOperationAction(ISD::SRA,              VT, Custom);
1036     }
1037 
1038     setOperationAction(ISD::ROTL,               MVT::v4i32, Custom);
1039     setOperationAction(ISD::ROTL,               MVT::v8i16, Custom);
1040 
1041     // With AVX512, expanding (and promoting the shifts) is better.
1042     if (!Subtarget.hasAVX512())
1043       setOperationAction(ISD::ROTL,             MVT::v16i8, Custom);
1044 
1045     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1046     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1047     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1048     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1049     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1050   }
1051 
1052   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1053     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1054     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1055     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1056     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1057     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1058     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1059     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1060     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1061 
1062     // These might be better off as horizontal vector ops.
1063     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1064     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1065     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1066     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1067   }
1068 
1069   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1070     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1071       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1072       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1073       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1074       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1075       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1076       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1077       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1078       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1079       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1080       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1081     }
1082 
1083     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1084     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1085     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1086     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1087     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1088     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1089     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1090     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1091 
1092     // FIXME: Do we need to handle scalar-to-vector here?
1093     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1094 
1095     // We directly match byte blends in the backend as they match the VSELECT
1096     // condition form.
1097     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1098 
1099     // SSE41 brings specific instructions for doing vector sign extend even in
1100     // cases where we don't have SRA.
1101     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1102       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1103       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1104     }
1105 
1106     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1107     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1108       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1109       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1110       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1111       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1112       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1113       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1114     }
1115 
1116     // i8 vectors are custom because the source register and source
1117     // source memory operand types are not the same width.
1118     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1119 
1120     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1121       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1122       // do the pre and post work in the vector domain.
1123       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1124       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1125       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1126       // so that DAG combine doesn't try to turn it into uint_to_fp.
1127       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1128       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1129     }
1130   }
1131 
1132   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1133     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1134                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1135       setOperationAction(ISD::ROTL, VT, Custom);
1136 
1137     // XOP can efficiently perform BITREVERSE with VPPERM.
1138     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1139       setOperationAction(ISD::BITREVERSE, VT, Custom);
1140 
1141     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1142                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1143       setOperationAction(ISD::BITREVERSE, VT, Custom);
1144   }
1145 
1146   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1147     bool HasInt256 = Subtarget.hasInt256();
1148 
1149     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1150                                                      : &X86::VR256RegClass);
1151     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1152                                                      : &X86::VR256RegClass);
1153     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1154                                                      : &X86::VR256RegClass);
1155     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1156                                                      : &X86::VR256RegClass);
1157     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1158                                                      : &X86::VR256RegClass);
1159     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1160                                                      : &X86::VR256RegClass);
1161 
1162     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1163       setOperationAction(ISD::FFLOOR,            VT, Legal);
1164       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1165       setOperationAction(ISD::FCEIL,             VT, Legal);
1166       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1167       setOperationAction(ISD::FTRUNC,            VT, Legal);
1168       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1169       setOperationAction(ISD::FRINT,             VT, Legal);
1170       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1171       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1172       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1173       setOperationAction(ISD::FNEG,              VT, Custom);
1174       setOperationAction(ISD::FABS,              VT, Custom);
1175       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1176     }
1177 
1178     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1179     // even though v8i16 is a legal type.
1180     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1181     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1182     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1183     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1184     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Legal);
1185     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Legal);
1186 
1187     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1188     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Legal);
1189 
1190     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1191     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1192     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1193     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1194     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1195     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1196     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1197     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1198     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1199     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
1200     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1201     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1202 
1203     if (!Subtarget.hasAVX512())
1204       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1205 
1206     // In the customized shift lowering, the legal v8i32/v4i64 cases
1207     // in AVX2 will be recognized.
1208     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1209       setOperationAction(ISD::SRL, VT, Custom);
1210       setOperationAction(ISD::SHL, VT, Custom);
1211       setOperationAction(ISD::SRA, VT, Custom);
1212     }
1213 
1214     // These types need custom splitting if their input is a 128-bit vector.
1215     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1216     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1218     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1219 
1220     setOperationAction(ISD::ROTL,              MVT::v8i32,  Custom);
1221     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1222 
1223     // With BWI, expanding (and promoting the shifts) is the better.
1224     if (!Subtarget.hasBWI())
1225       setOperationAction(ISD::ROTL,            MVT::v32i8,  Custom);
1226 
1227     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1228     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1229     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1230     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1231     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1233 
1234     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1235       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1236       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1237       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1238     }
1239 
1240     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1241     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1242     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1243     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1244 
1245     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1246       setOperationAction(ISD::SETCC,           VT, Custom);
1247       setOperationAction(ISD::STRICT_FSETCC,   VT, Custom);
1248       setOperationAction(ISD::STRICT_FSETCCS,  VT, Custom);
1249       setOperationAction(ISD::CTPOP,           VT, Custom);
1250       setOperationAction(ISD::CTLZ,            VT, Custom);
1251 
1252       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1253       // setcc all the way to isel and prefer SETGT in some isel patterns.
1254       setCondCodeAction(ISD::SETLT, VT, Custom);
1255       setCondCodeAction(ISD::SETLE, VT, Custom);
1256     }
1257 
1258     if (Subtarget.hasAnyFMA()) {
1259       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1260                        MVT::v2f64, MVT::v4f64 }) {
1261         setOperationAction(ISD::FMA, VT, Legal);
1262         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1263       }
1264     }
1265 
1266     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1267       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1268       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1269     }
1270 
1271     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1272     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1273     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1274     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1275 
1276     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1277     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1278     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1279     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1280     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1281     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1282 
1283     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1284     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1285     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1286     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1287     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1288 
1289     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1290     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1291     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1292     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1293     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1294     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1295     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1296     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1297 
1298     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1299       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1300       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1301       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1302       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1303       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1304     }
1305 
1306     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1307       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1308       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1309     }
1310 
1311     if (HasInt256) {
1312       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1313       // when we have a 256bit-wide blend with immediate.
1314       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1315       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1316 
1317       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1318       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1319         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1320         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1321         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1322         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1323         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1324         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1325       }
1326     }
1327 
1328     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1329                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1330       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1331       setOperationAction(ISD::MSTORE, VT, Legal);
1332     }
1333 
1334     // Extract subvector is special because the value type
1335     // (result) is 128-bit but the source is 256-bit wide.
1336     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1337                      MVT::v4f32, MVT::v2f64 }) {
1338       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1339     }
1340 
1341     // Custom lower several nodes for 256-bit types.
1342     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1343                     MVT::v8f32, MVT::v4f64 }) {
1344       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1345       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1346       setOperationAction(ISD::VSELECT,            VT, Custom);
1347       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1348       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1349       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1350       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1351       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1352       setOperationAction(ISD::STORE,              VT, Custom);
1353     }
1354 
1355     if (HasInt256) {
1356       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1357 
1358       // Custom legalize 2x32 to get a little better code.
1359       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1360       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1361 
1362       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1363                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1364         setOperationAction(ISD::MGATHER,  VT, Custom);
1365     }
1366   }
1367 
1368   // This block controls legalization of the mask vector sizes that are
1369   // available with AVX512. 512-bit vectors are in a separate block controlled
1370   // by useAVX512Regs.
1371   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1372     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1373     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1374     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1375     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1376     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1377 
1378     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1379     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1380     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1381 
1382     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1383     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1384     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1385     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1386     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1387     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1388     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1389     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1390     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1391     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1392     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1393     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1394 
1395     // There is no byte sized k-register load or store without AVX512DQ.
1396     if (!Subtarget.hasDQI()) {
1397       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1398       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1399       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1400       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1401 
1402       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1403       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1404       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1405       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1406     }
1407 
1408     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1409     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1410       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1411       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1412       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1413     }
1414 
1415     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1416       setOperationAction(ISD::ADD,              VT, Custom);
1417       setOperationAction(ISD::SUB,              VT, Custom);
1418       setOperationAction(ISD::MUL,              VT, Custom);
1419       setOperationAction(ISD::SETCC,            VT, Custom);
1420       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1421       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1422       setOperationAction(ISD::SELECT,           VT, Custom);
1423       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1424       setOperationAction(ISD::UADDSAT,          VT, Custom);
1425       setOperationAction(ISD::SADDSAT,          VT, Custom);
1426       setOperationAction(ISD::USUBSAT,          VT, Custom);
1427       setOperationAction(ISD::SSUBSAT,          VT, Custom);
1428 
1429       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1430       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1431       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1432       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1433       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1434       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1435       setOperationAction(ISD::VSELECT,          VT,  Expand);
1436     }
1437 
1438     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1439       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1440   }
1441 
1442   // This block controls legalization for 512-bit operations with 32/64 bit
1443   // elements. 512-bits can be disabled based on prefer-vector-width and
1444   // required-vector-width function attributes.
1445   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1446     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1447     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1448     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1449     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1450 
1451     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1452       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1453       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1454       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1455       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1456       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1457     }
1458 
1459     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1460       setOperationAction(ISD::FNEG,  VT, Custom);
1461       setOperationAction(ISD::FABS,  VT, Custom);
1462       setOperationAction(ISD::FMA,   VT, Legal);
1463       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1464       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1465     }
1466 
1467     for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1468       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1469       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1470       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1471       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1472     }
1473     setOperationAction(ISD::FP_TO_SINT,        MVT::v16i32, Legal);
1474     setOperationAction(ISD::FP_TO_UINT,        MVT::v16i32, Legal);
1475     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Legal);
1476     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Legal);
1477     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Legal);
1478     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Legal);
1479     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Legal);
1480     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Legal);
1481 
1482     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1483     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1484     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1485     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1486     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1487     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1488     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1489     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1490     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1491     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1492     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64,  Legal);
1493     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1494 
1495     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1496     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1497     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1498     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1499     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1500 
1501     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1502     // to 512-bit rather than use the AVX2 instructions so that we can use
1503     // k-masks.
1504     if (!Subtarget.hasVLX()) {
1505       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1506            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1507         setOperationAction(ISD::MLOAD,  VT, Custom);
1508         setOperationAction(ISD::MSTORE, VT, Custom);
1509       }
1510     }
1511 
1512     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1513     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1514     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1515     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1516     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1517     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1518     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1519     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1520 
1521     // Need to custom widen this if we don't have AVX512BW.
1522     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i8, Custom);
1525 
1526     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1527       setOperationAction(ISD::FFLOOR,            VT, Legal);
1528       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1529       setOperationAction(ISD::FCEIL,             VT, Legal);
1530       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1531       setOperationAction(ISD::FTRUNC,            VT, Legal);
1532       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1533       setOperationAction(ISD::FRINT,             VT, Legal);
1534       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1535       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1536       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1537 
1538       setOperationAction(ISD::SELECT,           VT, Custom);
1539     }
1540 
1541     // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1542     for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1543       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1544       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1545     }
1546 
1547     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1548     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1549     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1550     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1551 
1552     setOperationAction(ISD::MUL,                MVT::v8i64, Custom);
1553     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1554 
1555     setOperationAction(ISD::MULHU,              MVT::v16i32,  Custom);
1556     setOperationAction(ISD::MULHS,              MVT::v16i32,  Custom);
1557 
1558     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1559       setOperationAction(ISD::SMAX,             VT, Legal);
1560       setOperationAction(ISD::UMAX,             VT, Legal);
1561       setOperationAction(ISD::SMIN,             VT, Legal);
1562       setOperationAction(ISD::UMIN,             VT, Legal);
1563       setOperationAction(ISD::ABS,              VT, Legal);
1564       setOperationAction(ISD::SRL,              VT, Custom);
1565       setOperationAction(ISD::SHL,              VT, Custom);
1566       setOperationAction(ISD::SRA,              VT, Custom);
1567       setOperationAction(ISD::CTPOP,            VT, Custom);
1568       setOperationAction(ISD::ROTL,             VT, Custom);
1569       setOperationAction(ISD::ROTR,             VT, Custom);
1570       setOperationAction(ISD::SETCC,            VT, Custom);
1571       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1572       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1573       setOperationAction(ISD::SELECT,           VT, Custom);
1574 
1575       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1576       // setcc all the way to isel and prefer SETGT in some isel patterns.
1577       setCondCodeAction(ISD::SETLT, VT, Custom);
1578       setCondCodeAction(ISD::SETLE, VT, Custom);
1579     }
1580 
1581     if (Subtarget.hasDQI()) {
1582       setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1583       setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1584       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i64, Legal);
1585       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i64, Legal);
1586       setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1587       setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1588       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i64, Legal);
1589       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i64, Legal);
1590 
1591       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1592     }
1593 
1594     if (Subtarget.hasCDI()) {
1595       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1596       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1597         setOperationAction(ISD::CTLZ,            VT, Legal);
1598       }
1599     } // Subtarget.hasCDI()
1600 
1601     if (Subtarget.hasVPOPCNTDQ()) {
1602       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1603         setOperationAction(ISD::CTPOP, VT, Legal);
1604     }
1605 
1606     // Extract subvector is special because the value type
1607     // (result) is 256-bit but the source is 512-bit wide.
1608     // 128-bit was made Legal under AVX1.
1609     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1610                      MVT::v8f32, MVT::v4f64 })
1611       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1612 
1613     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1614       setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1615       setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1616       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1617       setOperationAction(ISD::VSELECT,             VT, Custom);
1618       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1619       setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1620       setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Legal);
1621       setOperationAction(ISD::MLOAD,               VT, Legal);
1622       setOperationAction(ISD::MSTORE,              VT, Legal);
1623       setOperationAction(ISD::MGATHER,             VT, Custom);
1624       setOperationAction(ISD::MSCATTER,            VT, Custom);
1625     }
1626     if (!Subtarget.hasBWI()) {
1627       // Need to custom split v32i16/v64i8 bitcasts.
1628       setOperationAction(ISD::BITCAST, MVT::v32i16, Custom);
1629       setOperationAction(ISD::BITCAST, MVT::v64i8,  Custom);
1630 
1631       // Better to split these into two 256-bit ops.
1632       setOperationAction(ISD::BITREVERSE, MVT::v8i64, Custom);
1633       setOperationAction(ISD::BITREVERSE, MVT::v16i32, Custom);
1634     }
1635 
1636     if (Subtarget.hasVBMI2()) {
1637       for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1638         setOperationAction(ISD::FSHL, VT, Custom);
1639         setOperationAction(ISD::FSHR, VT, Custom);
1640       }
1641     }
1642   }// has  AVX-512
1643 
1644   // This block controls legalization for operations that don't have
1645   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1646   // narrower widths.
1647   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1648     // These operations are handled on non-VLX by artificially widening in
1649     // isel patterns.
1650 
1651     setOperationAction(ISD::FP_TO_UINT, MVT::v8i32,
1652                        Subtarget.hasVLX() ? Legal : Custom);
1653     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32,
1654                        Subtarget.hasVLX() ? Legal : Custom);
1655     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1656     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32,
1657                        Subtarget.hasVLX() ? Legal : Custom);
1658     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32,
1659                        Subtarget.hasVLX() ? Legal : Custom);
1660     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1661     setOperationAction(ISD::UINT_TO_FP, MVT::v8i32,
1662                        Subtarget.hasVLX() ? Legal : Custom);
1663     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32,
1664                        Subtarget.hasVLX() ? Legal : Custom);
1665     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32,
1666                        Subtarget.hasVLX() ? Legal : Custom);
1667     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32,
1668                        Subtarget.hasVLX() ? Legal : Custom);
1669 
1670     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1671       setOperationAction(ISD::SMAX, VT, Legal);
1672       setOperationAction(ISD::UMAX, VT, Legal);
1673       setOperationAction(ISD::SMIN, VT, Legal);
1674       setOperationAction(ISD::UMIN, VT, Legal);
1675       setOperationAction(ISD::ABS,  VT, Legal);
1676     }
1677 
1678     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1679       setOperationAction(ISD::ROTL,     VT, Custom);
1680       setOperationAction(ISD::ROTR,     VT, Custom);
1681     }
1682 
1683     // Custom legalize 2x32 to get a little better code.
1684     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1685     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1686 
1687     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1688                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1689       setOperationAction(ISD::MSCATTER, VT, Custom);
1690 
1691     if (Subtarget.hasDQI()) {
1692       for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1693         setOperationAction(ISD::SINT_TO_FP, VT,
1694                            Subtarget.hasVLX() ? Legal : Custom);
1695         setOperationAction(ISD::UINT_TO_FP, VT,
1696                            Subtarget.hasVLX() ? Legal : Custom);
1697         setOperationAction(ISD::STRICT_SINT_TO_FP, VT,
1698                            Subtarget.hasVLX() ? Legal : Custom);
1699         setOperationAction(ISD::STRICT_UINT_TO_FP, VT,
1700                            Subtarget.hasVLX() ? Legal : Custom);
1701         setOperationAction(ISD::FP_TO_SINT, VT,
1702                            Subtarget.hasVLX() ? Legal : Custom);
1703         setOperationAction(ISD::FP_TO_UINT, VT,
1704                            Subtarget.hasVLX() ? Legal : Custom);
1705         setOperationAction(ISD::STRICT_FP_TO_SINT, VT,
1706                            Subtarget.hasVLX() ? Legal : Custom);
1707         setOperationAction(ISD::STRICT_FP_TO_UINT, VT,
1708                            Subtarget.hasVLX() ? Legal : Custom);
1709         setOperationAction(ISD::MUL,               VT, Legal);
1710       }
1711     }
1712 
1713     if (Subtarget.hasCDI()) {
1714       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1715         setOperationAction(ISD::CTLZ,            VT, Legal);
1716       }
1717     } // Subtarget.hasCDI()
1718 
1719     if (Subtarget.hasVPOPCNTDQ()) {
1720       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1721         setOperationAction(ISD::CTPOP, VT, Legal);
1722     }
1723   }
1724 
1725   // This block control legalization of v32i1/v64i1 which are available with
1726   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1727   // useBWIRegs.
1728   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1729     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1730     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1731 
1732     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1733       setOperationAction(ISD::ADD,                VT, Custom);
1734       setOperationAction(ISD::SUB,                VT, Custom);
1735       setOperationAction(ISD::MUL,                VT, Custom);
1736       setOperationAction(ISD::VSELECT,            VT, Expand);
1737       setOperationAction(ISD::UADDSAT,            VT, Custom);
1738       setOperationAction(ISD::SADDSAT,            VT, Custom);
1739       setOperationAction(ISD::USUBSAT,            VT, Custom);
1740       setOperationAction(ISD::SSUBSAT,            VT, Custom);
1741 
1742       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1743       setOperationAction(ISD::SETCC,              VT, Custom);
1744       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1745       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1746       setOperationAction(ISD::SELECT,             VT, Custom);
1747       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1748       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1749     }
1750 
1751     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1752     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1753     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1754     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1755     for (auto VT : { MVT::v16i1, MVT::v32i1 })
1756       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1757 
1758     // Extends from v32i1 masks to 256-bit vectors.
1759     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1760     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1761     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
1762   }
1763 
1764   // This block controls legalization for v32i16 and v64i8. 512-bits can be
1765   // disabled based on prefer-vector-width and required-vector-width function
1766   // attributes.
1767   if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1768     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1769     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1770 
1771     // Extends from v64i1 masks to 512-bit vectors.
1772     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1773     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1774     setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1775 
1776     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1777     setOperationAction(ISD::MUL,                MVT::v64i8, Custom);
1778     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1779     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1780     setOperationAction(ISD::MULHS,              MVT::v64i8, Custom);
1781     setOperationAction(ISD::MULHU,              MVT::v64i8, Custom);
1782     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1783     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1784     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Legal);
1785     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Legal);
1786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1787     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1788     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i16, Custom);
1789     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v64i8, Custom);
1790     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1791     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1792     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i16, Custom);
1793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1794     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1795     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1796     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1797     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1798     setOperationAction(ISD::BITREVERSE,         MVT::v64i8, Custom);
1799 
1800     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1801     setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1802 
1803     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1804 
1805     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1806       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1807       setOperationAction(ISD::VSELECT,      VT, Custom);
1808       setOperationAction(ISD::ABS,          VT, Legal);
1809       setOperationAction(ISD::SRL,          VT, Custom);
1810       setOperationAction(ISD::SHL,          VT, Custom);
1811       setOperationAction(ISD::SRA,          VT, Custom);
1812       setOperationAction(ISD::MLOAD,        VT, Legal);
1813       setOperationAction(ISD::MSTORE,       VT, Legal);
1814       setOperationAction(ISD::CTPOP,        VT, Custom);
1815       setOperationAction(ISD::CTLZ,         VT, Custom);
1816       setOperationAction(ISD::SMAX,         VT, Legal);
1817       setOperationAction(ISD::UMAX,         VT, Legal);
1818       setOperationAction(ISD::SMIN,         VT, Legal);
1819       setOperationAction(ISD::UMIN,         VT, Legal);
1820       setOperationAction(ISD::SETCC,        VT, Custom);
1821       setOperationAction(ISD::UADDSAT,      VT, Legal);
1822       setOperationAction(ISD::SADDSAT,      VT, Legal);
1823       setOperationAction(ISD::USUBSAT,      VT, Legal);
1824       setOperationAction(ISD::SSUBSAT,      VT, Legal);
1825       setOperationAction(ISD::SELECT,       VT, Custom);
1826 
1827       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1828       // setcc all the way to isel and prefer SETGT in some isel patterns.
1829       setCondCodeAction(ISD::SETLT, VT, Custom);
1830       setCondCodeAction(ISD::SETLE, VT, Custom);
1831     }
1832 
1833     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1834       setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1835     }
1836 
1837     if (Subtarget.hasBITALG()) {
1838       for (auto VT : { MVT::v64i8, MVT::v32i16 })
1839         setOperationAction(ISD::CTPOP, VT, Legal);
1840     }
1841 
1842     if (Subtarget.hasVBMI2()) {
1843       setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
1844       setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
1845     }
1846   }
1847 
1848   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1849     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1850       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1851       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1852     }
1853 
1854     // These operations are handled on non-VLX by artificially widening in
1855     // isel patterns.
1856     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1857 
1858     if (Subtarget.hasBITALG()) {
1859       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1860         setOperationAction(ISD::CTPOP, VT, Legal);
1861     }
1862   }
1863 
1864   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1865     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1866     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1867     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1868     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1869     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1870 
1871     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1872     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1873     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1874     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1875     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1876 
1877     if (Subtarget.hasDQI()) {
1878       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1879       // v2f32 UINT_TO_FP is already custom under SSE2.
1880       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1881              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
1882              "Unexpected operation action!");
1883       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1884       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
1885       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
1886       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1887       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1888     }
1889 
1890     if (Subtarget.hasBWI()) {
1891       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1892       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1893     }
1894 
1895     if (Subtarget.hasVBMI2()) {
1896       // TODO: Make these legal even without VLX?
1897       for (auto VT : { MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1898                        MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1899         setOperationAction(ISD::FSHL, VT, Custom);
1900         setOperationAction(ISD::FSHR, VT, Custom);
1901       }
1902     }
1903 
1904     setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1905     setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1906     setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1907   }
1908 
1909   // We want to custom lower some of our intrinsics.
1910   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1911   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1912   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1913   if (!Subtarget.is64Bit()) {
1914     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1915   }
1916 
1917   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1918   // handle type legalization for these operations here.
1919   //
1920   // FIXME: We really should do custom legalization for addition and
1921   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1922   // than generic legalization for 64-bit multiplication-with-overflow, though.
1923   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1924     if (VT == MVT::i64 && !Subtarget.is64Bit())
1925       continue;
1926     // Add/Sub/Mul with overflow operations are custom lowered.
1927     setOperationAction(ISD::SADDO, VT, Custom);
1928     setOperationAction(ISD::UADDO, VT, Custom);
1929     setOperationAction(ISD::SSUBO, VT, Custom);
1930     setOperationAction(ISD::USUBO, VT, Custom);
1931     setOperationAction(ISD::SMULO, VT, Custom);
1932     setOperationAction(ISD::UMULO, VT, Custom);
1933 
1934     // Support carry in as value rather than glue.
1935     setOperationAction(ISD::ADDCARRY, VT, Custom);
1936     setOperationAction(ISD::SUBCARRY, VT, Custom);
1937     setOperationAction(ISD::SETCCCARRY, VT, Custom);
1938   }
1939 
1940   if (!Subtarget.is64Bit()) {
1941     // These libcalls are not available in 32-bit.
1942     setLibcallName(RTLIB::SHL_I128, nullptr);
1943     setLibcallName(RTLIB::SRL_I128, nullptr);
1944     setLibcallName(RTLIB::SRA_I128, nullptr);
1945     setLibcallName(RTLIB::MUL_I128, nullptr);
1946   }
1947 
1948   // Combine sin / cos into _sincos_stret if it is available.
1949   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1950       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1951     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1952     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1953   }
1954 
1955   if (Subtarget.isTargetWin64()) {
1956     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1957     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1958     setOperationAction(ISD::SREM, MVT::i128, Custom);
1959     setOperationAction(ISD::UREM, MVT::i128, Custom);
1960     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1961     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1962   }
1963 
1964   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1965   // is. We should promote the value to 64-bits to solve this.
1966   // This is what the CRT headers do - `fmodf` is an inline header
1967   // function casting to f64 and calling `fmod`.
1968   if (Subtarget.is32Bit() &&
1969       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1970     for (ISD::NodeType Op :
1971          {ISD::FCEIL,  ISD::STRICT_FCEIL,
1972           ISD::FCOS,   ISD::STRICT_FCOS,
1973           ISD::FEXP,   ISD::STRICT_FEXP,
1974           ISD::FFLOOR, ISD::STRICT_FFLOOR,
1975           ISD::FREM,   ISD::STRICT_FREM,
1976           ISD::FLOG,   ISD::STRICT_FLOG,
1977           ISD::FLOG10, ISD::STRICT_FLOG10,
1978           ISD::FPOW,   ISD::STRICT_FPOW,
1979           ISD::FSIN,   ISD::STRICT_FSIN})
1980       if (isOperationExpand(Op, MVT::f32))
1981         setOperationAction(Op, MVT::f32, Promote);
1982 
1983   // We have target-specific dag combine patterns for the following nodes:
1984   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1985   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1986   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1987   setTargetDAGCombine(ISD::CONCAT_VECTORS);
1988   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1989   setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1990   setTargetDAGCombine(ISD::BITCAST);
1991   setTargetDAGCombine(ISD::VSELECT);
1992   setTargetDAGCombine(ISD::SELECT);
1993   setTargetDAGCombine(ISD::SHL);
1994   setTargetDAGCombine(ISD::SRA);
1995   setTargetDAGCombine(ISD::SRL);
1996   setTargetDAGCombine(ISD::OR);
1997   setTargetDAGCombine(ISD::AND);
1998   setTargetDAGCombine(ISD::ADD);
1999   setTargetDAGCombine(ISD::FADD);
2000   setTargetDAGCombine(ISD::FSUB);
2001   setTargetDAGCombine(ISD::FNEG);
2002   setTargetDAGCombine(ISD::FMA);
2003   setTargetDAGCombine(ISD::FMINNUM);
2004   setTargetDAGCombine(ISD::FMAXNUM);
2005   setTargetDAGCombine(ISD::SUB);
2006   setTargetDAGCombine(ISD::LOAD);
2007   setTargetDAGCombine(ISD::MLOAD);
2008   setTargetDAGCombine(ISD::STORE);
2009   setTargetDAGCombine(ISD::MSTORE);
2010   setTargetDAGCombine(ISD::TRUNCATE);
2011   setTargetDAGCombine(ISD::ZERO_EXTEND);
2012   setTargetDAGCombine(ISD::ANY_EXTEND);
2013   setTargetDAGCombine(ISD::SIGN_EXTEND);
2014   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
2015   setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
2016   setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
2017   setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
2018   setTargetDAGCombine(ISD::SINT_TO_FP);
2019   setTargetDAGCombine(ISD::UINT_TO_FP);
2020   setTargetDAGCombine(ISD::STRICT_SINT_TO_FP);
2021   setTargetDAGCombine(ISD::STRICT_UINT_TO_FP);
2022   setTargetDAGCombine(ISD::SETCC);
2023   setTargetDAGCombine(ISD::MUL);
2024   setTargetDAGCombine(ISD::XOR);
2025   setTargetDAGCombine(ISD::MSCATTER);
2026   setTargetDAGCombine(ISD::MGATHER);
2027 
2028   computeRegisterProperties(Subtarget.getRegisterInfo());
2029 
2030   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2031   MaxStoresPerMemsetOptSize = 8;
2032   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2033   MaxStoresPerMemcpyOptSize = 4;
2034   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2035   MaxStoresPerMemmoveOptSize = 4;
2036 
2037   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2038   // that needs to benchmarked and balanced with the potential use of vector
2039   // load/store types (PR33329, PR33914).
2040   MaxLoadsPerMemcmp = 2;
2041   MaxLoadsPerMemcmpOptSize = 2;
2042 
2043   // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
2044   setPrefLoopAlignment(Align(1ULL << ExperimentalPrefLoopAlignment));
2045 
2046   // An out-of-order CPU can speculatively execute past a predictable branch,
2047   // but a conditional move could be stalled by an expensive earlier operation.
2048   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2049   EnableExtLdPromotion = true;
2050   setPrefFunctionAlignment(Align(16));
2051 
2052   verifyIntrinsicTables();
2053 
2054   // Default to having -disable-strictnode-mutation on
2055   IsStrictFPEnabled = true;
2056 }
2057 
2058 // This has so far only been implemented for 64-bit MachO.
useLoadStackGuardNode() const2059 bool X86TargetLowering::useLoadStackGuardNode() const {
2060   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2061 }
2062 
useStackGuardXorFP() const2063 bool X86TargetLowering::useStackGuardXorFP() const {
2064   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2065   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2066 }
2067 
emitStackGuardXorFP(SelectionDAG & DAG,SDValue Val,const SDLoc & DL) const2068 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2069                                                const SDLoc &DL) const {
2070   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2071   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2072   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2073   return SDValue(Node, 0);
2074 }
2075 
2076 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const2077 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2078   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
2079     return TypeSplitVector;
2080 
2081   if (VT.getVectorNumElements() != 1 &&
2082       VT.getVectorElementType() != MVT::i1)
2083     return TypeWidenVector;
2084 
2085   return TargetLoweringBase::getPreferredVectorAction(VT);
2086 }
2087 
getRegisterTypeForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const2088 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2089                                                      CallingConv::ID CC,
2090                                                      EVT VT) const {
2091   // v32i1 vectors should be promoted to v32i8 to match avx2.
2092   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
2093     return MVT::v32i8;
2094   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2095   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2096       Subtarget.hasAVX512() &&
2097       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2098        (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
2099        (VT.getVectorNumElements() > 64 && Subtarget.hasBWI())))
2100     return MVT::i8;
2101   // Split v64i1 vectors if we don't have v64i8 available.
2102   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2103       CC != CallingConv::X86_RegCall)
2104     return MVT::v32i1;
2105   // FIXME: Should we just make these types legal and custom split operations?
2106   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !EnableOldKNLABI &&
2107       Subtarget.useAVX512Regs() && !Subtarget.hasBWI())
2108     return MVT::v16i32;
2109   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2110 }
2111 
getNumRegistersForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const2112 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2113                                                           CallingConv::ID CC,
2114                                                           EVT VT) const {
2115   // v32i1 vectors should be promoted to v32i8 to match avx2.
2116   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
2117     return 1;
2118   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2119   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2120       Subtarget.hasAVX512() &&
2121       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2122        (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
2123        (VT.getVectorNumElements() > 64 && Subtarget.hasBWI())))
2124     return VT.getVectorNumElements();
2125   // Split v64i1 vectors if we don't have v64i8 available.
2126   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2127       CC != CallingConv::X86_RegCall)
2128     return 2;
2129   // FIXME: Should we just make these types legal and custom split operations?
2130   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !EnableOldKNLABI &&
2131       Subtarget.useAVX512Regs() && !Subtarget.hasBWI())
2132     return 1;
2133   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2134 }
2135 
getVectorTypeBreakdownForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT,EVT & IntermediateVT,unsigned & NumIntermediates,MVT & RegisterVT) const2136 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2137     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2138     unsigned &NumIntermediates, MVT &RegisterVT) const {
2139   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2140   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2141       Subtarget.hasAVX512() &&
2142       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2143        (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
2144        (VT.getVectorNumElements() > 64 && Subtarget.hasBWI()))) {
2145     RegisterVT = MVT::i8;
2146     IntermediateVT = MVT::i1;
2147     NumIntermediates = VT.getVectorNumElements();
2148     return NumIntermediates;
2149   }
2150 
2151   // Split v64i1 vectors if we don't have v64i8 available.
2152   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2153       CC != CallingConv::X86_RegCall) {
2154     RegisterVT = MVT::v32i1;
2155     IntermediateVT = MVT::v32i1;
2156     NumIntermediates = 2;
2157     return 2;
2158   }
2159 
2160   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2161                                               NumIntermediates, RegisterVT);
2162 }
2163 
getSetCCResultType(const DataLayout & DL,LLVMContext & Context,EVT VT) const2164 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2165                                           LLVMContext& Context,
2166                                           EVT VT) const {
2167   if (!VT.isVector())
2168     return MVT::i8;
2169 
2170   if (Subtarget.hasAVX512()) {
2171     const unsigned NumElts = VT.getVectorNumElements();
2172 
2173     // Figure out what this type will be legalized to.
2174     EVT LegalVT = VT;
2175     while (getTypeAction(Context, LegalVT) != TypeLegal)
2176       LegalVT = getTypeToTransformTo(Context, LegalVT);
2177 
2178     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2179     if (LegalVT.getSimpleVT().is512BitVector())
2180       return EVT::getVectorVT(Context, MVT::i1, NumElts);
2181 
2182     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2183       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2184       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2185       // vXi16/vXi8.
2186       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2187       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2188         return EVT::getVectorVT(Context, MVT::i1, NumElts);
2189     }
2190   }
2191 
2192   return VT.changeVectorElementTypeToInteger();
2193 }
2194 
2195 /// Helper for getByValTypeAlignment to determine
2196 /// the desired ByVal argument alignment.
getMaxByValAlign(Type * Ty,unsigned & MaxAlign)2197 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
2198   if (MaxAlign == 16)
2199     return;
2200   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2201     if (VTy->getBitWidth() == 128)
2202       MaxAlign = 16;
2203   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2204     unsigned EltAlign = 0;
2205     getMaxByValAlign(ATy->getElementType(), EltAlign);
2206     if (EltAlign > MaxAlign)
2207       MaxAlign = EltAlign;
2208   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2209     for (auto *EltTy : STy->elements()) {
2210       unsigned EltAlign = 0;
2211       getMaxByValAlign(EltTy, EltAlign);
2212       if (EltAlign > MaxAlign)
2213         MaxAlign = EltAlign;
2214       if (MaxAlign == 16)
2215         break;
2216     }
2217   }
2218 }
2219 
2220 /// Return the desired alignment for ByVal aggregate
2221 /// function arguments in the caller parameter area. For X86, aggregates
2222 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2223 /// are at 4-byte boundaries.
getByValTypeAlignment(Type * Ty,const DataLayout & DL) const2224 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2225                                                   const DataLayout &DL) const {
2226   if (Subtarget.is64Bit()) {
2227     // Max of 8 and alignment of type.
2228     unsigned TyAlign = DL.getABITypeAlignment(Ty);
2229     if (TyAlign > 8)
2230       return TyAlign;
2231     return 8;
2232   }
2233 
2234   unsigned Align = 4;
2235   if (Subtarget.hasSSE1())
2236     getMaxByValAlign(Ty, Align);
2237   return Align;
2238 }
2239 
2240 /// Returns the target specific optimal type for load
2241 /// and store operations as a result of memset, memcpy, and memmove
2242 /// lowering. If DstAlign is zero that means it's safe to destination
2243 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2244 /// means there isn't a need to check it against alignment requirement,
2245 /// probably because the source does not need to be loaded. If 'IsMemset' is
2246 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2247 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2248 /// source is constant so it does not need to be loaded.
2249 /// It returns EVT::Other if the type should be determined using generic
2250 /// target-independent logic.
2251 /// For vector ops we check that the overall size isn't larger than our
2252 /// preferred vector width.
getOptimalMemOpType(uint64_t Size,unsigned DstAlign,unsigned SrcAlign,bool IsMemset,bool ZeroMemset,bool MemcpyStrSrc,const AttributeList & FuncAttributes) const2253 EVT X86TargetLowering::getOptimalMemOpType(
2254     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
2255     bool ZeroMemset, bool MemcpyStrSrc,
2256     const AttributeList &FuncAttributes) const {
2257   if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2258     if (Size >= 16 && (!Subtarget.isUnalignedMem16Slow() ||
2259                        ((DstAlign == 0 || DstAlign >= 16) &&
2260                         (SrcAlign == 0 || SrcAlign >= 16)))) {
2261       // FIXME: Check if unaligned 64-byte accesses are slow.
2262       if (Size >= 64 && Subtarget.hasAVX512() &&
2263           (Subtarget.getPreferVectorWidth() >= 512)) {
2264         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2265       }
2266       // FIXME: Check if unaligned 32-byte accesses are slow.
2267       if (Size >= 32 && Subtarget.hasAVX() &&
2268           (Subtarget.getPreferVectorWidth() >= 256)) {
2269         // Although this isn't a well-supported type for AVX1, we'll let
2270         // legalization and shuffle lowering produce the optimal codegen. If we
2271         // choose an optimal type with a vector element larger than a byte,
2272         // getMemsetStores() may create an intermediate splat (using an integer
2273         // multiply) before we splat as a vector.
2274         return MVT::v32i8;
2275       }
2276       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2277         return MVT::v16i8;
2278       // TODO: Can SSE1 handle a byte vector?
2279       // If we have SSE1 registers we should be able to use them.
2280       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2281           (Subtarget.getPreferVectorWidth() >= 128))
2282         return MVT::v4f32;
2283     } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2284                !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2285       // Do not use f64 to lower memcpy if source is string constant. It's
2286       // better to use i32 to avoid the loads.
2287       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2288       // The gymnastics of splatting a byte value into an XMM register and then
2289       // only using 8-byte stores (because this is a CPU with slow unaligned
2290       // 16-byte accesses) makes that a loser.
2291       return MVT::f64;
2292     }
2293   }
2294   // This is a compromise. If we reach here, unaligned accesses may be slow on
2295   // this target. However, creating smaller, aligned accesses could be even
2296   // slower and would certainly be a lot more code.
2297   if (Subtarget.is64Bit() && Size >= 8)
2298     return MVT::i64;
2299   return MVT::i32;
2300 }
2301 
isSafeMemOpType(MVT VT) const2302 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2303   if (VT == MVT::f32)
2304     return X86ScalarSSEf32;
2305   else if (VT == MVT::f64)
2306     return X86ScalarSSEf64;
2307   return true;
2308 }
2309 
allowsMisalignedMemoryAccesses(EVT VT,unsigned,unsigned Align,MachineMemOperand::Flags Flags,bool * Fast) const2310 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2311     EVT VT, unsigned, unsigned Align, MachineMemOperand::Flags Flags,
2312     bool *Fast) const {
2313   if (Fast) {
2314     switch (VT.getSizeInBits()) {
2315     default:
2316       // 8-byte and under are always assumed to be fast.
2317       *Fast = true;
2318       break;
2319     case 128:
2320       *Fast = !Subtarget.isUnalignedMem16Slow();
2321       break;
2322     case 256:
2323       *Fast = !Subtarget.isUnalignedMem32Slow();
2324       break;
2325     // TODO: What about AVX-512 (512-bit) accesses?
2326     }
2327   }
2328   // NonTemporal vector memory ops must be aligned.
2329   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2330     // NT loads can only be vector aligned, so if its less aligned than the
2331     // minimum vector size (which we can split the vector down to), we might as
2332     // well use a regular unaligned vector load.
2333     // We don't have any NT loads pre-SSE41.
2334     if (!!(Flags & MachineMemOperand::MOLoad))
2335       return (Align < 16 || !Subtarget.hasSSE41());
2336     return false;
2337   }
2338   // Misaligned accesses of any size are always allowed.
2339   return true;
2340 }
2341 
2342 /// Return the entry encoding for a jump table in the
2343 /// current function.  The returned value is a member of the
2344 /// MachineJumpTableInfo::JTEntryKind enum.
getJumpTableEncoding() const2345 unsigned X86TargetLowering::getJumpTableEncoding() const {
2346   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2347   // symbol.
2348   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2349     return MachineJumpTableInfo::EK_Custom32;
2350 
2351   // Otherwise, use the normal jump table encoding heuristics.
2352   return TargetLowering::getJumpTableEncoding();
2353 }
2354 
useSoftFloat() const2355 bool X86TargetLowering::useSoftFloat() const {
2356   return Subtarget.useSoftFloat();
2357 }
2358 
markLibCallAttributes(MachineFunction * MF,unsigned CC,ArgListTy & Args) const2359 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2360                                               ArgListTy &Args) const {
2361 
2362   // Only relabel X86-32 for C / Stdcall CCs.
2363   if (Subtarget.is64Bit())
2364     return;
2365   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2366     return;
2367   unsigned ParamRegs = 0;
2368   if (auto *M = MF->getFunction().getParent())
2369     ParamRegs = M->getNumberRegisterParameters();
2370 
2371   // Mark the first N int arguments as having reg
2372   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2373     Type *T = Args[Idx].Ty;
2374     if (T->isIntOrPtrTy())
2375       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2376         unsigned numRegs = 1;
2377         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2378           numRegs = 2;
2379         if (ParamRegs < numRegs)
2380           return;
2381         ParamRegs -= numRegs;
2382         Args[Idx].IsInReg = true;
2383       }
2384   }
2385 }
2386 
2387 const MCExpr *
LowerCustomJumpTableEntry(const MachineJumpTableInfo * MJTI,const MachineBasicBlock * MBB,unsigned uid,MCContext & Ctx) const2388 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2389                                              const MachineBasicBlock *MBB,
2390                                              unsigned uid,MCContext &Ctx) const{
2391   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2392   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2393   // entries.
2394   return MCSymbolRefExpr::create(MBB->getSymbol(),
2395                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2396 }
2397 
2398 /// Returns relocation base for the given PIC jumptable.
getPICJumpTableRelocBase(SDValue Table,SelectionDAG & DAG) const2399 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2400                                                     SelectionDAG &DAG) const {
2401   if (!Subtarget.is64Bit())
2402     // This doesn't have SDLoc associated with it, but is not really the
2403     // same as a Register.
2404     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2405                        getPointerTy(DAG.getDataLayout()));
2406   return Table;
2407 }
2408 
2409 /// This returns the relocation base for the given PIC jumptable,
2410 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2411 const MCExpr *X86TargetLowering::
getPICJumpTableRelocBaseExpr(const MachineFunction * MF,unsigned JTI,MCContext & Ctx) const2412 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2413                              MCContext &Ctx) const {
2414   // X86-64 uses RIP relative addressing based on the jump table label.
2415   if (Subtarget.isPICStyleRIPRel())
2416     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2417 
2418   // Otherwise, the reference is relative to the PIC base.
2419   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2420 }
2421 
2422 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const2423 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2424                                            MVT VT) const {
2425   const TargetRegisterClass *RRC = nullptr;
2426   uint8_t Cost = 1;
2427   switch (VT.SimpleTy) {
2428   default:
2429     return TargetLowering::findRepresentativeClass(TRI, VT);
2430   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2431     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2432     break;
2433   case MVT::x86mmx:
2434     RRC = &X86::VR64RegClass;
2435     break;
2436   case MVT::f32: case MVT::f64:
2437   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2438   case MVT::v4f32: case MVT::v2f64:
2439   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2440   case MVT::v8f32: case MVT::v4f64:
2441   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2442   case MVT::v16f32: case MVT::v8f64:
2443     RRC = &X86::VR128XRegClass;
2444     break;
2445   }
2446   return std::make_pair(RRC, Cost);
2447 }
2448 
getAddressSpace() const2449 unsigned X86TargetLowering::getAddressSpace() const {
2450   if (Subtarget.is64Bit())
2451     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2452   return 256;
2453 }
2454 
hasStackGuardSlotTLS(const Triple & TargetTriple)2455 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2456   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2457          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2458 }
2459 
SegmentOffset(IRBuilder<> & IRB,unsigned Offset,unsigned AddressSpace)2460 static Constant* SegmentOffset(IRBuilder<> &IRB,
2461                                unsigned Offset, unsigned AddressSpace) {
2462   return ConstantExpr::getIntToPtr(
2463       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2464       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2465 }
2466 
getIRStackGuard(IRBuilder<> & IRB) const2467 Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2468   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2469   // tcbhead_t; use it instead of the usual global variable (see
2470   // sysdeps/{i386,x86_64}/nptl/tls.h)
2471   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2472     if (Subtarget.isTargetFuchsia()) {
2473       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2474       return SegmentOffset(IRB, 0x10, getAddressSpace());
2475     } else {
2476       // %fs:0x28, unless we're using a Kernel code model, in which case
2477       // it's %gs:0x28.  gs:0x14 on i386.
2478       unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2479       return SegmentOffset(IRB, Offset, getAddressSpace());
2480     }
2481   }
2482 
2483   return TargetLowering::getIRStackGuard(IRB);
2484 }
2485 
insertSSPDeclarations(Module & M) const2486 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2487   // MSVC CRT provides functionalities for stack protection.
2488   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2489       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2490     // MSVC CRT has a global variable holding security cookie.
2491     M.getOrInsertGlobal("__security_cookie",
2492                         Type::getInt8PtrTy(M.getContext()));
2493 
2494     // MSVC CRT has a function to validate security cookie.
2495     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2496         "__security_check_cookie", Type::getVoidTy(M.getContext()),
2497         Type::getInt8PtrTy(M.getContext()));
2498     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2499       F->setCallingConv(CallingConv::X86_FastCall);
2500       F->addAttribute(1, Attribute::AttrKind::InReg);
2501     }
2502     return;
2503   }
2504   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2505   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2506     return;
2507   TargetLowering::insertSSPDeclarations(M);
2508 }
2509 
getSDagStackGuard(const Module & M) const2510 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2511   // MSVC CRT has a global variable holding security cookie.
2512   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2513       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2514     return M.getGlobalVariable("__security_cookie");
2515   }
2516   return TargetLowering::getSDagStackGuard(M);
2517 }
2518 
getSSPStackGuardCheck(const Module & M) const2519 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2520   // MSVC CRT has a function to validate security cookie.
2521   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2522       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2523     return M.getFunction("__security_check_cookie");
2524   }
2525   return TargetLowering::getSSPStackGuardCheck(M);
2526 }
2527 
getSafeStackPointerLocation(IRBuilder<> & IRB) const2528 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2529   if (Subtarget.getTargetTriple().isOSContiki())
2530     return getDefaultSafeStackPointerLocation(IRB, false);
2531 
2532   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2533   // definition of TLS_SLOT_SAFESTACK in
2534   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2535   if (Subtarget.isTargetAndroid()) {
2536     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2537     // %gs:0x24 on i386
2538     unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2539     return SegmentOffset(IRB, Offset, getAddressSpace());
2540   }
2541 
2542   // Fuchsia is similar.
2543   if (Subtarget.isTargetFuchsia()) {
2544     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2545     return SegmentOffset(IRB, 0x18, getAddressSpace());
2546   }
2547 
2548   return TargetLowering::getSafeStackPointerLocation(IRB);
2549 }
2550 
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS) const2551 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2552                                             unsigned DestAS) const {
2553   assert(SrcAS != DestAS && "Expected different address spaces!");
2554 
2555   const TargetMachine &TM = getTargetMachine();
2556   if (TM.getPointerSize(SrcAS) != TM.getPointerSize(DestAS))
2557     return false;
2558 
2559   return SrcAS < 256 && DestAS < 256;
2560 }
2561 
2562 //===----------------------------------------------------------------------===//
2563 //               Return Value Calling Convention Implementation
2564 //===----------------------------------------------------------------------===//
2565 
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2566 bool X86TargetLowering::CanLowerReturn(
2567     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2568     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2569   SmallVector<CCValAssign, 16> RVLocs;
2570   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2571   return CCInfo.CheckReturn(Outs, RetCC_X86);
2572 }
2573 
getScratchRegisters(CallingConv::ID) const2574 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2575   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2576   return ScratchRegs;
2577 }
2578 
2579 /// Lowers masks values (v*i1) to the local register values
2580 /// \returns DAG node after lowering to register type
lowerMasksToReg(const SDValue & ValArg,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2581 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2582                                const SDLoc &Dl, SelectionDAG &DAG) {
2583   EVT ValVT = ValArg.getValueType();
2584 
2585   if (ValVT == MVT::v1i1)
2586     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2587                        DAG.getIntPtrConstant(0, Dl));
2588 
2589   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2590       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2591     // Two stage lowering might be required
2592     // bitcast:   v8i1 -> i8 / v16i1 -> i16
2593     // anyextend: i8   -> i32 / i16   -> i32
2594     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2595     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2596     if (ValLoc == MVT::i32)
2597       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2598     return ValToCopy;
2599   }
2600 
2601   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2602       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2603     // One stage lowering is required
2604     // bitcast:   v32i1 -> i32 / v64i1 -> i64
2605     return DAG.getBitcast(ValLoc, ValArg);
2606   }
2607 
2608   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2609 }
2610 
2611 /// Breaks v64i1 value into two registers and adds the new node to the DAG
Passv64i1ArgInRegs(const SDLoc & Dl,SelectionDAG & DAG,SDValue & Arg,SmallVectorImpl<std::pair<unsigned,SDValue>> & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,const X86Subtarget & Subtarget)2612 static void Passv64i1ArgInRegs(
2613     const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2614     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, CCValAssign &VA,
2615     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2616   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2617   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2618   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2619   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2620          "The value should reside in two registers");
2621 
2622   // Before splitting the value we cast it to i64
2623   Arg = DAG.getBitcast(MVT::i64, Arg);
2624 
2625   // Splitting the value into two i32 types
2626   SDValue Lo, Hi;
2627   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2628                    DAG.getConstant(0, Dl, MVT::i32));
2629   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2630                    DAG.getConstant(1, Dl, MVT::i32));
2631 
2632   // Attach the two i32 types into corresponding registers
2633   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2634   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2635 }
2636 
2637 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const2638 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2639                                bool isVarArg,
2640                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2641                                const SmallVectorImpl<SDValue> &OutVals,
2642                                const SDLoc &dl, SelectionDAG &DAG) const {
2643   MachineFunction &MF = DAG.getMachineFunction();
2644   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2645 
2646   // In some cases we need to disable registers from the default CSR list.
2647   // For example, when they are used for argument passing.
2648   bool ShouldDisableCalleeSavedRegister =
2649       CallConv == CallingConv::X86_RegCall ||
2650       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2651 
2652   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2653     report_fatal_error("X86 interrupts may not return any value");
2654 
2655   SmallVector<CCValAssign, 16> RVLocs;
2656   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2657   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2658 
2659   SDValue Flag;
2660   SmallVector<SDValue, 6> RetOps;
2661   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2662   // Operand #1 = Bytes To Pop
2663   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2664                    MVT::i32));
2665 
2666   // Copy the result values into the output registers.
2667   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2668        ++I, ++OutsIndex) {
2669     CCValAssign &VA = RVLocs[I];
2670     assert(VA.isRegLoc() && "Can only return in registers!");
2671 
2672     // Add the register to the CalleeSaveDisableRegs list.
2673     if (ShouldDisableCalleeSavedRegister)
2674       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2675 
2676     SDValue ValToCopy = OutVals[OutsIndex];
2677     EVT ValVT = ValToCopy.getValueType();
2678 
2679     // Promote values to the appropriate types.
2680     if (VA.getLocInfo() == CCValAssign::SExt)
2681       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2682     else if (VA.getLocInfo() == CCValAssign::ZExt)
2683       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2684     else if (VA.getLocInfo() == CCValAssign::AExt) {
2685       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2686         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2687       else
2688         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2689     }
2690     else if (VA.getLocInfo() == CCValAssign::BCvt)
2691       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2692 
2693     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2694            "Unexpected FP-extend for return value.");
2695 
2696     // Report an error if we have attempted to return a value via an XMM
2697     // register and SSE was disabled.
2698     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
2699       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2700       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2701     } else if (!Subtarget.hasSSE2() &&
2702                X86::FR64XRegClass.contains(VA.getLocReg()) &&
2703                ValVT == MVT::f64) {
2704       // When returning a double via an XMM register, report an error if SSE2 is
2705       // not enabled.
2706       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2707       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2708     }
2709 
2710     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2711     // the RET instruction and handled by the FP Stackifier.
2712     if (VA.getLocReg() == X86::FP0 ||
2713         VA.getLocReg() == X86::FP1) {
2714       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2715       // change the value to the FP stack register class.
2716       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2717         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2718       RetOps.push_back(ValToCopy);
2719       // Don't emit a copytoreg.
2720       continue;
2721     }
2722 
2723     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2724     // which is returned in RAX / RDX.
2725     if (Subtarget.is64Bit()) {
2726       if (ValVT == MVT::x86mmx) {
2727         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2728           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2729           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2730                                   ValToCopy);
2731           // If we don't have SSE2 available, convert to v4f32 so the generated
2732           // register is legal.
2733           if (!Subtarget.hasSSE2())
2734             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2735         }
2736       }
2737     }
2738 
2739     SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2740 
2741     if (VA.needsCustom()) {
2742       assert(VA.getValVT() == MVT::v64i1 &&
2743              "Currently the only custom case is when we split v64i1 to 2 regs");
2744 
2745       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RegsToPass, VA, RVLocs[++I],
2746                          Subtarget);
2747 
2748       assert(2 == RegsToPass.size() &&
2749              "Expecting two registers after Pass64BitArgInRegs");
2750 
2751       // Add the second register to the CalleeSaveDisableRegs list.
2752       if (ShouldDisableCalleeSavedRegister)
2753         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2754     } else {
2755       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2756     }
2757 
2758     // Add nodes to the DAG and add the values into the RetOps list
2759     for (auto &Reg : RegsToPass) {
2760       Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2761       Flag = Chain.getValue(1);
2762       RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2763     }
2764   }
2765 
2766   // Swift calling convention does not require we copy the sret argument
2767   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2768 
2769   // All x86 ABIs require that for returning structs by value we copy
2770   // the sret argument into %rax/%eax (depending on ABI) for the return.
2771   // We saved the argument into a virtual register in the entry block,
2772   // so now we copy the value out and into %rax/%eax.
2773   //
2774   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2775   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2776   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2777   // either case FuncInfo->setSRetReturnReg() will have been called.
2778   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2779     // When we have both sret and another return value, we should use the
2780     // original Chain stored in RetOps[0], instead of the current Chain updated
2781     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2782 
2783     // For the case of sret and another return value, we have
2784     //   Chain_0 at the function entry
2785     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
2786     // If we use Chain_1 in getCopyFromReg, we will have
2787     //   Val = getCopyFromReg(Chain_1)
2788     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
2789 
2790     // getCopyToReg(Chain_0) will be glued together with
2791     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2792     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2793     //   Data dependency from Unit B to Unit A due to usage of Val in
2794     //     getCopyToReg(Chain_1, Val)
2795     //   Chain dependency from Unit A to Unit B
2796 
2797     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2798     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2799                                      getPointerTy(MF.getDataLayout()));
2800 
2801     unsigned RetValReg
2802         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2803           X86::RAX : X86::EAX;
2804     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2805     Flag = Chain.getValue(1);
2806 
2807     // RAX/EAX now acts like a return value.
2808     RetOps.push_back(
2809         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2810 
2811     // Add the returned register to the CalleeSaveDisableRegs list.
2812     if (ShouldDisableCalleeSavedRegister)
2813       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2814   }
2815 
2816   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2817   const MCPhysReg *I =
2818       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2819   if (I) {
2820     for (; *I; ++I) {
2821       if (X86::GR64RegClass.contains(*I))
2822         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2823       else
2824         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2825     }
2826   }
2827 
2828   RetOps[0] = Chain;  // Update chain.
2829 
2830   // Add the flag if we have it.
2831   if (Flag.getNode())
2832     RetOps.push_back(Flag);
2833 
2834   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2835   if (CallConv == CallingConv::X86_INTR)
2836     opcode = X86ISD::IRET;
2837   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2838 }
2839 
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const2840 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2841   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2842     return false;
2843 
2844   SDValue TCChain = Chain;
2845   SDNode *Copy = *N->use_begin();
2846   if (Copy->getOpcode() == ISD::CopyToReg) {
2847     // If the copy has a glue operand, we conservatively assume it isn't safe to
2848     // perform a tail call.
2849     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2850       return false;
2851     TCChain = Copy->getOperand(0);
2852   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2853     return false;
2854 
2855   bool HasRet = false;
2856   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2857        UI != UE; ++UI) {
2858     if (UI->getOpcode() != X86ISD::RET_FLAG)
2859       return false;
2860     // If we are returning more than one value, we can definitely
2861     // not make a tail call see PR19530
2862     if (UI->getNumOperands() > 4)
2863       return false;
2864     if (UI->getNumOperands() == 4 &&
2865         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2866       return false;
2867     HasRet = true;
2868   }
2869 
2870   if (!HasRet)
2871     return false;
2872 
2873   Chain = TCChain;
2874   return true;
2875 }
2876 
getTypeForExtReturn(LLVMContext & Context,EVT VT,ISD::NodeType ExtendKind) const2877 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2878                                            ISD::NodeType ExtendKind) const {
2879   MVT ReturnMVT = MVT::i32;
2880 
2881   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2882   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2883     // The ABI does not require i1, i8 or i16 to be extended.
2884     //
2885     // On Darwin, there is code in the wild relying on Clang's old behaviour of
2886     // always extending i8/i16 return values, so keep doing that for now.
2887     // (PR26665).
2888     ReturnMVT = MVT::i8;
2889   }
2890 
2891   EVT MinVT = getRegisterType(Context, ReturnMVT);
2892   return VT.bitsLT(MinVT) ? MinVT : VT;
2893 }
2894 
2895 /// Reads two 32 bit registers and creates a 64 bit mask value.
2896 /// \param VA The current 32 bit value that need to be assigned.
2897 /// \param NextVA The next 32 bit value that need to be assigned.
2898 /// \param Root The parent DAG node.
2899 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2900 ///                        glue purposes. In the case the DAG is already using
2901 ///                        physical register instead of virtual, we should glue
2902 ///                        our new SDValue to InFlag SDvalue.
2903 /// \return a new SDvalue of size 64bit.
getv64i1Argument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,const SDLoc & Dl,const X86Subtarget & Subtarget,SDValue * InFlag=nullptr)2904 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2905                                 SDValue &Root, SelectionDAG &DAG,
2906                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
2907                                 SDValue *InFlag = nullptr) {
2908   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2909   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2910   assert(VA.getValVT() == MVT::v64i1 &&
2911          "Expecting first location of 64 bit width type");
2912   assert(NextVA.getValVT() == VA.getValVT() &&
2913          "The locations should have the same type");
2914   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2915          "The values should reside in two registers");
2916 
2917   SDValue Lo, Hi;
2918   SDValue ArgValueLo, ArgValueHi;
2919 
2920   MachineFunction &MF = DAG.getMachineFunction();
2921   const TargetRegisterClass *RC = &X86::GR32RegClass;
2922 
2923   // Read a 32 bit value from the registers.
2924   if (nullptr == InFlag) {
2925     // When no physical register is present,
2926     // create an intermediate virtual register.
2927     unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2928     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2929     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2930     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2931   } else {
2932     // When a physical register is available read the value from it and glue
2933     // the reads together.
2934     ArgValueLo =
2935       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2936     *InFlag = ArgValueLo.getValue(2);
2937     ArgValueHi =
2938       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2939     *InFlag = ArgValueHi.getValue(2);
2940   }
2941 
2942   // Convert the i32 type into v32i1 type.
2943   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2944 
2945   // Convert the i32 type into v32i1 type.
2946   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2947 
2948   // Concatenate the two values together.
2949   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2950 }
2951 
2952 /// The function will lower a register of various sizes (8/16/32/64)
2953 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2954 /// \returns a DAG node contains the operand after lowering to mask type.
lowerRegToMasks(const SDValue & ValArg,const EVT & ValVT,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2955 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2956                                const EVT &ValLoc, const SDLoc &Dl,
2957                                SelectionDAG &DAG) {
2958   SDValue ValReturned = ValArg;
2959 
2960   if (ValVT == MVT::v1i1)
2961     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2962 
2963   if (ValVT == MVT::v64i1) {
2964     // In 32 bit machine, this case is handled by getv64i1Argument
2965     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2966     // In 64 bit machine, There is no need to truncate the value only bitcast
2967   } else {
2968     MVT maskLen;
2969     switch (ValVT.getSimpleVT().SimpleTy) {
2970     case MVT::v8i1:
2971       maskLen = MVT::i8;
2972       break;
2973     case MVT::v16i1:
2974       maskLen = MVT::i16;
2975       break;
2976     case MVT::v32i1:
2977       maskLen = MVT::i32;
2978       break;
2979     default:
2980       llvm_unreachable("Expecting a vector of i1 types");
2981     }
2982 
2983     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2984   }
2985   return DAG.getBitcast(ValVT, ValReturned);
2986 }
2987 
2988 /// Lower the result values of a call into the
2989 /// appropriate copies out of appropriate physical registers.
2990 ///
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,uint32_t * RegMask) const2991 SDValue X86TargetLowering::LowerCallResult(
2992     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2993     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2994     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2995     uint32_t *RegMask) const {
2996 
2997   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2998   // Assign locations to each value returned by this call.
2999   SmallVector<CCValAssign, 16> RVLocs;
3000   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3001                  *DAG.getContext());
3002   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3003 
3004   // Copy all of the result registers out of their specified physreg.
3005   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3006        ++I, ++InsIndex) {
3007     CCValAssign &VA = RVLocs[I];
3008     EVT CopyVT = VA.getLocVT();
3009 
3010     // In some calling conventions we need to remove the used registers
3011     // from the register mask.
3012     if (RegMask) {
3013       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
3014            SubRegs.isValid(); ++SubRegs)
3015         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3016     }
3017 
3018     // Report an error if there was an attempt to return FP values via XMM
3019     // registers.
3020     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3021       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3022       if (VA.getLocReg() == X86::XMM1)
3023         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3024       else
3025         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3026     } else if (!Subtarget.hasSSE2() &&
3027                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3028                CopyVT == MVT::f64) {
3029       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3030       if (VA.getLocReg() == X86::XMM1)
3031         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3032       else
3033         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3034     }
3035 
3036     // If we prefer to use the value in xmm registers, copy it out as f80 and
3037     // use a truncate to move it from fp stack reg to xmm reg.
3038     bool RoundAfterCopy = false;
3039     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3040         isScalarFPTypeInSSEReg(VA.getValVT())) {
3041       if (!Subtarget.hasX87())
3042         report_fatal_error("X87 register return with X87 disabled");
3043       CopyVT = MVT::f80;
3044       RoundAfterCopy = (CopyVT != VA.getLocVT());
3045     }
3046 
3047     SDValue Val;
3048     if (VA.needsCustom()) {
3049       assert(VA.getValVT() == MVT::v64i1 &&
3050              "Currently the only custom case is when we split v64i1 to 2 regs");
3051       Val =
3052           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3053     } else {
3054       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3055                   .getValue(1);
3056       Val = Chain.getValue(0);
3057       InFlag = Chain.getValue(2);
3058     }
3059 
3060     if (RoundAfterCopy)
3061       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3062                         // This truncation won't change the value.
3063                         DAG.getIntPtrConstant(1, dl));
3064 
3065     if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
3066       if (VA.getValVT().isVector() &&
3067           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3068            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3069         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3070         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3071       } else
3072         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3073     }
3074 
3075     if (VA.getLocInfo() == CCValAssign::BCvt)
3076       Val = DAG.getBitcast(VA.getValVT(), Val);
3077 
3078     InVals.push_back(Val);
3079   }
3080 
3081   return Chain;
3082 }
3083 
3084 //===----------------------------------------------------------------------===//
3085 //                C & StdCall & Fast Calling Convention implementation
3086 //===----------------------------------------------------------------------===//
3087 //  StdCall calling convention seems to be standard for many Windows' API
3088 //  routines and around. It differs from C calling convention just a little:
3089 //  callee should clean up the stack, not caller. Symbols should be also
3090 //  decorated in some fancy way :) It doesn't support any vector arguments.
3091 //  For info on fast calling convention see Fast Calling Convention (tail call)
3092 //  implementation LowerX86_32FastCCCallTo.
3093 
3094 /// CallIsStructReturn - Determines whether a call uses struct return
3095 /// semantics.
3096 enum StructReturnType {
3097   NotStructReturn,
3098   RegStructReturn,
3099   StackStructReturn
3100 };
3101 static StructReturnType
callIsStructReturn(ArrayRef<ISD::OutputArg> Outs,bool IsMCU)3102 callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
3103   if (Outs.empty())
3104     return NotStructReturn;
3105 
3106   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
3107   if (!Flags.isSRet())
3108     return NotStructReturn;
3109   if (Flags.isInReg() || IsMCU)
3110     return RegStructReturn;
3111   return StackStructReturn;
3112 }
3113 
3114 /// Determines whether a function uses struct return semantics.
3115 static StructReturnType
argsAreStructReturn(ArrayRef<ISD::InputArg> Ins,bool IsMCU)3116 argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
3117   if (Ins.empty())
3118     return NotStructReturn;
3119 
3120   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
3121   if (!Flags.isSRet())
3122     return NotStructReturn;
3123   if (Flags.isInReg() || IsMCU)
3124     return RegStructReturn;
3125   return StackStructReturn;
3126 }
3127 
3128 /// Make a copy of an aggregate at address specified by "Src" to address
3129 /// "Dst" with size and alignment information specified by the specific
3130 /// parameter attribute. The copy will be passed as a byval function parameter.
CreateCopyOfByValArgument(SDValue Src,SDValue Dst,SDValue Chain,ISD::ArgFlagsTy Flags,SelectionDAG & DAG,const SDLoc & dl)3131 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3132                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3133                                          SelectionDAG &DAG, const SDLoc &dl) {
3134   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3135 
3136   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3137                        /*isVolatile*/false, /*AlwaysInline=*/true,
3138                        /*isTailCall*/false,
3139                        MachinePointerInfo(), MachinePointerInfo());
3140 }
3141 
3142 /// Return true if the calling convention is one that we can guarantee TCO for.
canGuaranteeTCO(CallingConv::ID CC)3143 static bool canGuaranteeTCO(CallingConv::ID CC) {
3144   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3145           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3146           CC == CallingConv::HHVM || CC == CallingConv::Tail);
3147 }
3148 
3149 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)3150 static bool mayTailCallThisCC(CallingConv::ID CC) {
3151   switch (CC) {
3152   // C calling conventions:
3153   case CallingConv::C:
3154   case CallingConv::Win64:
3155   case CallingConv::X86_64_SysV:
3156   // Callee pop conventions:
3157   case CallingConv::X86_ThisCall:
3158   case CallingConv::X86_StdCall:
3159   case CallingConv::X86_VectorCall:
3160   case CallingConv::X86_FastCall:
3161   // Swift:
3162   case CallingConv::Swift:
3163     return true;
3164   default:
3165     return canGuaranteeTCO(CC);
3166   }
3167 }
3168 
3169 /// Return true if the function is being made into a tailcall target by
3170 /// changing its ABI.
shouldGuaranteeTCO(CallingConv::ID CC,bool GuaranteedTailCallOpt)3171 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3172   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) || CC == CallingConv::Tail;
3173 }
3174 
mayBeEmittedAsTailCall(const CallInst * CI) const3175 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3176   if (!CI->isTailCall())
3177     return false;
3178 
3179   ImmutableCallSite CS(CI);
3180   CallingConv::ID CalleeCC = CS.getCallingConv();
3181   if (!mayTailCallThisCC(CalleeCC))
3182     return false;
3183 
3184   return true;
3185 }
3186 
3187 SDValue
LowerMemArgument(SDValue Chain,CallingConv::ID CallConv,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,MachineFrameInfo & MFI,unsigned i) const3188 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3189                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3190                                     const SDLoc &dl, SelectionDAG &DAG,
3191                                     const CCValAssign &VA,
3192                                     MachineFrameInfo &MFI, unsigned i) const {
3193   // Create the nodes corresponding to a load from this parameter slot.
3194   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3195   bool AlwaysUseMutable = shouldGuaranteeTCO(
3196       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3197   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3198   EVT ValVT;
3199   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3200 
3201   // If value is passed by pointer we have address passed instead of the value
3202   // itself. No need to extend if the mask value and location share the same
3203   // absolute size.
3204   bool ExtendedInMem =
3205       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3206       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3207 
3208   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3209     ValVT = VA.getLocVT();
3210   else
3211     ValVT = VA.getValVT();
3212 
3213   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3214   // changed with more analysis.
3215   // In case of tail call optimization mark all arguments mutable. Since they
3216   // could be overwritten by lowering of arguments in case of a tail call.
3217   if (Flags.isByVal()) {
3218     unsigned Bytes = Flags.getByValSize();
3219     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3220 
3221     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3222     // can be improved with deeper analysis.
3223     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3224                                    /*isAliased=*/true);
3225     return DAG.getFrameIndex(FI, PtrVT);
3226   }
3227 
3228   // This is an argument in memory. We might be able to perform copy elision.
3229   // If the argument is passed directly in memory without any extension, then we
3230   // can perform copy elision. Large vector types, for example, may be passed
3231   // indirectly by pointer.
3232   if (Flags.isCopyElisionCandidate() &&
3233       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem) {
3234     EVT ArgVT = Ins[i].ArgVT;
3235     SDValue PartAddr;
3236     if (Ins[i].PartOffset == 0) {
3237       // If this is a one-part value or the first part of a multi-part value,
3238       // create a stack object for the entire argument value type and return a
3239       // load from our portion of it. This assumes that if the first part of an
3240       // argument is in memory, the rest will also be in memory.
3241       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3242                                      /*IsImmutable=*/false);
3243       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3244       return DAG.getLoad(
3245           ValVT, dl, Chain, PartAddr,
3246           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3247     } else {
3248       // This is not the first piece of an argument in memory. See if there is
3249       // already a fixed stack object including this offset. If so, assume it
3250       // was created by the PartOffset == 0 branch above and create a load from
3251       // the appropriate offset into it.
3252       int64_t PartBegin = VA.getLocMemOffset();
3253       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3254       int FI = MFI.getObjectIndexBegin();
3255       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3256         int64_t ObjBegin = MFI.getObjectOffset(FI);
3257         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3258         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3259           break;
3260       }
3261       if (MFI.isFixedObjectIndex(FI)) {
3262         SDValue Addr =
3263             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3264                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3265         return DAG.getLoad(
3266             ValVT, dl, Chain, Addr,
3267             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3268                                               Ins[i].PartOffset));
3269       }
3270     }
3271   }
3272 
3273   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3274                                  VA.getLocMemOffset(), isImmutable);
3275 
3276   // Set SExt or ZExt flag.
3277   if (VA.getLocInfo() == CCValAssign::ZExt) {
3278     MFI.setObjectZExt(FI, true);
3279   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3280     MFI.setObjectSExt(FI, true);
3281   }
3282 
3283   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3284   SDValue Val = DAG.getLoad(
3285       ValVT, dl, Chain, FIN,
3286       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3287   return ExtendedInMem
3288              ? (VA.getValVT().isVector()
3289                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3290                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3291              : Val;
3292 }
3293 
3294 // FIXME: Get this from tablegen.
get64BitArgumentGPRs(CallingConv::ID CallConv,const X86Subtarget & Subtarget)3295 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3296                                                 const X86Subtarget &Subtarget) {
3297   assert(Subtarget.is64Bit());
3298 
3299   if (Subtarget.isCallingConvWin64(CallConv)) {
3300     static const MCPhysReg GPR64ArgRegsWin64[] = {
3301       X86::RCX, X86::RDX, X86::R8,  X86::R9
3302     };
3303     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3304   }
3305 
3306   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3307     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3308   };
3309   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3310 }
3311 
3312 // FIXME: Get this from tablegen.
get64BitArgumentXMMs(MachineFunction & MF,CallingConv::ID CallConv,const X86Subtarget & Subtarget)3313 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3314                                                 CallingConv::ID CallConv,
3315                                                 const X86Subtarget &Subtarget) {
3316   assert(Subtarget.is64Bit());
3317   if (Subtarget.isCallingConvWin64(CallConv)) {
3318     // The XMM registers which might contain var arg parameters are shadowed
3319     // in their paired GPR.  So we only need to save the GPR to their home
3320     // slots.
3321     // TODO: __vectorcall will change this.
3322     return None;
3323   }
3324 
3325   const Function &F = MF.getFunction();
3326   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3327   bool isSoftFloat = Subtarget.useSoftFloat();
3328   assert(!(isSoftFloat && NoImplicitFloatOps) &&
3329          "SSE register cannot be used when SSE is disabled!");
3330   if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3331     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3332     // registers.
3333     return None;
3334 
3335   static const MCPhysReg XMMArgRegs64Bit[] = {
3336     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3337     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3338   };
3339   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3340 }
3341 
3342 #ifndef NDEBUG
isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs)3343 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3344   return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3345                         [](const CCValAssign &A, const CCValAssign &B) -> bool {
3346                           return A.getValNo() < B.getValNo();
3347                         });
3348 }
3349 #endif
3350 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const3351 SDValue X86TargetLowering::LowerFormalArguments(
3352     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3353     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3354     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3355   MachineFunction &MF = DAG.getMachineFunction();
3356   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3357   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3358 
3359   const Function &F = MF.getFunction();
3360   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3361       F.getName() == "main")
3362     FuncInfo->setForceFramePointer(true);
3363 
3364   MachineFrameInfo &MFI = MF.getFrameInfo();
3365   bool Is64Bit = Subtarget.is64Bit();
3366   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3367 
3368   assert(
3369       !(isVarArg && canGuaranteeTCO(CallConv)) &&
3370       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3371 
3372   // Assign locations to all of the incoming arguments.
3373   SmallVector<CCValAssign, 16> ArgLocs;
3374   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3375 
3376   // Allocate shadow area for Win64.
3377   if (IsWin64)
3378     CCInfo.AllocateStack(32, 8);
3379 
3380   CCInfo.AnalyzeArguments(Ins, CC_X86);
3381 
3382   // In vectorcall calling convention a second pass is required for the HVA
3383   // types.
3384   if (CallingConv::X86_VectorCall == CallConv) {
3385     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3386   }
3387 
3388   // The next loop assumes that the locations are in the same order of the
3389   // input arguments.
3390   assert(isSortedByValueNo(ArgLocs) &&
3391          "Argument Location list must be sorted before lowering");
3392 
3393   SDValue ArgValue;
3394   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3395        ++I, ++InsIndex) {
3396     assert(InsIndex < Ins.size() && "Invalid Ins index");
3397     CCValAssign &VA = ArgLocs[I];
3398 
3399     if (VA.isRegLoc()) {
3400       EVT RegVT = VA.getLocVT();
3401       if (VA.needsCustom()) {
3402         assert(
3403             VA.getValVT() == MVT::v64i1 &&
3404             "Currently the only custom case is when we split v64i1 to 2 regs");
3405 
3406         // v64i1 values, in regcall calling convention, that are
3407         // compiled to 32 bit arch, are split up into two registers.
3408         ArgValue =
3409             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3410       } else {
3411         const TargetRegisterClass *RC;
3412         if (RegVT == MVT::i8)
3413           RC = &X86::GR8RegClass;
3414         else if (RegVT == MVT::i16)
3415           RC = &X86::GR16RegClass;
3416         else if (RegVT == MVT::i32)
3417           RC = &X86::GR32RegClass;
3418         else if (Is64Bit && RegVT == MVT::i64)
3419           RC = &X86::GR64RegClass;
3420         else if (RegVT == MVT::f32)
3421           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3422         else if (RegVT == MVT::f64)
3423           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3424         else if (RegVT == MVT::f80)
3425           RC = &X86::RFP80RegClass;
3426         else if (RegVT == MVT::f128)
3427           RC = &X86::VR128RegClass;
3428         else if (RegVT.is512BitVector())
3429           RC = &X86::VR512RegClass;
3430         else if (RegVT.is256BitVector())
3431           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3432         else if (RegVT.is128BitVector())
3433           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3434         else if (RegVT == MVT::x86mmx)
3435           RC = &X86::VR64RegClass;
3436         else if (RegVT == MVT::v1i1)
3437           RC = &X86::VK1RegClass;
3438         else if (RegVT == MVT::v8i1)
3439           RC = &X86::VK8RegClass;
3440         else if (RegVT == MVT::v16i1)
3441           RC = &X86::VK16RegClass;
3442         else if (RegVT == MVT::v32i1)
3443           RC = &X86::VK32RegClass;
3444         else if (RegVT == MVT::v64i1)
3445           RC = &X86::VK64RegClass;
3446         else
3447           llvm_unreachable("Unknown argument type!");
3448 
3449         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3450         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3451       }
3452 
3453       // If this is an 8 or 16-bit value, it is really passed promoted to 32
3454       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
3455       // right size.
3456       if (VA.getLocInfo() == CCValAssign::SExt)
3457         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3458                                DAG.getValueType(VA.getValVT()));
3459       else if (VA.getLocInfo() == CCValAssign::ZExt)
3460         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3461                                DAG.getValueType(VA.getValVT()));
3462       else if (VA.getLocInfo() == CCValAssign::BCvt)
3463         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3464 
3465       if (VA.isExtInLoc()) {
3466         // Handle MMX values passed in XMM regs.
3467         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3468           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3469         else if (VA.getValVT().isVector() &&
3470                  VA.getValVT().getScalarType() == MVT::i1 &&
3471                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3472                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3473           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3474           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3475         } else
3476           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3477       }
3478     } else {
3479       assert(VA.isMemLoc());
3480       ArgValue =
3481           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3482     }
3483 
3484     // If value is passed via pointer - do a load.
3485     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3486       ArgValue =
3487           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3488 
3489     InVals.push_back(ArgValue);
3490   }
3491 
3492   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3493     // Swift calling convention does not require we copy the sret argument
3494     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3495     if (CallConv == CallingConv::Swift)
3496       continue;
3497 
3498     // All x86 ABIs require that for returning structs by value we copy the
3499     // sret argument into %rax/%eax (depending on ABI) for the return. Save
3500     // the argument into a virtual register so that we can access it from the
3501     // return points.
3502     if (Ins[I].Flags.isSRet()) {
3503       unsigned Reg = FuncInfo->getSRetReturnReg();
3504       if (!Reg) {
3505         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3506         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3507         FuncInfo->setSRetReturnReg(Reg);
3508       }
3509       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3510       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3511       break;
3512     }
3513   }
3514 
3515   unsigned StackSize = CCInfo.getNextStackOffset();
3516   // Align stack specially for tail calls.
3517   if (shouldGuaranteeTCO(CallConv,
3518                          MF.getTarget().Options.GuaranteedTailCallOpt))
3519     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3520 
3521   // If the function takes variable number of arguments, make a frame index for
3522   // the start of the first vararg value... for expansion of llvm.va_start. We
3523   // can skip this if there are no va_start calls.
3524   if (MFI.hasVAStart() &&
3525       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3526                    CallConv != CallingConv::X86_ThisCall))) {
3527     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3528   }
3529 
3530   // Figure out if XMM registers are in use.
3531   assert(!(Subtarget.useSoftFloat() &&
3532            F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3533          "SSE register cannot be used when SSE is disabled!");
3534 
3535   // 64-bit calling conventions support varargs and register parameters, so we
3536   // have to do extra work to spill them in the prologue.
3537   if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3538     // Find the first unallocated argument registers.
3539     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3540     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3541     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3542     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3543     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3544            "SSE register cannot be used when SSE is disabled!");
3545 
3546     // Gather all the live in physical registers.
3547     SmallVector<SDValue, 6> LiveGPRs;
3548     SmallVector<SDValue, 8> LiveXMMRegs;
3549     SDValue ALVal;
3550     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3551       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3552       LiveGPRs.push_back(
3553           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3554     }
3555     if (!ArgXMMs.empty()) {
3556       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3557       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3558       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3559         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3560         LiveXMMRegs.push_back(
3561             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3562       }
3563     }
3564 
3565     if (IsWin64) {
3566       // Get to the caller-allocated home save location.  Add 8 to account
3567       // for the return address.
3568       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3569       FuncInfo->setRegSaveFrameIndex(
3570           MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3571       // Fixup to set vararg frame on shadow area (4 x i64).
3572       if (NumIntRegs < 4)
3573         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3574     } else {
3575       // For X86-64, if there are vararg parameters that are passed via
3576       // registers, then we must store them to their spots on the stack so
3577       // they may be loaded by dereferencing the result of va_next.
3578       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3579       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3580       FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3581           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3582     }
3583 
3584     // Store the integer parameter registers.
3585     SmallVector<SDValue, 8> MemOps;
3586     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3587                                       getPointerTy(DAG.getDataLayout()));
3588     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3589     for (SDValue Val : LiveGPRs) {
3590       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3591                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3592       SDValue Store =
3593           DAG.getStore(Val.getValue(1), dl, Val, FIN,
3594                        MachinePointerInfo::getFixedStack(
3595                            DAG.getMachineFunction(),
3596                            FuncInfo->getRegSaveFrameIndex(), Offset));
3597       MemOps.push_back(Store);
3598       Offset += 8;
3599     }
3600 
3601     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3602       // Now store the XMM (fp + vector) parameter registers.
3603       SmallVector<SDValue, 12> SaveXMMOps;
3604       SaveXMMOps.push_back(Chain);
3605       SaveXMMOps.push_back(ALVal);
3606       SaveXMMOps.push_back(DAG.getIntPtrConstant(
3607                              FuncInfo->getRegSaveFrameIndex(), dl));
3608       SaveXMMOps.push_back(DAG.getIntPtrConstant(
3609                              FuncInfo->getVarArgsFPOffset(), dl));
3610       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3611                         LiveXMMRegs.end());
3612       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3613                                    MVT::Other, SaveXMMOps));
3614     }
3615 
3616     if (!MemOps.empty())
3617       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3618   }
3619 
3620   if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3621     // Find the largest legal vector type.
3622     MVT VecVT = MVT::Other;
3623     // FIXME: Only some x86_32 calling conventions support AVX512.
3624     if (Subtarget.useAVX512Regs() &&
3625         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3626                      CallConv == CallingConv::Intel_OCL_BI)))
3627       VecVT = MVT::v16f32;
3628     else if (Subtarget.hasAVX())
3629       VecVT = MVT::v8f32;
3630     else if (Subtarget.hasSSE2())
3631       VecVT = MVT::v4f32;
3632 
3633     // We forward some GPRs and some vector types.
3634     SmallVector<MVT, 2> RegParmTypes;
3635     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3636     RegParmTypes.push_back(IntVT);
3637     if (VecVT != MVT::Other)
3638       RegParmTypes.push_back(VecVT);
3639 
3640     // Compute the set of forwarded registers. The rest are scratch.
3641     SmallVectorImpl<ForwardedRegister> &Forwards =
3642         FuncInfo->getForwardedMustTailRegParms();
3643     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3644 
3645     // Forward AL for SysV x86_64 targets, since it is used for varargs.
3646     if (Is64Bit && !IsWin64 && !CCInfo.isAllocated(X86::AL)) {
3647       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3648       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3649     }
3650 
3651     // Copy all forwards from physical to virtual registers.
3652     for (ForwardedRegister &FR : Forwards) {
3653       // FIXME: Can we use a less constrained schedule?
3654       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, FR.VReg, FR.VT);
3655       FR.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(FR.VT));
3656       Chain = DAG.getCopyToReg(Chain, dl, FR.VReg, RegVal);
3657     }
3658   }
3659 
3660   // Some CCs need callee pop.
3661   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3662                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
3663     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3664   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3665     // X86 interrupts must pop the error code (and the alignment padding) if
3666     // present.
3667     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3668   } else {
3669     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3670     // If this is an sret function, the return should pop the hidden pointer.
3671     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3672         !Subtarget.getTargetTriple().isOSMSVCRT() &&
3673         argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3674       FuncInfo->setBytesToPopOnReturn(4);
3675   }
3676 
3677   if (!Is64Bit) {
3678     // RegSaveFrameIndex is X86-64 only.
3679     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3680     if (CallConv == CallingConv::X86_FastCall ||
3681         CallConv == CallingConv::X86_ThisCall)
3682       // fastcc functions can't have varargs.
3683       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3684   }
3685 
3686   FuncInfo->setArgumentStackSize(StackSize);
3687 
3688   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3689     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3690     if (Personality == EHPersonality::CoreCLR) {
3691       assert(Is64Bit);
3692       // TODO: Add a mechanism to frame lowering that will allow us to indicate
3693       // that we'd prefer this slot be allocated towards the bottom of the frame
3694       // (i.e. near the stack pointer after allocating the frame).  Every
3695       // funclet needs a copy of this slot in its (mostly empty) frame, and the
3696       // offset from the bottom of this and each funclet's frame must be the
3697       // same, so the size of funclets' (mostly empty) frames is dictated by
3698       // how far this slot is from the bottom (since they allocate just enough
3699       // space to accommodate holding this slot at the correct offset).
3700       int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3701       EHInfo->PSPSymFrameIdx = PSPSymFI;
3702     }
3703   }
3704 
3705   if (CallConv == CallingConv::X86_RegCall ||
3706       F.hasFnAttribute("no_caller_saved_registers")) {
3707     MachineRegisterInfo &MRI = MF.getRegInfo();
3708     for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3709       MRI.disableCalleeSavedRegister(Pair.first);
3710   }
3711 
3712   return Chain;
3713 }
3714 
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags) const3715 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3716                                             SDValue Arg, const SDLoc &dl,
3717                                             SelectionDAG &DAG,
3718                                             const CCValAssign &VA,
3719                                             ISD::ArgFlagsTy Flags) const {
3720   unsigned LocMemOffset = VA.getLocMemOffset();
3721   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3722   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3723                        StackPtr, PtrOff);
3724   if (Flags.isByVal())
3725     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3726 
3727   return DAG.getStore(
3728       Chain, dl, Arg, PtrOff,
3729       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3730 }
3731 
3732 /// Emit a load of return address if tail call
3733 /// optimization is performed and it is required.
EmitTailCallLoadRetAddr(SelectionDAG & DAG,SDValue & OutRetAddr,SDValue Chain,bool IsTailCall,bool Is64Bit,int FPDiff,const SDLoc & dl) const3734 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3735     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3736     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3737   // Adjust the Return address stack slot.
3738   EVT VT = getPointerTy(DAG.getDataLayout());
3739   OutRetAddr = getReturnAddressFrameIndex(DAG);
3740 
3741   // Load the "old" Return address.
3742   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3743   return SDValue(OutRetAddr.getNode(), 1);
3744 }
3745 
3746 /// Emit a store of the return address if tail call
3747 /// optimization is performed and it is required (FPDiff!=0).
EmitTailCallStoreRetAddr(SelectionDAG & DAG,MachineFunction & MF,SDValue Chain,SDValue RetAddrFrIdx,EVT PtrVT,unsigned SlotSize,int FPDiff,const SDLoc & dl)3748 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3749                                         SDValue Chain, SDValue RetAddrFrIdx,
3750                                         EVT PtrVT, unsigned SlotSize,
3751                                         int FPDiff, const SDLoc &dl) {
3752   // Store the return address to the appropriate stack slot.
3753   if (!FPDiff) return Chain;
3754   // Calculate the new stack slot for the return address.
3755   int NewReturnAddrFI =
3756     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3757                                          false);
3758   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3759   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3760                        MachinePointerInfo::getFixedStack(
3761                            DAG.getMachineFunction(), NewReturnAddrFI));
3762   return Chain;
3763 }
3764 
3765 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3766 /// operation of specified width.
getMOVL(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)3767 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3768                        SDValue V2) {
3769   unsigned NumElems = VT.getVectorNumElements();
3770   SmallVector<int, 8> Mask;
3771   Mask.push_back(NumElems);
3772   for (unsigned i = 1; i != NumElems; ++i)
3773     Mask.push_back(i);
3774   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3775 }
3776 
3777 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const3778 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3779                              SmallVectorImpl<SDValue> &InVals) const {
3780   SelectionDAG &DAG                     = CLI.DAG;
3781   SDLoc &dl                             = CLI.DL;
3782   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3783   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3784   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3785   SDValue Chain                         = CLI.Chain;
3786   SDValue Callee                        = CLI.Callee;
3787   CallingConv::ID CallConv              = CLI.CallConv;
3788   bool &isTailCall                      = CLI.IsTailCall;
3789   bool isVarArg                         = CLI.IsVarArg;
3790 
3791   MachineFunction &MF = DAG.getMachineFunction();
3792   bool Is64Bit        = Subtarget.is64Bit();
3793   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
3794   StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3795   bool IsSibcall      = false;
3796   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
3797       CallConv == CallingConv::Tail;
3798   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3799   const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3800   const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3801   bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3802                  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3803   const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3804   bool HasNoCfCheck =
3805       (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3806   const Module *M = MF.getMMI().getModule();
3807   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3808 
3809   MachineFunction::CallSiteInfo CSInfo;
3810 
3811   if (CallConv == CallingConv::X86_INTR)
3812     report_fatal_error("X86 interrupts may not be called directly");
3813 
3814   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO) {
3815     // If we are using a GOT, disable tail calls to external symbols with
3816     // default visibility. Tail calling such a symbol requires using a GOT
3817     // relocation, which forces early binding of the symbol. This breaks code
3818     // that require lazy function symbol resolution. Using musttail or
3819     // GuaranteedTailCallOpt will override this.
3820     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3821     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3822                G->getGlobal()->hasDefaultVisibility()))
3823       isTailCall = false;
3824   }
3825 
3826   bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3827   if (IsMustTail) {
3828     // Force this to be a tail call.  The verifier rules are enough to ensure
3829     // that we can lower this successfully without moving the return address
3830     // around.
3831     isTailCall = true;
3832   } else if (isTailCall) {
3833     // Check if it's really possible to do a tail call.
3834     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3835                     isVarArg, SR != NotStructReturn,
3836                     MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3837                     Outs, OutVals, Ins, DAG);
3838 
3839     // Sibcalls are automatically detected tailcalls which do not require
3840     // ABI changes.
3841     if (!IsGuaranteeTCO && isTailCall)
3842       IsSibcall = true;
3843 
3844     if (isTailCall)
3845       ++NumTailCalls;
3846   }
3847 
3848   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3849          "Var args not supported with calling convention fastcc, ghc or hipe");
3850 
3851   // Analyze operands of the call, assigning locations to each operand.
3852   SmallVector<CCValAssign, 16> ArgLocs;
3853   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3854 
3855   // Allocate shadow area for Win64.
3856   if (IsWin64)
3857     CCInfo.AllocateStack(32, 8);
3858 
3859   CCInfo.AnalyzeArguments(Outs, CC_X86);
3860 
3861   // In vectorcall calling convention a second pass is required for the HVA
3862   // types.
3863   if (CallingConv::X86_VectorCall == CallConv) {
3864     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3865   }
3866 
3867   // Get a count of how many bytes are to be pushed on the stack.
3868   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3869   if (IsSibcall)
3870     // This is a sibcall. The memory operands are available in caller's
3871     // own caller's stack.
3872     NumBytes = 0;
3873   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
3874     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3875 
3876   int FPDiff = 0;
3877   if (isTailCall && !IsSibcall && !IsMustTail) {
3878     // Lower arguments at fp - stackoffset + fpdiff.
3879     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3880 
3881     FPDiff = NumBytesCallerPushed - NumBytes;
3882 
3883     // Set the delta of movement of the returnaddr stackslot.
3884     // But only set if delta is greater than previous delta.
3885     if (FPDiff < X86Info->getTCReturnAddrDelta())
3886       X86Info->setTCReturnAddrDelta(FPDiff);
3887   }
3888 
3889   unsigned NumBytesToPush = NumBytes;
3890   unsigned NumBytesToPop = NumBytes;
3891 
3892   // If we have an inalloca argument, all stack space has already been allocated
3893   // for us and be right at the top of the stack.  We don't support multiple
3894   // arguments passed in memory when using inalloca.
3895   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3896     NumBytesToPush = 0;
3897     if (!ArgLocs.back().isMemLoc())
3898       report_fatal_error("cannot use inalloca attribute on a register "
3899                          "parameter");
3900     if (ArgLocs.back().getLocMemOffset() != 0)
3901       report_fatal_error("any parameter with the inalloca attribute must be "
3902                          "the only memory argument");
3903   }
3904 
3905   if (!IsSibcall && !IsMustTail)
3906     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3907                                  NumBytes - NumBytesToPush, dl);
3908 
3909   SDValue RetAddrFrIdx;
3910   // Load return address for tail calls.
3911   if (isTailCall && FPDiff)
3912     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3913                                     Is64Bit, FPDiff, dl);
3914 
3915   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3916   SmallVector<SDValue, 8> MemOpChains;
3917   SDValue StackPtr;
3918 
3919   // The next loop assumes that the locations are in the same order of the
3920   // input arguments.
3921   assert(isSortedByValueNo(ArgLocs) &&
3922          "Argument Location list must be sorted before lowering");
3923 
3924   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3925   // of tail call optimization arguments are handle later.
3926   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3927   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3928        ++I, ++OutIndex) {
3929     assert(OutIndex < Outs.size() && "Invalid Out index");
3930     // Skip inalloca arguments, they have already been written.
3931     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3932     if (Flags.isInAlloca())
3933       continue;
3934 
3935     CCValAssign &VA = ArgLocs[I];
3936     EVT RegVT = VA.getLocVT();
3937     SDValue Arg = OutVals[OutIndex];
3938     bool isByVal = Flags.isByVal();
3939 
3940     // Promote the value if needed.
3941     switch (VA.getLocInfo()) {
3942     default: llvm_unreachable("Unknown loc info!");
3943     case CCValAssign::Full: break;
3944     case CCValAssign::SExt:
3945       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3946       break;
3947     case CCValAssign::ZExt:
3948       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3949       break;
3950     case CCValAssign::AExt:
3951       if (Arg.getValueType().isVector() &&
3952           Arg.getValueType().getVectorElementType() == MVT::i1)
3953         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3954       else if (RegVT.is128BitVector()) {
3955         // Special case: passing MMX values in XMM registers.
3956         Arg = DAG.getBitcast(MVT::i64, Arg);
3957         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3958         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3959       } else
3960         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3961       break;
3962     case CCValAssign::BCvt:
3963       Arg = DAG.getBitcast(RegVT, Arg);
3964       break;
3965     case CCValAssign::Indirect: {
3966       if (isByVal) {
3967         // Memcpy the argument to a temporary stack slot to prevent
3968         // the caller from seeing any modifications the callee may make
3969         // as guaranteed by the `byval` attribute.
3970         int FrameIdx = MF.getFrameInfo().CreateStackObject(
3971             Flags.getByValSize(), std::max(16, (int)Flags.getByValAlign()),
3972             false);
3973         SDValue StackSlot =
3974             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
3975         Chain =
3976             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
3977         // From now on treat this as a regular pointer
3978         Arg = StackSlot;
3979         isByVal = false;
3980       } else {
3981         // Store the argument.
3982         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3983         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3984         Chain = DAG.getStore(
3985             Chain, dl, Arg, SpillSlot,
3986             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3987         Arg = SpillSlot;
3988       }
3989       break;
3990     }
3991     }
3992 
3993     if (VA.needsCustom()) {
3994       assert(VA.getValVT() == MVT::v64i1 &&
3995              "Currently the only custom case is when we split v64i1 to 2 regs");
3996       // Split v64i1 value into two registers
3997       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
3998     } else if (VA.isRegLoc()) {
3999       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4000       const TargetOptions &Options = DAG.getTarget().Options;
4001       if (Options.EnableDebugEntryValues)
4002         CSInfo.emplace_back(VA.getLocReg(), I);
4003       if (isVarArg && IsWin64) {
4004         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4005         // shadow reg if callee is a varargs function.
4006         unsigned ShadowReg = 0;
4007         switch (VA.getLocReg()) {
4008         case X86::XMM0: ShadowReg = X86::RCX; break;
4009         case X86::XMM1: ShadowReg = X86::RDX; break;
4010         case X86::XMM2: ShadowReg = X86::R8; break;
4011         case X86::XMM3: ShadowReg = X86::R9; break;
4012         }
4013         if (ShadowReg)
4014           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4015       }
4016     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4017       assert(VA.isMemLoc());
4018       if (!StackPtr.getNode())
4019         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4020                                       getPointerTy(DAG.getDataLayout()));
4021       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4022                                              dl, DAG, VA, Flags));
4023     }
4024   }
4025 
4026   if (!MemOpChains.empty())
4027     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4028 
4029   if (Subtarget.isPICStyleGOT()) {
4030     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4031     // GOT pointer.
4032     if (!isTailCall) {
4033       RegsToPass.push_back(std::make_pair(
4034           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4035                                           getPointerTy(DAG.getDataLayout()))));
4036     } else {
4037       // If we are tail calling and generating PIC/GOT style code load the
4038       // address of the callee into ECX. The value in ecx is used as target of
4039       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4040       // for tail calls on PIC/GOT architectures. Normally we would just put the
4041       // address of GOT into ebx and then call target@PLT. But for tail calls
4042       // ebx would be restored (since ebx is callee saved) before jumping to the
4043       // target@PLT.
4044 
4045       // Note: The actual moving to ECX is done further down.
4046       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4047       if (G && !G->getGlobal()->hasLocalLinkage() &&
4048           G->getGlobal()->hasDefaultVisibility())
4049         Callee = LowerGlobalAddress(Callee, DAG);
4050       else if (isa<ExternalSymbolSDNode>(Callee))
4051         Callee = LowerExternalSymbol(Callee, DAG);
4052     }
4053   }
4054 
4055   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
4056     // From AMD64 ABI document:
4057     // For calls that may call functions that use varargs or stdargs
4058     // (prototype-less calls or calls to functions containing ellipsis (...) in
4059     // the declaration) %al is used as hidden argument to specify the number
4060     // of SSE registers used. The contents of %al do not need to match exactly
4061     // the number of registers, but must be an ubound on the number of SSE
4062     // registers used and is in the range 0 - 8 inclusive.
4063 
4064     // Count the number of XMM registers allocated.
4065     static const MCPhysReg XMMArgRegs[] = {
4066       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4067       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4068     };
4069     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4070     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4071            && "SSE registers cannot be used when SSE is disabled");
4072 
4073     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
4074                                         DAG.getConstant(NumXMMRegs, dl,
4075                                                         MVT::i8)));
4076   }
4077 
4078   if (isVarArg && IsMustTail) {
4079     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4080     for (const auto &F : Forwards) {
4081       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4082       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
4083     }
4084   }
4085 
4086   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4087   // don't need this because the eligibility check rejects calls that require
4088   // shuffling arguments passed in memory.
4089   if (!IsSibcall && isTailCall) {
4090     // Force all the incoming stack arguments to be loaded from the stack
4091     // before any new outgoing arguments are stored to the stack, because the
4092     // outgoing stack slots may alias the incoming argument stack slots, and
4093     // the alias isn't otherwise explicit. This is slightly more conservative
4094     // than necessary, because it means that each store effectively depends
4095     // on every argument instead of just those arguments it would clobber.
4096     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4097 
4098     SmallVector<SDValue, 8> MemOpChains2;
4099     SDValue FIN;
4100     int FI = 0;
4101     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4102          ++I, ++OutsIndex) {
4103       CCValAssign &VA = ArgLocs[I];
4104 
4105       if (VA.isRegLoc()) {
4106         if (VA.needsCustom()) {
4107           assert((CallConv == CallingConv::X86_RegCall) &&
4108                  "Expecting custom case only in regcall calling convention");
4109           // This means that we are in special case where one argument was
4110           // passed through two register locations - Skip the next location
4111           ++I;
4112         }
4113 
4114         continue;
4115       }
4116 
4117       assert(VA.isMemLoc());
4118       SDValue Arg = OutVals[OutsIndex];
4119       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4120       // Skip inalloca arguments.  They don't require any work.
4121       if (Flags.isInAlloca())
4122         continue;
4123       // Create frame index.
4124       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4125       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4126       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4127       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4128 
4129       if (Flags.isByVal()) {
4130         // Copy relative to framepointer.
4131         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4132         if (!StackPtr.getNode())
4133           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4134                                         getPointerTy(DAG.getDataLayout()));
4135         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4136                              StackPtr, Source);
4137 
4138         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4139                                                          ArgChain,
4140                                                          Flags, DAG, dl));
4141       } else {
4142         // Store relative to framepointer.
4143         MemOpChains2.push_back(DAG.getStore(
4144             ArgChain, dl, Arg, FIN,
4145             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4146       }
4147     }
4148 
4149     if (!MemOpChains2.empty())
4150       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4151 
4152     // Store the return address to the appropriate stack slot.
4153     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4154                                      getPointerTy(DAG.getDataLayout()),
4155                                      RegInfo->getSlotSize(), FPDiff, dl);
4156   }
4157 
4158   // Build a sequence of copy-to-reg nodes chained together with token chain
4159   // and flag operands which copy the outgoing args into registers.
4160   SDValue InFlag;
4161   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4162     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4163                              RegsToPass[i].second, InFlag);
4164     InFlag = Chain.getValue(1);
4165   }
4166 
4167   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4168     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4169     // In the 64-bit large code model, we have to make all calls
4170     // through a register, since the call instruction's 32-bit
4171     // pc-relative offset may not be large enough to hold the whole
4172     // address.
4173   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4174              Callee->getOpcode() == ISD::ExternalSymbol) {
4175     // Lower direct calls to global addresses and external symbols. Setting
4176     // ForCall to true here has the effect of removing WrapperRIP when possible
4177     // to allow direct calls to be selected without first materializing the
4178     // address into a register.
4179     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4180   } else if (Subtarget.isTarget64BitILP32() &&
4181              Callee->getValueType(0) == MVT::i32) {
4182     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4183     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4184   }
4185 
4186   // Returns a chain & a flag for retval copy to use.
4187   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4188   SmallVector<SDValue, 8> Ops;
4189 
4190   if (!IsSibcall && isTailCall && !IsMustTail) {
4191     Chain = DAG.getCALLSEQ_END(Chain,
4192                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4193                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4194     InFlag = Chain.getValue(1);
4195   }
4196 
4197   Ops.push_back(Chain);
4198   Ops.push_back(Callee);
4199 
4200   if (isTailCall)
4201     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
4202 
4203   // Add argument registers to the end of the list so that they are known live
4204   // into the call.
4205   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4206     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4207                                   RegsToPass[i].second.getValueType()));
4208 
4209   // Add a register mask operand representing the call-preserved registers.
4210   // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
4211   // set X86_INTR calling convention because it has the same CSR mask
4212   // (same preserved registers).
4213   const uint32_t *Mask = RegInfo->getCallPreservedMask(
4214       MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
4215   assert(Mask && "Missing call preserved mask for calling convention");
4216 
4217   // If this is an invoke in a 32-bit function using a funclet-based
4218   // personality, assume the function clobbers all registers. If an exception
4219   // is thrown, the runtime will not restore CSRs.
4220   // FIXME: Model this more precisely so that we can register allocate across
4221   // the normal edge and spill and fill across the exceptional edge.
4222   if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
4223     const Function &CallerFn = MF.getFunction();
4224     EHPersonality Pers =
4225         CallerFn.hasPersonalityFn()
4226             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4227             : EHPersonality::Unknown;
4228     if (isFuncletEHPersonality(Pers))
4229       Mask = RegInfo->getNoPreservedMask();
4230   }
4231 
4232   // Define a new register mask from the existing mask.
4233   uint32_t *RegMask = nullptr;
4234 
4235   // In some calling conventions we need to remove the used physical registers
4236   // from the reg mask.
4237   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4238     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4239 
4240     // Allocate a new Reg Mask and copy Mask.
4241     RegMask = MF.allocateRegMask();
4242     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4243     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4244 
4245     // Make sure all sub registers of the argument registers are reset
4246     // in the RegMask.
4247     for (auto const &RegPair : RegsToPass)
4248       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4249            SubRegs.isValid(); ++SubRegs)
4250         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4251 
4252     // Create the RegMask Operand according to our updated mask.
4253     Ops.push_back(DAG.getRegisterMask(RegMask));
4254   } else {
4255     // Create the RegMask Operand according to the static mask.
4256     Ops.push_back(DAG.getRegisterMask(Mask));
4257   }
4258 
4259   if (InFlag.getNode())
4260     Ops.push_back(InFlag);
4261 
4262   if (isTailCall) {
4263     // We used to do:
4264     //// If this is the first return lowered for this function, add the regs
4265     //// to the liveout set for the function.
4266     // This isn't right, although it's probably harmless on x86; liveouts
4267     // should be computed from returns not tail calls.  Consider a void
4268     // function making a tail call to a function returning int.
4269     MF.getFrameInfo().setHasTailCall();
4270     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4271     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4272     return Ret;
4273   }
4274 
4275   if (HasNoCfCheck && IsCFProtectionSupported) {
4276     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4277   } else {
4278     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4279   }
4280   InFlag = Chain.getValue(1);
4281   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4282 
4283   // Save heapallocsite metadata.
4284   if (CLI.CS)
4285     if (MDNode *HeapAlloc = CLI.CS->getMetadata("heapallocsite"))
4286       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4287 
4288   // Create the CALLSEQ_END node.
4289   unsigned NumBytesForCalleeToPop;
4290   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4291                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4292     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4293   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4294            !Subtarget.getTargetTriple().isOSMSVCRT() &&
4295            SR == StackStructReturn)
4296     // If this is a call to a struct-return function, the callee
4297     // pops the hidden struct pointer, so we have to push it back.
4298     // This is common for Darwin/X86, Linux & Mingw32 targets.
4299     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4300     NumBytesForCalleeToPop = 4;
4301   else
4302     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
4303 
4304   if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
4305     // No need to reset the stack after the call if the call doesn't return. To
4306     // make the MI verify, we'll pretend the callee does it for us.
4307     NumBytesForCalleeToPop = NumBytes;
4308   }
4309 
4310   // Returns a flag for retval copy to use.
4311   if (!IsSibcall) {
4312     Chain = DAG.getCALLSEQ_END(Chain,
4313                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4314                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4315                                                      true),
4316                                InFlag, dl);
4317     InFlag = Chain.getValue(1);
4318   }
4319 
4320   // Handle result values, copying them out of physregs into vregs that we
4321   // return.
4322   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4323                          InVals, RegMask);
4324 }
4325 
4326 //===----------------------------------------------------------------------===//
4327 //                Fast Calling Convention (tail call) implementation
4328 //===----------------------------------------------------------------------===//
4329 
4330 //  Like std call, callee cleans arguments, convention except that ECX is
4331 //  reserved for storing the tail called function address. Only 2 registers are
4332 //  free for argument passing (inreg). Tail call optimization is performed
4333 //  provided:
4334 //                * tailcallopt is enabled
4335 //                * caller/callee are fastcc
4336 //  On X86_64 architecture with GOT-style position independent code only local
4337 //  (within module) calls are supported at the moment.
4338 //  To keep the stack aligned according to platform abi the function
4339 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4340 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
4341 //  If a tail called function callee has more arguments than the caller the
4342 //  caller needs to make sure that there is room to move the RETADDR to. This is
4343 //  achieved by reserving an area the size of the argument delta right after the
4344 //  original RETADDR, but before the saved framepointer or the spilled registers
4345 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4346 //  stack layout:
4347 //    arg1
4348 //    arg2
4349 //    RETADDR
4350 //    [ new RETADDR
4351 //      move area ]
4352 //    (possible EBP)
4353 //    ESI
4354 //    EDI
4355 //    local1 ..
4356 
4357 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4358 /// requirement.
4359 unsigned
GetAlignedArgumentStackSize(const unsigned StackSize,SelectionDAG & DAG) const4360 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4361                                                SelectionDAG &DAG) const {
4362   const Align StackAlignment(Subtarget.getFrameLowering()->getStackAlignment());
4363   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4364   assert(StackSize % SlotSize == 0 &&
4365          "StackSize must be a multiple of SlotSize");
4366   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4367 }
4368 
4369 /// Return true if the given stack call argument is already available in the
4370 /// same position (relatively) of the caller's incoming argument stack.
4371 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo & MFI,const MachineRegisterInfo * MRI,const X86InstrInfo * TII,const CCValAssign & VA)4372 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4373                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4374                          const X86InstrInfo *TII, const CCValAssign &VA) {
4375   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4376 
4377   for (;;) {
4378     // Look through nodes that don't alter the bits of the incoming value.
4379     unsigned Op = Arg.getOpcode();
4380     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4381       Arg = Arg.getOperand(0);
4382       continue;
4383     }
4384     if (Op == ISD::TRUNCATE) {
4385       const SDValue &TruncInput = Arg.getOperand(0);
4386       if (TruncInput.getOpcode() == ISD::AssertZext &&
4387           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4388               Arg.getValueType()) {
4389         Arg = TruncInput.getOperand(0);
4390         continue;
4391       }
4392     }
4393     break;
4394   }
4395 
4396   int FI = INT_MAX;
4397   if (Arg.getOpcode() == ISD::CopyFromReg) {
4398     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4399     if (!Register::isVirtualRegister(VR))
4400       return false;
4401     MachineInstr *Def = MRI->getVRegDef(VR);
4402     if (!Def)
4403       return false;
4404     if (!Flags.isByVal()) {
4405       if (!TII->isLoadFromStackSlot(*Def, FI))
4406         return false;
4407     } else {
4408       unsigned Opcode = Def->getOpcode();
4409       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4410            Opcode == X86::LEA64_32r) &&
4411           Def->getOperand(1).isFI()) {
4412         FI = Def->getOperand(1).getIndex();
4413         Bytes = Flags.getByValSize();
4414       } else
4415         return false;
4416     }
4417   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4418     if (Flags.isByVal())
4419       // ByVal argument is passed in as a pointer but it's now being
4420       // dereferenced. e.g.
4421       // define @foo(%struct.X* %A) {
4422       //   tail call @bar(%struct.X* byval %A)
4423       // }
4424       return false;
4425     SDValue Ptr = Ld->getBasePtr();
4426     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4427     if (!FINode)
4428       return false;
4429     FI = FINode->getIndex();
4430   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4431     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4432     FI = FINode->getIndex();
4433     Bytes = Flags.getByValSize();
4434   } else
4435     return false;
4436 
4437   assert(FI != INT_MAX);
4438   if (!MFI.isFixedObjectIndex(FI))
4439     return false;
4440 
4441   if (Offset != MFI.getObjectOffset(FI))
4442     return false;
4443 
4444   // If this is not byval, check that the argument stack object is immutable.
4445   // inalloca and argument copy elision can create mutable argument stack
4446   // objects. Byval objects can be mutated, but a byval call intends to pass the
4447   // mutated memory.
4448   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4449     return false;
4450 
4451   if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4452     // If the argument location is wider than the argument type, check that any
4453     // extension flags match.
4454     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4455         Flags.isSExt() != MFI.isObjectSExt(FI)) {
4456       return false;
4457     }
4458   }
4459 
4460   return Bytes == MFI.getObjectSize(FI);
4461 }
4462 
4463 /// Check whether the call is eligible for tail call optimization. Targets
4464 /// that want to do tail call optimization should implement this function.
IsEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,bool isCalleeStructRet,bool isCallerStructRet,Type * RetTy,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const4465 bool X86TargetLowering::IsEligibleForTailCallOptimization(
4466     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4467     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4468     const SmallVectorImpl<ISD::OutputArg> &Outs,
4469     const SmallVectorImpl<SDValue> &OutVals,
4470     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4471   if (!mayTailCallThisCC(CalleeCC))
4472     return false;
4473 
4474   // If -tailcallopt is specified, make fastcc functions tail-callable.
4475   MachineFunction &MF = DAG.getMachineFunction();
4476   const Function &CallerF = MF.getFunction();
4477 
4478   // If the function return type is x86_fp80 and the callee return type is not,
4479   // then the FP_EXTEND of the call result is not a nop. It's not safe to
4480   // perform a tailcall optimization here.
4481   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4482     return false;
4483 
4484   CallingConv::ID CallerCC = CallerF.getCallingConv();
4485   bool CCMatch = CallerCC == CalleeCC;
4486   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4487   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4488   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4489       CalleeCC == CallingConv::Tail;
4490 
4491   // Win64 functions have extra shadow space for argument homing. Don't do the
4492   // sibcall if the caller and callee have mismatched expectations for this
4493   // space.
4494   if (IsCalleeWin64 != IsCallerWin64)
4495     return false;
4496 
4497   if (IsGuaranteeTCO) {
4498     if (canGuaranteeTCO(CalleeCC) && CCMatch)
4499       return true;
4500     return false;
4501   }
4502 
4503   // Look for obvious safe cases to perform tail call optimization that do not
4504   // require ABI changes. This is what gcc calls sibcall.
4505 
4506   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4507   // emit a special epilogue.
4508   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4509   if (RegInfo->needsStackRealignment(MF))
4510     return false;
4511 
4512   // Also avoid sibcall optimization if either caller or callee uses struct
4513   // return semantics.
4514   if (isCalleeStructRet || isCallerStructRet)
4515     return false;
4516 
4517   // Do not sibcall optimize vararg calls unless all arguments are passed via
4518   // registers.
4519   LLVMContext &C = *DAG.getContext();
4520   if (isVarArg && !Outs.empty()) {
4521     // Optimizing for varargs on Win64 is unlikely to be safe without
4522     // additional testing.
4523     if (IsCalleeWin64 || IsCallerWin64)
4524       return false;
4525 
4526     SmallVector<CCValAssign, 16> ArgLocs;
4527     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4528 
4529     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4530     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4531       if (!ArgLocs[i].isRegLoc())
4532         return false;
4533   }
4534 
4535   // If the call result is in ST0 / ST1, it needs to be popped off the x87
4536   // stack.  Therefore, if it's not used by the call it is not safe to optimize
4537   // this into a sibcall.
4538   bool Unused = false;
4539   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4540     if (!Ins[i].Used) {
4541       Unused = true;
4542       break;
4543     }
4544   }
4545   if (Unused) {
4546     SmallVector<CCValAssign, 16> RVLocs;
4547     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4548     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4549     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4550       CCValAssign &VA = RVLocs[i];
4551       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4552         return false;
4553     }
4554   }
4555 
4556   // Check that the call results are passed in the same way.
4557   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4558                                   RetCC_X86, RetCC_X86))
4559     return false;
4560   // The callee has to preserve all registers the caller needs to preserve.
4561   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4562   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4563   if (!CCMatch) {
4564     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4565     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4566       return false;
4567   }
4568 
4569   unsigned StackArgsSize = 0;
4570 
4571   // If the callee takes no arguments then go on to check the results of the
4572   // call.
4573   if (!Outs.empty()) {
4574     // Check if stack adjustment is needed. For now, do not do this if any
4575     // argument is passed on the stack.
4576     SmallVector<CCValAssign, 16> ArgLocs;
4577     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4578 
4579     // Allocate shadow area for Win64
4580     if (IsCalleeWin64)
4581       CCInfo.AllocateStack(32, 8);
4582 
4583     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4584     StackArgsSize = CCInfo.getNextStackOffset();
4585 
4586     if (CCInfo.getNextStackOffset()) {
4587       // Check if the arguments are already laid out in the right way as
4588       // the caller's fixed stack objects.
4589       MachineFrameInfo &MFI = MF.getFrameInfo();
4590       const MachineRegisterInfo *MRI = &MF.getRegInfo();
4591       const X86InstrInfo *TII = Subtarget.getInstrInfo();
4592       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4593         CCValAssign &VA = ArgLocs[i];
4594         SDValue Arg = OutVals[i];
4595         ISD::ArgFlagsTy Flags = Outs[i].Flags;
4596         if (VA.getLocInfo() == CCValAssign::Indirect)
4597           return false;
4598         if (!VA.isRegLoc()) {
4599           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4600                                    MFI, MRI, TII, VA))
4601             return false;
4602         }
4603       }
4604     }
4605 
4606     bool PositionIndependent = isPositionIndependent();
4607     // If the tailcall address may be in a register, then make sure it's
4608     // possible to register allocate for it. In 32-bit, the call address can
4609     // only target EAX, EDX, or ECX since the tail call must be scheduled after
4610     // callee-saved registers are restored. These happen to be the same
4611     // registers used to pass 'inreg' arguments so watch out for those.
4612     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4613                                   !isa<ExternalSymbolSDNode>(Callee)) ||
4614                                  PositionIndependent)) {
4615       unsigned NumInRegs = 0;
4616       // In PIC we need an extra register to formulate the address computation
4617       // for the callee.
4618       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4619 
4620       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4621         CCValAssign &VA = ArgLocs[i];
4622         if (!VA.isRegLoc())
4623           continue;
4624         Register Reg = VA.getLocReg();
4625         switch (Reg) {
4626         default: break;
4627         case X86::EAX: case X86::EDX: case X86::ECX:
4628           if (++NumInRegs == MaxInRegs)
4629             return false;
4630           break;
4631         }
4632       }
4633     }
4634 
4635     const MachineRegisterInfo &MRI = MF.getRegInfo();
4636     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4637       return false;
4638   }
4639 
4640   bool CalleeWillPop =
4641       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4642                        MF.getTarget().Options.GuaranteedTailCallOpt);
4643 
4644   if (unsigned BytesToPop =
4645           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4646     // If we have bytes to pop, the callee must pop them.
4647     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4648     if (!CalleePopMatches)
4649       return false;
4650   } else if (CalleeWillPop && StackArgsSize > 0) {
4651     // If we don't have bytes to pop, make sure the callee doesn't pop any.
4652     return false;
4653   }
4654 
4655   return true;
4656 }
4657 
4658 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const4659 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4660                                   const TargetLibraryInfo *libInfo) const {
4661   return X86::createFastISel(funcInfo, libInfo);
4662 }
4663 
4664 //===----------------------------------------------------------------------===//
4665 //                           Other Lowering Hooks
4666 //===----------------------------------------------------------------------===//
4667 
MayFoldLoad(SDValue Op)4668 static bool MayFoldLoad(SDValue Op) {
4669   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4670 }
4671 
MayFoldIntoStore(SDValue Op)4672 static bool MayFoldIntoStore(SDValue Op) {
4673   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4674 }
4675 
MayFoldIntoZeroExtend(SDValue Op)4676 static bool MayFoldIntoZeroExtend(SDValue Op) {
4677   if (Op.hasOneUse()) {
4678     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4679     return (ISD::ZERO_EXTEND == Opcode);
4680   }
4681   return false;
4682 }
4683 
isTargetShuffle(unsigned Opcode)4684 static bool isTargetShuffle(unsigned Opcode) {
4685   switch(Opcode) {
4686   default: return false;
4687   case X86ISD::BLENDI:
4688   case X86ISD::PSHUFB:
4689   case X86ISD::PSHUFD:
4690   case X86ISD::PSHUFHW:
4691   case X86ISD::PSHUFLW:
4692   case X86ISD::SHUFP:
4693   case X86ISD::INSERTPS:
4694   case X86ISD::EXTRQI:
4695   case X86ISD::INSERTQI:
4696   case X86ISD::PALIGNR:
4697   case X86ISD::VSHLDQ:
4698   case X86ISD::VSRLDQ:
4699   case X86ISD::MOVLHPS:
4700   case X86ISD::MOVHLPS:
4701   case X86ISD::MOVSHDUP:
4702   case X86ISD::MOVSLDUP:
4703   case X86ISD::MOVDDUP:
4704   case X86ISD::MOVSS:
4705   case X86ISD::MOVSD:
4706   case X86ISD::UNPCKL:
4707   case X86ISD::UNPCKH:
4708   case X86ISD::VBROADCAST:
4709   case X86ISD::VPERMILPI:
4710   case X86ISD::VPERMILPV:
4711   case X86ISD::VPERM2X128:
4712   case X86ISD::SHUF128:
4713   case X86ISD::VPERMIL2:
4714   case X86ISD::VPERMI:
4715   case X86ISD::VPPERM:
4716   case X86ISD::VPERMV:
4717   case X86ISD::VPERMV3:
4718   case X86ISD::VZEXT_MOVL:
4719     return true;
4720   }
4721 }
4722 
isTargetShuffleVariableMask(unsigned Opcode)4723 static bool isTargetShuffleVariableMask(unsigned Opcode) {
4724   switch (Opcode) {
4725   default: return false;
4726   // Target Shuffles.
4727   case X86ISD::PSHUFB:
4728   case X86ISD::VPERMILPV:
4729   case X86ISD::VPERMIL2:
4730   case X86ISD::VPPERM:
4731   case X86ISD::VPERMV:
4732   case X86ISD::VPERMV3:
4733     return true;
4734   // 'Faux' Target Shuffles.
4735   case ISD::OR:
4736   case ISD::AND:
4737   case X86ISD::ANDNP:
4738     return true;
4739   }
4740 }
4741 
getReturnAddressFrameIndex(SelectionDAG & DAG) const4742 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4743   MachineFunction &MF = DAG.getMachineFunction();
4744   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4745   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4746   int ReturnAddrIndex = FuncInfo->getRAIndex();
4747 
4748   if (ReturnAddrIndex == 0) {
4749     // Set up a frame object for the return address.
4750     unsigned SlotSize = RegInfo->getSlotSize();
4751     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4752                                                           -(int64_t)SlotSize,
4753                                                           false);
4754     FuncInfo->setRAIndex(ReturnAddrIndex);
4755   }
4756 
4757   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4758 }
4759 
isOffsetSuitableForCodeModel(int64_t Offset,CodeModel::Model M,bool hasSymbolicDisplacement)4760 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4761                                        bool hasSymbolicDisplacement) {
4762   // Offset should fit into 32 bit immediate field.
4763   if (!isInt<32>(Offset))
4764     return false;
4765 
4766   // If we don't have a symbolic displacement - we don't have any extra
4767   // restrictions.
4768   if (!hasSymbolicDisplacement)
4769     return true;
4770 
4771   // FIXME: Some tweaks might be needed for medium code model.
4772   if (M != CodeModel::Small && M != CodeModel::Kernel)
4773     return false;
4774 
4775   // For small code model we assume that latest object is 16MB before end of 31
4776   // bits boundary. We may also accept pretty large negative constants knowing
4777   // that all objects are in the positive half of address space.
4778   if (M == CodeModel::Small && Offset < 16*1024*1024)
4779     return true;
4780 
4781   // For kernel code model we know that all object resist in the negative half
4782   // of 32bits address space. We may not accept negative offsets, since they may
4783   // be just off and we may accept pretty large positive ones.
4784   if (M == CodeModel::Kernel && Offset >= 0)
4785     return true;
4786 
4787   return false;
4788 }
4789 
4790 /// Determines whether the callee is required to pop its own arguments.
4791 /// Callee pop is necessary to support tail calls.
isCalleePop(CallingConv::ID CallingConv,bool is64Bit,bool IsVarArg,bool GuaranteeTCO)4792 bool X86::isCalleePop(CallingConv::ID CallingConv,
4793                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4794   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4795   // can guarantee TCO.
4796   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4797     return true;
4798 
4799   switch (CallingConv) {
4800   default:
4801     return false;
4802   case CallingConv::X86_StdCall:
4803   case CallingConv::X86_FastCall:
4804   case CallingConv::X86_ThisCall:
4805   case CallingConv::X86_VectorCall:
4806     return !is64Bit;
4807   }
4808 }
4809 
4810 /// Return true if the condition is an signed comparison operation.
isX86CCSigned(unsigned X86CC)4811 static bool isX86CCSigned(unsigned X86CC) {
4812   switch (X86CC) {
4813   default:
4814     llvm_unreachable("Invalid integer condition!");
4815   case X86::COND_E:
4816   case X86::COND_NE:
4817   case X86::COND_B:
4818   case X86::COND_A:
4819   case X86::COND_BE:
4820   case X86::COND_AE:
4821     return false;
4822   case X86::COND_G:
4823   case X86::COND_GE:
4824   case X86::COND_L:
4825   case X86::COND_LE:
4826     return true;
4827   }
4828 }
4829 
TranslateIntegerX86CC(ISD::CondCode SetCCOpcode)4830 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4831   switch (SetCCOpcode) {
4832   default: llvm_unreachable("Invalid integer condition!");
4833   case ISD::SETEQ:  return X86::COND_E;
4834   case ISD::SETGT:  return X86::COND_G;
4835   case ISD::SETGE:  return X86::COND_GE;
4836   case ISD::SETLT:  return X86::COND_L;
4837   case ISD::SETLE:  return X86::COND_LE;
4838   case ISD::SETNE:  return X86::COND_NE;
4839   case ISD::SETULT: return X86::COND_B;
4840   case ISD::SETUGT: return X86::COND_A;
4841   case ISD::SETULE: return X86::COND_BE;
4842   case ISD::SETUGE: return X86::COND_AE;
4843   }
4844 }
4845 
4846 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4847 /// condition code, returning the condition code and the LHS/RHS of the
4848 /// comparison to make.
TranslateX86CC(ISD::CondCode SetCCOpcode,const SDLoc & DL,bool isFP,SDValue & LHS,SDValue & RHS,SelectionDAG & DAG)4849 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4850                                bool isFP, SDValue &LHS, SDValue &RHS,
4851                                SelectionDAG &DAG) {
4852   if (!isFP) {
4853     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4854       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4855         // X > -1   -> X == 0, jump !sign.
4856         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4857         return X86::COND_NS;
4858       }
4859       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4860         // X < 0   -> X == 0, jump on sign.
4861         return X86::COND_S;
4862       }
4863       if (SetCCOpcode == ISD::SETGE && RHSC->isNullValue()) {
4864         // X >= 0   -> X == 0, jump on !sign.
4865         return X86::COND_NS;
4866       }
4867       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
4868         // X < 1   -> X <= 0
4869         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4870         return X86::COND_LE;
4871       }
4872     }
4873 
4874     return TranslateIntegerX86CC(SetCCOpcode);
4875   }
4876 
4877   // First determine if it is required or is profitable to flip the operands.
4878 
4879   // If LHS is a foldable load, but RHS is not, flip the condition.
4880   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4881       !ISD::isNON_EXTLoad(RHS.getNode())) {
4882     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4883     std::swap(LHS, RHS);
4884   }
4885 
4886   switch (SetCCOpcode) {
4887   default: break;
4888   case ISD::SETOLT:
4889   case ISD::SETOLE:
4890   case ISD::SETUGT:
4891   case ISD::SETUGE:
4892     std::swap(LHS, RHS);
4893     break;
4894   }
4895 
4896   // On a floating point condition, the flags are set as follows:
4897   // ZF  PF  CF   op
4898   //  0 | 0 | 0 | X > Y
4899   //  0 | 0 | 1 | X < Y
4900   //  1 | 0 | 0 | X == Y
4901   //  1 | 1 | 1 | unordered
4902   switch (SetCCOpcode) {
4903   default: llvm_unreachable("Condcode should be pre-legalized away");
4904   case ISD::SETUEQ:
4905   case ISD::SETEQ:   return X86::COND_E;
4906   case ISD::SETOLT:              // flipped
4907   case ISD::SETOGT:
4908   case ISD::SETGT:   return X86::COND_A;
4909   case ISD::SETOLE:              // flipped
4910   case ISD::SETOGE:
4911   case ISD::SETGE:   return X86::COND_AE;
4912   case ISD::SETUGT:              // flipped
4913   case ISD::SETULT:
4914   case ISD::SETLT:   return X86::COND_B;
4915   case ISD::SETUGE:              // flipped
4916   case ISD::SETULE:
4917   case ISD::SETLE:   return X86::COND_BE;
4918   case ISD::SETONE:
4919   case ISD::SETNE:   return X86::COND_NE;
4920   case ISD::SETUO:   return X86::COND_P;
4921   case ISD::SETO:    return X86::COND_NP;
4922   case ISD::SETOEQ:
4923   case ISD::SETUNE:  return X86::COND_INVALID;
4924   }
4925 }
4926 
4927 /// Is there a floating point cmov for the specific X86 condition code?
4928 /// Current x86 isa includes the following FP cmov instructions:
4929 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
hasFPCMov(unsigned X86CC)4930 static bool hasFPCMov(unsigned X86CC) {
4931   switch (X86CC) {
4932   default:
4933     return false;
4934   case X86::COND_B:
4935   case X86::COND_BE:
4936   case X86::COND_E:
4937   case X86::COND_P:
4938   case X86::COND_A:
4939   case X86::COND_AE:
4940   case X86::COND_NE:
4941   case X86::COND_NP:
4942     return true;
4943   }
4944 }
4945 
4946 
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const4947 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4948                                            const CallInst &I,
4949                                            MachineFunction &MF,
4950                                            unsigned Intrinsic) const {
4951 
4952   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4953   if (!IntrData)
4954     return false;
4955 
4956   Info.flags = MachineMemOperand::MONone;
4957   Info.offset = 0;
4958 
4959   switch (IntrData->Type) {
4960   case TRUNCATE_TO_MEM_VI8:
4961   case TRUNCATE_TO_MEM_VI16:
4962   case TRUNCATE_TO_MEM_VI32: {
4963     Info.opc = ISD::INTRINSIC_VOID;
4964     Info.ptrVal = I.getArgOperand(0);
4965     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
4966     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4967     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4968       ScalarVT = MVT::i8;
4969     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4970       ScalarVT = MVT::i16;
4971     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4972       ScalarVT = MVT::i32;
4973 
4974     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4975     Info.align = Align::None();
4976     Info.flags |= MachineMemOperand::MOStore;
4977     break;
4978   }
4979   case GATHER:
4980   case GATHER_AVX2: {
4981     Info.opc = ISD::INTRINSIC_W_CHAIN;
4982     Info.ptrVal = nullptr;
4983     MVT DataVT = MVT::getVT(I.getType());
4984     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4985     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4986                                 IndexVT.getVectorNumElements());
4987     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
4988     Info.align = Align::None();
4989     Info.flags |= MachineMemOperand::MOLoad;
4990     break;
4991   }
4992   case SCATTER: {
4993     Info.opc = ISD::INTRINSIC_VOID;
4994     Info.ptrVal = nullptr;
4995     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
4996     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4997     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4998                                 IndexVT.getVectorNumElements());
4999     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5000     Info.align = Align::None();
5001     Info.flags |= MachineMemOperand::MOStore;
5002     break;
5003   }
5004   default:
5005     return false;
5006   }
5007 
5008   return true;
5009 }
5010 
5011 /// Returns true if the target can instruction select the
5012 /// specified FP immediate natively. If false, the legalizer will
5013 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT,bool ForCodeSize) const5014 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5015                                      bool ForCodeSize) const {
5016   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
5017     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
5018       return true;
5019   }
5020   return false;
5021 }
5022 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const5023 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5024                                               ISD::LoadExtType ExtTy,
5025                                               EVT NewVT) const {
5026   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5027 
5028   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5029   // relocation target a movq or addq instruction: don't let the load shrink.
5030   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5031   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5032     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5033       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5034 
5035   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5036   // those uses are extracted directly into a store, then the extract + store
5037   // can be store-folded. Therefore, it's probably not worth splitting the load.
5038   EVT VT = Load->getValueType(0);
5039   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5040     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5041       // Skip uses of the chain value. Result 0 of the node is the load value.
5042       if (UI.getUse().getResNo() != 0)
5043         continue;
5044 
5045       // If this use is not an extract + store, it's probably worth splitting.
5046       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5047           UI->use_begin()->getOpcode() != ISD::STORE)
5048         return true;
5049     }
5050     // All non-chain uses are extract + store.
5051     return false;
5052   }
5053 
5054   return true;
5055 }
5056 
5057 /// Returns true if it is beneficial to convert a load of a constant
5058 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const5059 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5060                                                           Type *Ty) const {
5061   assert(Ty->isIntegerTy());
5062 
5063   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5064   if (BitSize == 0 || BitSize > 64)
5065     return false;
5066   return true;
5067 }
5068 
reduceSelectOfFPConstantLoads(EVT CmpOpVT) const5069 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5070   // If we are using XMM registers in the ABI and the condition of the select is
5071   // a floating-point compare and we have blendv or conditional move, then it is
5072   // cheaper to select instead of doing a cross-register move and creating a
5073   // load that depends on the compare result.
5074   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5075   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5076 }
5077 
convertSelectOfConstantsToMath(EVT VT) const5078 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5079   // TODO: It might be a win to ease or lift this restriction, but the generic
5080   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5081   if (VT.isVector() && Subtarget.hasAVX512())
5082     return false;
5083 
5084   return true;
5085 }
5086 
decomposeMulByConstant(LLVMContext & Context,EVT VT,SDValue C) const5087 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5088                                                SDValue C) const {
5089   // TODO: We handle scalars using custom code, but generic combining could make
5090   // that unnecessary.
5091   APInt MulC;
5092   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5093     return false;
5094 
5095   // Find the type this will be legalized too. Otherwise we might prematurely
5096   // convert this to shl+add/sub and then still have to type legalize those ops.
5097   // Another choice would be to defer the decision for illegal types until
5098   // after type legalization. But constant splat vectors of i64 can't make it
5099   // through type legalization on 32-bit targets so we would need to special
5100   // case vXi64.
5101   while (getTypeAction(Context, VT) != TypeLegal)
5102     VT = getTypeToTransformTo(Context, VT);
5103 
5104   // If vector multiply is legal, assume that's faster than shl + add/sub.
5105   // TODO: Multiply is a complex op with higher latency and lower throughput in
5106   //       most implementations, so this check could be loosened based on type
5107   //       and/or a CPU attribute.
5108   if (isOperationLegal(ISD::MUL, VT))
5109     return false;
5110 
5111   // shl+add, shl+sub, shl+add+neg
5112   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5113          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5114 }
5115 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const5116 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5117                                                 unsigned Index) const {
5118   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5119     return false;
5120 
5121   // Mask vectors support all subregister combinations and operations that
5122   // extract half of vector.
5123   if (ResVT.getVectorElementType() == MVT::i1)
5124     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5125                           (Index == ResVT.getVectorNumElements()));
5126 
5127   return (Index % ResVT.getVectorNumElements()) == 0;
5128 }
5129 
shouldScalarizeBinop(SDValue VecOp) const5130 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5131   unsigned Opc = VecOp.getOpcode();
5132 
5133   // Assume target opcodes can't be scalarized.
5134   // TODO - do we have any exceptions?
5135   if (Opc >= ISD::BUILTIN_OP_END)
5136     return false;
5137 
5138   // If the vector op is not supported, try to convert to scalar.
5139   EVT VecVT = VecOp.getValueType();
5140   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5141     return true;
5142 
5143   // If the vector op is supported, but the scalar op is not, the transform may
5144   // not be worthwhile.
5145   EVT ScalarVT = VecVT.getScalarType();
5146   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5147 }
5148 
shouldFormOverflowOp(unsigned Opcode,EVT VT) const5149 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
5150   // TODO: Allow vectors?
5151   if (VT.isVector())
5152     return false;
5153   return VT.isSimple() || !isOperationExpand(Opcode, VT);
5154 }
5155 
isCheapToSpeculateCttz() const5156 bool X86TargetLowering::isCheapToSpeculateCttz() const {
5157   // Speculate cttz only if we can directly use TZCNT.
5158   return Subtarget.hasBMI();
5159 }
5160 
isCheapToSpeculateCtlz() const5161 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5162   // Speculate ctlz only if we can directly use LZCNT.
5163   return Subtarget.hasLZCNT();
5164 }
5165 
isLoadBitCastBeneficial(EVT LoadVT,EVT BitcastVT,const SelectionDAG & DAG,const MachineMemOperand & MMO) const5166 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5167                                                 const SelectionDAG &DAG,
5168                                                 const MachineMemOperand &MMO) const {
5169   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5170       BitcastVT.getVectorElementType() == MVT::i1)
5171     return false;
5172 
5173   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5174     return false;
5175 
5176   // If both types are legal vectors, it's always ok to convert them.
5177   if (LoadVT.isVector() && BitcastVT.isVector() &&
5178       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5179     return true;
5180 
5181   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5182 }
5183 
canMergeStoresTo(unsigned AddressSpace,EVT MemVT,const SelectionDAG & DAG) const5184 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5185                                          const SelectionDAG &DAG) const {
5186   // Do not merge to float value size (128 bytes) if no implicit
5187   // float attribute is set.
5188   bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
5189       Attribute::NoImplicitFloat);
5190 
5191   if (NoFloat) {
5192     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5193     return (MemVT.getSizeInBits() <= MaxIntSize);
5194   }
5195   // Make sure we don't merge greater than our preferred vector
5196   // width.
5197   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5198     return false;
5199   return true;
5200 }
5201 
isCtlzFast() const5202 bool X86TargetLowering::isCtlzFast() const {
5203   return Subtarget.hasFastLZCNT();
5204 }
5205 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const5206 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5207     const Instruction &AndI) const {
5208   return true;
5209 }
5210 
hasAndNotCompare(SDValue Y) const5211 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5212   EVT VT = Y.getValueType();
5213 
5214   if (VT.isVector())
5215     return false;
5216 
5217   if (!Subtarget.hasBMI())
5218     return false;
5219 
5220   // There are only 32-bit and 64-bit forms for 'andn'.
5221   if (VT != MVT::i32 && VT != MVT::i64)
5222     return false;
5223 
5224   return !isa<ConstantSDNode>(Y);
5225 }
5226 
hasAndNot(SDValue Y) const5227 bool X86TargetLowering::hasAndNot(SDValue Y) const {
5228   EVT VT = Y.getValueType();
5229 
5230   if (!VT.isVector())
5231     return hasAndNotCompare(Y);
5232 
5233   // Vector.
5234 
5235   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5236     return false;
5237 
5238   if (VT == MVT::v4i32)
5239     return true;
5240 
5241   return Subtarget.hasSSE2();
5242 }
5243 
hasBitTest(SDValue X,SDValue Y) const5244 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5245   return X.getValueType().isScalarInteger(); // 'bt'
5246 }
5247 
5248 bool X86TargetLowering::
shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X,ConstantSDNode * XC,ConstantSDNode * CC,SDValue Y,unsigned OldShiftOpcode,unsigned NewShiftOpcode,SelectionDAG & DAG) const5249     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5250         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5251         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5252         SelectionDAG &DAG) const {
5253   // Does baseline recommend not to perform the fold by default?
5254   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5255           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5256     return false;
5257   // For scalars this transform is always beneficial.
5258   if (X.getValueType().isScalarInteger())
5259     return true;
5260   // If all the shift amounts are identical, then transform is beneficial even
5261   // with rudimentary SSE2 shifts.
5262   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5263     return true;
5264   // If we have AVX2 with it's powerful shift operations, then it's also good.
5265   if (Subtarget.hasAVX2())
5266     return true;
5267   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5268   return NewShiftOpcode == ISD::SHL;
5269 }
5270 
shouldFoldConstantShiftPairToMask(const SDNode * N,CombineLevel Level) const5271 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5272     const SDNode *N, CombineLevel Level) const {
5273   assert(((N->getOpcode() == ISD::SHL &&
5274            N->getOperand(0).getOpcode() == ISD::SRL) ||
5275           (N->getOpcode() == ISD::SRL &&
5276            N->getOperand(0).getOpcode() == ISD::SHL)) &&
5277          "Expected shift-shift mask");
5278   EVT VT = N->getValueType(0);
5279   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5280       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5281     // Only fold if the shift values are equal - so it folds to AND.
5282     // TODO - we should fold if either is a non-uniform vector but we don't do
5283     // the fold for non-splats yet.
5284     return N->getOperand(1) == N->getOperand(0).getOperand(1);
5285   }
5286   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5287 }
5288 
shouldFoldMaskToVariableShiftPair(SDValue Y) const5289 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5290   EVT VT = Y.getValueType();
5291 
5292   // For vectors, we don't have a preference, but we probably want a mask.
5293   if (VT.isVector())
5294     return false;
5295 
5296   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5297   if (VT == MVT::i64 && !Subtarget.is64Bit())
5298     return false;
5299 
5300   return true;
5301 }
5302 
shouldExpandShift(SelectionDAG & DAG,SDNode * N) const5303 bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5304                                           SDNode *N) const {
5305   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5306       !Subtarget.isOSWindows())
5307     return false;
5308   return true;
5309 }
5310 
shouldSplatInsEltVarIndex(EVT VT) const5311 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5312   // Any legal vector type can be splatted more efficiently than
5313   // loading/spilling from memory.
5314   return isTypeLegal(VT);
5315 }
5316 
hasFastEqualityCompare(unsigned NumBits) const5317 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5318   MVT VT = MVT::getIntegerVT(NumBits);
5319   if (isTypeLegal(VT))
5320     return VT;
5321 
5322   // PMOVMSKB can handle this.
5323   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5324     return MVT::v16i8;
5325 
5326   // VPMOVMSKB can handle this.
5327   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5328     return MVT::v32i8;
5329 
5330   // TODO: Allow 64-bit type for 32-bit target.
5331   // TODO: 512-bit types should be allowed, but make sure that those
5332   // cases are handled in combineVectorSizedSetCCEquality().
5333 
5334   return MVT::INVALID_SIMPLE_VALUE_TYPE;
5335 }
5336 
5337 /// Val is the undef sentinel value or equal to the specified value.
isUndefOrEqual(int Val,int CmpVal)5338 static bool isUndefOrEqual(int Val, int CmpVal) {
5339   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5340 }
5341 
5342 /// Val is either the undef or zero sentinel value.
isUndefOrZero(int Val)5343 static bool isUndefOrZero(int Val) {
5344   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5345 }
5346 
5347 /// Return true if every element in Mask, beginning from position Pos and ending
5348 /// in Pos+Size is the undef sentinel value.
isUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5349 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5350   return llvm::all_of(Mask.slice(Pos, Size),
5351                       [](int M) { return M == SM_SentinelUndef; });
5352 }
5353 
5354 /// Return true if the mask creates a vector whose lower half is undefined.
isUndefLowerHalf(ArrayRef<int> Mask)5355 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5356   unsigned NumElts = Mask.size();
5357   return isUndefInRange(Mask, 0, NumElts / 2);
5358 }
5359 
5360 /// Return true if the mask creates a vector whose upper half is undefined.
isUndefUpperHalf(ArrayRef<int> Mask)5361 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5362   unsigned NumElts = Mask.size();
5363   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5364 }
5365 
5366 /// Return true if Val falls within the specified range (L, H].
isInRange(int Val,int Low,int Hi)5367 static bool isInRange(int Val, int Low, int Hi) {
5368   return (Val >= Low && Val < Hi);
5369 }
5370 
5371 /// Return true if the value of any element in Mask falls within the specified
5372 /// range (L, H].
isAnyInRange(ArrayRef<int> Mask,int Low,int Hi)5373 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5374   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5375 }
5376 
5377 /// Return true if Val is undef or if its value falls within the
5378 /// specified range (L, H].
isUndefOrInRange(int Val,int Low,int Hi)5379 static bool isUndefOrInRange(int Val, int Low, int Hi) {
5380   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5381 }
5382 
5383 /// Return true if every element in Mask is undef or if its value
5384 /// falls within the specified range (L, H].
isUndefOrInRange(ArrayRef<int> Mask,int Low,int Hi)5385 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5386   return llvm::all_of(
5387       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5388 }
5389 
5390 /// Return true if Val is undef, zero or if its value falls within the
5391 /// specified range (L, H].
isUndefOrZeroOrInRange(int Val,int Low,int Hi)5392 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5393   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5394 }
5395 
5396 /// Return true if every element in Mask is undef, zero or if its value
5397 /// falls within the specified range (L, H].
isUndefOrZeroOrInRange(ArrayRef<int> Mask,int Low,int Hi)5398 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5399   return llvm::all_of(
5400       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5401 }
5402 
5403 /// Return true if every element in Mask, beginning
5404 /// from position Pos and ending in Pos + Size, falls within the specified
5405 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
isSequentialOrUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)5406 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5407                                        unsigned Size, int Low, int Step = 1) {
5408   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5409     if (!isUndefOrEqual(Mask[i], Low))
5410       return false;
5411   return true;
5412 }
5413 
5414 /// Return true if every element in Mask, beginning
5415 /// from position Pos and ending in Pos+Size, falls within the specified
5416 /// sequential range (Low, Low+Size], or is undef or is zero.
isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)5417 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5418                                              unsigned Size, int Low,
5419                                              int Step = 1) {
5420   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5421     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5422       return false;
5423   return true;
5424 }
5425 
5426 /// Return true if every element in Mask, beginning
5427 /// from position Pos and ending in Pos+Size is undef or is zero.
isUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5428 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5429                                  unsigned Size) {
5430   return llvm::all_of(Mask.slice(Pos, Size),
5431                       [](int M) { return isUndefOrZero(M); });
5432 }
5433 
5434 /// Helper function to test whether a shuffle mask could be
5435 /// simplified by widening the elements being shuffled.
5436 ///
5437 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5438 /// leaves it in an unspecified state.
5439 ///
5440 /// NOTE: This must handle normal vector shuffle masks and *target* vector
5441 /// shuffle masks. The latter have the special property of a '-2' representing
5442 /// a zero-ed lane of a vector.
canWidenShuffleElements(ArrayRef<int> Mask,SmallVectorImpl<int> & WidenedMask)5443 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5444                                     SmallVectorImpl<int> &WidenedMask) {
5445   WidenedMask.assign(Mask.size() / 2, 0);
5446   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5447     int M0 = Mask[i];
5448     int M1 = Mask[i + 1];
5449 
5450     // If both elements are undef, its trivial.
5451     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5452       WidenedMask[i / 2] = SM_SentinelUndef;
5453       continue;
5454     }
5455 
5456     // Check for an undef mask and a mask value properly aligned to fit with
5457     // a pair of values. If we find such a case, use the non-undef mask's value.
5458     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5459       WidenedMask[i / 2] = M1 / 2;
5460       continue;
5461     }
5462     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5463       WidenedMask[i / 2] = M0 / 2;
5464       continue;
5465     }
5466 
5467     // When zeroing, we need to spread the zeroing across both lanes to widen.
5468     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5469       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5470           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5471         WidenedMask[i / 2] = SM_SentinelZero;
5472         continue;
5473       }
5474       return false;
5475     }
5476 
5477     // Finally check if the two mask values are adjacent and aligned with
5478     // a pair.
5479     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5480       WidenedMask[i / 2] = M0 / 2;
5481       continue;
5482     }
5483 
5484     // Otherwise we can't safely widen the elements used in this shuffle.
5485     return false;
5486   }
5487   assert(WidenedMask.size() == Mask.size() / 2 &&
5488          "Incorrect size of mask after widening the elements!");
5489 
5490   return true;
5491 }
5492 
canWidenShuffleElements(ArrayRef<int> Mask,const APInt & Zeroable,bool V2IsZero,SmallVectorImpl<int> & WidenedMask)5493 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5494                                     const APInt &Zeroable,
5495                                     bool V2IsZero,
5496                                     SmallVectorImpl<int> &WidenedMask) {
5497   // Create an alternative mask with info about zeroable elements.
5498   // Here we do not set undef elements as zeroable.
5499   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
5500   if (V2IsZero) {
5501     assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!");
5502     for (int i = 0, Size = Mask.size(); i != Size; ++i)
5503       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
5504         ZeroableMask[i] = SM_SentinelZero;
5505   }
5506   return canWidenShuffleElements(ZeroableMask, WidenedMask);
5507 }
5508 
canWidenShuffleElements(ArrayRef<int> Mask)5509 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5510   SmallVector<int, 32> WidenedMask;
5511   return canWidenShuffleElements(Mask, WidenedMask);
5512 }
5513 
5514 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
isZeroNode(SDValue Elt)5515 bool X86::isZeroNode(SDValue Elt) {
5516   return isNullConstant(Elt) || isNullFPConstant(Elt);
5517 }
5518 
5519 // Build a vector of constants.
5520 // Use an UNDEF node if MaskElt == -1.
5521 // Split 64-bit constants in the 32-bit mode.
getConstVector(ArrayRef<int> Values,MVT VT,SelectionDAG & DAG,const SDLoc & dl,bool IsMask=false)5522 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5523                               const SDLoc &dl, bool IsMask = false) {
5524 
5525   SmallVector<SDValue, 32>  Ops;
5526   bool Split = false;
5527 
5528   MVT ConstVecVT = VT;
5529   unsigned NumElts = VT.getVectorNumElements();
5530   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5531   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5532     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5533     Split = true;
5534   }
5535 
5536   MVT EltVT = ConstVecVT.getVectorElementType();
5537   for (unsigned i = 0; i < NumElts; ++i) {
5538     bool IsUndef = Values[i] < 0 && IsMask;
5539     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5540       DAG.getConstant(Values[i], dl, EltVT);
5541     Ops.push_back(OpNode);
5542     if (Split)
5543       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5544                     DAG.getConstant(0, dl, EltVT));
5545   }
5546   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5547   if (Split)
5548     ConstsNode = DAG.getBitcast(VT, ConstsNode);
5549   return ConstsNode;
5550 }
5551 
getConstVector(ArrayRef<APInt> Bits,APInt & Undefs,MVT VT,SelectionDAG & DAG,const SDLoc & dl)5552 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5553                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5554   assert(Bits.size() == Undefs.getBitWidth() &&
5555          "Unequal constant and undef arrays");
5556   SmallVector<SDValue, 32> Ops;
5557   bool Split = false;
5558 
5559   MVT ConstVecVT = VT;
5560   unsigned NumElts = VT.getVectorNumElements();
5561   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5562   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5563     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5564     Split = true;
5565   }
5566 
5567   MVT EltVT = ConstVecVT.getVectorElementType();
5568   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5569     if (Undefs[i]) {
5570       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5571       continue;
5572     }
5573     const APInt &V = Bits[i];
5574     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
5575     if (Split) {
5576       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5577       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5578     } else if (EltVT == MVT::f32) {
5579       APFloat FV(APFloat::IEEEsingle(), V);
5580       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5581     } else if (EltVT == MVT::f64) {
5582       APFloat FV(APFloat::IEEEdouble(), V);
5583       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5584     } else {
5585       Ops.push_back(DAG.getConstant(V, dl, EltVT));
5586     }
5587   }
5588 
5589   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5590   return DAG.getBitcast(VT, ConstsNode);
5591 }
5592 
5593 /// Returns a vector of specified type with all zero elements.
getZeroVector(MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5594 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5595                              SelectionDAG &DAG, const SDLoc &dl) {
5596   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
5597           VT.getVectorElementType() == MVT::i1) &&
5598          "Unexpected vector type");
5599 
5600   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5601   // type. This ensures they get CSE'd. But if the integer type is not
5602   // available, use a floating-point +0.0 instead.
5603   SDValue Vec;
5604   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5605     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5606   } else if (VT.isFloatingPoint()) {
5607     Vec = DAG.getConstantFP(+0.0, dl, VT);
5608   } else if (VT.getVectorElementType() == MVT::i1) {
5609     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
5610            "Unexpected vector type");
5611     Vec = DAG.getConstant(0, dl, VT);
5612   } else {
5613     unsigned Num32BitElts = VT.getSizeInBits() / 32;
5614     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5615   }
5616   return DAG.getBitcast(VT, Vec);
5617 }
5618 
extractSubVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5619 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5620                                 const SDLoc &dl, unsigned vectorWidth) {
5621   EVT VT = Vec.getValueType();
5622   EVT ElVT = VT.getVectorElementType();
5623   unsigned Factor = VT.getSizeInBits()/vectorWidth;
5624   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5625                                   VT.getVectorNumElements()/Factor);
5626 
5627   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
5628   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5629   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5630 
5631   // This is the index of the first element of the vectorWidth-bit chunk
5632   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5633   IdxVal &= ~(ElemsPerChunk - 1);
5634 
5635   // If the input is a buildvector just emit a smaller one.
5636   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5637     return DAG.getBuildVector(ResultVT, dl,
5638                               Vec->ops().slice(IdxVal, ElemsPerChunk));
5639 
5640   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5641   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5642 }
5643 
5644 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
5645 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5646 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5647 /// instructions or a simple subregister reference. Idx is an index in the
5648 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
5649 /// lowering EXTRACT_VECTOR_ELT operations easier.
extract128BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5650 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5651                                    SelectionDAG &DAG, const SDLoc &dl) {
5652   assert((Vec.getValueType().is256BitVector() ||
5653           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
5654   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5655 }
5656 
5657 /// Generate a DAG to grab 256-bits from a 512-bit vector.
extract256BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5658 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5659                                    SelectionDAG &DAG, const SDLoc &dl) {
5660   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
5661   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5662 }
5663 
insertSubVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5664 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5665                                SelectionDAG &DAG, const SDLoc &dl,
5666                                unsigned vectorWidth) {
5667   assert((vectorWidth == 128 || vectorWidth == 256) &&
5668          "Unsupported vector width");
5669   // Inserting UNDEF is Result
5670   if (Vec.isUndef())
5671     return Result;
5672   EVT VT = Vec.getValueType();
5673   EVT ElVT = VT.getVectorElementType();
5674   EVT ResultVT = Result.getValueType();
5675 
5676   // Insert the relevant vectorWidth bits.
5677   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5678   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5679 
5680   // This is the index of the first element of the vectorWidth-bit chunk
5681   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5682   IdxVal &= ~(ElemsPerChunk - 1);
5683 
5684   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5685   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5686 }
5687 
5688 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
5689 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5690 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5691 /// simple superregister reference.  Idx is an index in the 128 bits
5692 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
5693 /// lowering INSERT_VECTOR_ELT operations easier.
insert128BitVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5694 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5695                                   SelectionDAG &DAG, const SDLoc &dl) {
5696   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
5697   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5698 }
5699 
5700 /// Widen a vector to a larger size with the same scalar type, with the new
5701 /// elements either zero or undef.
widenSubVector(MVT VT,SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5702 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5703                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5704                               const SDLoc &dl) {
5705   assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&
5706          Vec.getValueType().getScalarType() == VT.getScalarType() &&
5707          "Unsupported vector widening type");
5708   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5709                                 : DAG.getUNDEF(VT);
5710   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5711                      DAG.getIntPtrConstant(0, dl));
5712 }
5713 
5714 /// Widen a vector to a larger size with the same scalar type, with the new
5715 /// elements either zero or undef.
widenSubVector(SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl,unsigned WideSizeInBits)5716 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
5717                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5718                               const SDLoc &dl, unsigned WideSizeInBits) {
5719   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
5720          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
5721          "Unsupported vector widening type");
5722   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
5723   MVT SVT = Vec.getSimpleValueType().getScalarType();
5724   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
5725   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
5726 }
5727 
5728 // Helper function to collect subvector ops that are concated together,
5729 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5730 // The subvectors in Ops are guaranteed to be the same type.
collectConcatOps(SDNode * N,SmallVectorImpl<SDValue> & Ops)5731 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5732   assert(Ops.empty() && "Expected an empty ops vector");
5733 
5734   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5735     Ops.append(N->op_begin(), N->op_end());
5736     return true;
5737   }
5738 
5739   if (N->getOpcode() == ISD::INSERT_SUBVECTOR &&
5740       isa<ConstantSDNode>(N->getOperand(2))) {
5741     SDValue Src = N->getOperand(0);
5742     SDValue Sub = N->getOperand(1);
5743     const APInt &Idx = N->getConstantOperandAPInt(2);
5744     EVT VT = Src.getValueType();
5745     EVT SubVT = Sub.getValueType();
5746 
5747     // TODO - Handle more general insert_subvector chains.
5748     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
5749         Idx == (VT.getVectorNumElements() / 2) &&
5750         Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
5751         Src.getOperand(1).getValueType() == SubVT &&
5752         isNullConstant(Src.getOperand(2))) {
5753       Ops.push_back(Src.getOperand(1));
5754       Ops.push_back(Sub);
5755       return true;
5756     }
5757   }
5758 
5759   return false;
5760 }
5761 
5762 // Helper for splitting operands of an operation to legal target size and
5763 // apply a function on each part.
5764 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5765 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5766 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5767 // The argument Builder is a function that will be applied on each split part:
5768 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5769 template <typename F>
SplitOpsAndApply(SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,F Builder,bool CheckBWI=true)5770 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5771                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5772                          F Builder, bool CheckBWI = true) {
5773   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
5774   unsigned NumSubs = 1;
5775   if ((CheckBWI && Subtarget.useBWIRegs()) ||
5776       (!CheckBWI && Subtarget.useAVX512Regs())) {
5777     if (VT.getSizeInBits() > 512) {
5778       NumSubs = VT.getSizeInBits() / 512;
5779       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
5780     }
5781   } else if (Subtarget.hasAVX2()) {
5782     if (VT.getSizeInBits() > 256) {
5783       NumSubs = VT.getSizeInBits() / 256;
5784       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
5785     }
5786   } else {
5787     if (VT.getSizeInBits() > 128) {
5788       NumSubs = VT.getSizeInBits() / 128;
5789       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
5790     }
5791   }
5792 
5793   if (NumSubs == 1)
5794     return Builder(DAG, DL, Ops);
5795 
5796   SmallVector<SDValue, 4> Subs;
5797   for (unsigned i = 0; i != NumSubs; ++i) {
5798     SmallVector<SDValue, 2> SubOps;
5799     for (SDValue Op : Ops) {
5800       EVT OpVT = Op.getValueType();
5801       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5802       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5803       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5804     }
5805     Subs.push_back(Builder(DAG, DL, SubOps));
5806   }
5807   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5808 }
5809 
5810 /// Insert i1-subvector to i1-vector.
insert1BitVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)5811 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5812                                 const X86Subtarget &Subtarget) {
5813 
5814   SDLoc dl(Op);
5815   SDValue Vec = Op.getOperand(0);
5816   SDValue SubVec = Op.getOperand(1);
5817   SDValue Idx = Op.getOperand(2);
5818 
5819   if (!isa<ConstantSDNode>(Idx))
5820     return SDValue();
5821 
5822   // Inserting undef is a nop. We can just return the original vector.
5823   if (SubVec.isUndef())
5824     return Vec;
5825 
5826   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5827   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5828     return Op;
5829 
5830   MVT OpVT = Op.getSimpleValueType();
5831   unsigned NumElems = OpVT.getVectorNumElements();
5832 
5833   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5834 
5835   // Extend to natively supported kshift.
5836   MVT WideOpVT = OpVT;
5837   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
5838     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5839 
5840   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
5841   // if necessary.
5842   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
5843     // May need to promote to a legal type.
5844     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5845                      DAG.getConstant(0, dl, WideOpVT),
5846                      SubVec, Idx);
5847     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5848   }
5849 
5850   MVT SubVecVT = SubVec.getSimpleValueType();
5851   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5852 
5853   assert(IdxVal + SubVecNumElems <= NumElems &&
5854          IdxVal % SubVecVT.getSizeInBits() == 0 &&
5855          "Unexpected index value in INSERT_SUBVECTOR");
5856 
5857   SDValue Undef = DAG.getUNDEF(WideOpVT);
5858 
5859   if (IdxVal == 0) {
5860     // Zero lower bits of the Vec
5861     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
5862     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
5863                       ZeroIdx);
5864     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5865     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5866     // Merge them together, SubVec should be zero extended.
5867     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5868                          DAG.getConstant(0, dl, WideOpVT),
5869                          SubVec, ZeroIdx);
5870     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5871     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5872   }
5873 
5874   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5875                        Undef, SubVec, ZeroIdx);
5876 
5877   if (Vec.isUndef()) {
5878     assert(IdxVal != 0 && "Unexpected index");
5879     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5880                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
5881     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5882   }
5883 
5884   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5885     assert(IdxVal != 0 && "Unexpected index");
5886     NumElems = WideOpVT.getVectorNumElements();
5887     unsigned ShiftLeft = NumElems - SubVecNumElems;
5888     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5889     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5890                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5891     if (ShiftRight != 0)
5892       SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5893                            DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5894     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5895   }
5896 
5897   // Simple case when we put subvector in the upper part
5898   if (IdxVal + SubVecNumElems == NumElems) {
5899     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5900                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
5901     if (SubVecNumElems * 2 == NumElems) {
5902       // Special case, use legal zero extending insert_subvector. This allows
5903       // isel to opimitize when bits are known zero.
5904       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
5905       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5906                         DAG.getConstant(0, dl, WideOpVT),
5907                         Vec, ZeroIdx);
5908     } else {
5909       // Otherwise use explicit shifts to zero the bits.
5910       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5911                         Undef, Vec, ZeroIdx);
5912       NumElems = WideOpVT.getVectorNumElements();
5913       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
5914       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5915       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5916     }
5917     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5918     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5919   }
5920 
5921   // Inserting into the middle is more complicated.
5922 
5923   NumElems = WideOpVT.getVectorNumElements();
5924 
5925   // Widen the vector if needed.
5926   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5927 
5928   unsigned ShiftLeft = NumElems - SubVecNumElems;
5929   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5930 
5931   // Do an optimization for the the most frequently used types.
5932   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
5933     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
5934     Mask0.flipAllBits();
5935     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
5936     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
5937     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
5938     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5939                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5940     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5941                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5942     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5943 
5944     // Reduce to original width if needed.
5945     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5946   }
5947 
5948   // Clear the upper bits of the subvector and move it to its insert position.
5949   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5950                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5951   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5952                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5953 
5954   // Isolate the bits below the insertion point.
5955   unsigned LowShift = NumElems - IdxVal;
5956   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
5957                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
5958   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
5959                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
5960 
5961   // Isolate the bits after the last inserted bit.
5962   unsigned HighShift = IdxVal + SubVecNumElems;
5963   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5964                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
5965   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
5966                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
5967 
5968   // Now OR all 3 pieces together.
5969   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
5970   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
5971 
5972   // Reduce to original width if needed.
5973   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5974 }
5975 
concatSubVectors(SDValue V1,SDValue V2,SelectionDAG & DAG,const SDLoc & dl)5976 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
5977                                 const SDLoc &dl) {
5978   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
5979   EVT SubVT = V1.getValueType();
5980   EVT SubSVT = SubVT.getScalarType();
5981   unsigned SubNumElts = SubVT.getVectorNumElements();
5982   unsigned SubVectorWidth = SubVT.getSizeInBits();
5983   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
5984   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
5985   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
5986 }
5987 
5988 /// Returns a vector of specified type with all bits set.
5989 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5990 /// Then bitcast to their original type, ensuring they get CSE'd.
getOnesVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)5991 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5992   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5993          "Expected a 128/256/512-bit vector type");
5994 
5995   APInt Ones = APInt::getAllOnesValue(32);
5996   unsigned NumElts = VT.getSizeInBits() / 32;
5997   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5998   return DAG.getBitcast(VT, Vec);
5999 }
6000 
6001 // Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode)6002 static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6003   switch (Opcode) {
6004   case ISD::ANY_EXTEND:
6005   case ISD::ANY_EXTEND_VECTOR_INREG:
6006     return ISD::ANY_EXTEND_VECTOR_INREG;
6007   case ISD::ZERO_EXTEND:
6008   case ISD::ZERO_EXTEND_VECTOR_INREG:
6009     return ISD::ZERO_EXTEND_VECTOR_INREG;
6010   case ISD::SIGN_EXTEND:
6011   case ISD::SIGN_EXTEND_VECTOR_INREG:
6012     return ISD::SIGN_EXTEND_VECTOR_INREG;
6013   }
6014   llvm_unreachable("Unknown opcode");
6015 }
6016 
getExtendInVec(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue In,SelectionDAG & DAG)6017 static SDValue getExtendInVec(unsigned Opcode, const SDLoc &DL, EVT VT,
6018                               SDValue In, SelectionDAG &DAG) {
6019   EVT InVT = In.getValueType();
6020   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
6021   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
6022           ISD::ZERO_EXTEND == Opcode) &&
6023          "Unknown extension opcode");
6024 
6025   // For 256-bit vectors, we only need the lower (128-bit) input half.
6026   // For 512-bit vectors, we only need the lower input half or quarter.
6027   if (InVT.getSizeInBits() > 128) {
6028     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
6029            "Expected VTs to be the same size!");
6030     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6031     In = extractSubVector(In, 0, DAG, DL,
6032                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6033     InVT = In.getValueType();
6034   }
6035 
6036   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6037     Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6038 
6039   return DAG.getNode(Opcode, DL, VT, In);
6040 }
6041 
6042 // Match (xor X, -1) -> X.
6043 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
6044 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
IsNOT(SDValue V,SelectionDAG & DAG)6045 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
6046   V = peekThroughBitcasts(V);
6047   if (V.getOpcode() == ISD::XOR &&
6048       ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6049     return V.getOperand(0);
6050   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6051       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6052     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6053       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6054       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6055                          Not, V.getOperand(1));
6056     }
6057   }
6058   SmallVector<SDValue, 2> CatOps;
6059   if (collectConcatOps(V.getNode(), CatOps)) {
6060     for (SDValue &CatOp : CatOps) {
6061       SDValue NotCat = IsNOT(CatOp, DAG);
6062       if (!NotCat) return SDValue();
6063       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6064     }
6065     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6066   }
6067   return SDValue();
6068 }
6069 
6070 /// Returns a vector_shuffle node for an unpackl operation.
getUnpackl(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)6071 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
6072                           SDValue V1, SDValue V2) {
6073   SmallVector<int, 8> Mask;
6074   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
6075   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6076 }
6077 
6078 /// Returns a vector_shuffle node for an unpackh operation.
getUnpackh(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)6079 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
6080                           SDValue V1, SDValue V2) {
6081   SmallVector<int, 8> Mask;
6082   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
6083   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6084 }
6085 
6086 /// Return a vector_shuffle of the specified vector of zero or undef vector.
6087 /// This produces a shuffle where the low element of V2 is swizzled into the
6088 /// zero/undef vector, landing at element Idx.
6089 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
getShuffleVectorZeroOrUndef(SDValue V2,int Idx,bool IsZero,const X86Subtarget & Subtarget,SelectionDAG & DAG)6090 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
6091                                            bool IsZero,
6092                                            const X86Subtarget &Subtarget,
6093                                            SelectionDAG &DAG) {
6094   MVT VT = V2.getSimpleValueType();
6095   SDValue V1 = IsZero
6096     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
6097   int NumElems = VT.getVectorNumElements();
6098   SmallVector<int, 16> MaskVec(NumElems);
6099   for (int i = 0; i != NumElems; ++i)
6100     // If this is the insertion idx, put the low elt of V2 here.
6101     MaskVec[i] = (i == Idx) ? NumElems : i;
6102   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
6103 }
6104 
getTargetConstantFromNode(LoadSDNode * Load)6105 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
6106   if (!Load || !ISD::isNormalLoad(Load))
6107     return nullptr;
6108 
6109   SDValue Ptr = Load->getBasePtr();
6110   if (Ptr->getOpcode() == X86ISD::Wrapper ||
6111       Ptr->getOpcode() == X86ISD::WrapperRIP)
6112     Ptr = Ptr->getOperand(0);
6113 
6114   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6115   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
6116     return nullptr;
6117 
6118   return CNode->getConstVal();
6119 }
6120 
getTargetConstantFromNode(SDValue Op)6121 static const Constant *getTargetConstantFromNode(SDValue Op) {
6122   Op = peekThroughBitcasts(Op);
6123   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
6124 }
6125 
6126 const Constant *
getTargetConstantFromLoad(LoadSDNode * LD) const6127 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
6128   assert(LD && "Unexpected null LoadSDNode");
6129   return getTargetConstantFromNode(LD);
6130 }
6131 
6132 // Extract raw constant bits from constant pools.
getTargetConstantBitsFromNode(SDValue Op,unsigned EltSizeInBits,APInt & UndefElts,SmallVectorImpl<APInt> & EltBits,bool AllowWholeUndefs=true,bool AllowPartialUndefs=true)6133 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
6134                                           APInt &UndefElts,
6135                                           SmallVectorImpl<APInt> &EltBits,
6136                                           bool AllowWholeUndefs = true,
6137                                           bool AllowPartialUndefs = true) {
6138   assert(EltBits.empty() && "Expected an empty EltBits vector");
6139 
6140   Op = peekThroughBitcasts(Op);
6141 
6142   EVT VT = Op.getValueType();
6143   unsigned SizeInBits = VT.getSizeInBits();
6144   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
6145   unsigned NumElts = SizeInBits / EltSizeInBits;
6146 
6147   // Bitcast a source array of element bits to the target size.
6148   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
6149     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
6150     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
6151     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
6152            "Constant bit sizes don't match");
6153 
6154     // Don't split if we don't allow undef bits.
6155     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
6156     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
6157       return false;
6158 
6159     // If we're already the right size, don't bother bitcasting.
6160     if (NumSrcElts == NumElts) {
6161       UndefElts = UndefSrcElts;
6162       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
6163       return true;
6164     }
6165 
6166     // Extract all the undef/constant element data and pack into single bitsets.
6167     APInt UndefBits(SizeInBits, 0);
6168     APInt MaskBits(SizeInBits, 0);
6169 
6170     for (unsigned i = 0; i != NumSrcElts; ++i) {
6171       unsigned BitOffset = i * SrcEltSizeInBits;
6172       if (UndefSrcElts[i])
6173         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
6174       MaskBits.insertBits(SrcEltBits[i], BitOffset);
6175     }
6176 
6177     // Split the undef/constant single bitset data into the target elements.
6178     UndefElts = APInt(NumElts, 0);
6179     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
6180 
6181     for (unsigned i = 0; i != NumElts; ++i) {
6182       unsigned BitOffset = i * EltSizeInBits;
6183       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
6184 
6185       // Only treat an element as UNDEF if all bits are UNDEF.
6186       if (UndefEltBits.isAllOnesValue()) {
6187         if (!AllowWholeUndefs)
6188           return false;
6189         UndefElts.setBit(i);
6190         continue;
6191       }
6192 
6193       // If only some bits are UNDEF then treat them as zero (or bail if not
6194       // supported).
6195       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
6196         return false;
6197 
6198       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
6199     }
6200     return true;
6201   };
6202 
6203   // Collect constant bits and insert into mask/undef bit masks.
6204   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
6205                                 unsigned UndefBitIndex) {
6206     if (!Cst)
6207       return false;
6208     if (isa<UndefValue>(Cst)) {
6209       Undefs.setBit(UndefBitIndex);
6210       return true;
6211     }
6212     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
6213       Mask = CInt->getValue();
6214       return true;
6215     }
6216     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
6217       Mask = CFP->getValueAPF().bitcastToAPInt();
6218       return true;
6219     }
6220     return false;
6221   };
6222 
6223   // Handle UNDEFs.
6224   if (Op.isUndef()) {
6225     APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
6226     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
6227     return CastBitData(UndefSrcElts, SrcEltBits);
6228   }
6229 
6230   // Extract scalar constant bits.
6231   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
6232     APInt UndefSrcElts = APInt::getNullValue(1);
6233     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
6234     return CastBitData(UndefSrcElts, SrcEltBits);
6235   }
6236   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6237     APInt UndefSrcElts = APInt::getNullValue(1);
6238     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6239     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
6240     return CastBitData(UndefSrcElts, SrcEltBits);
6241   }
6242 
6243   // Extract constant bits from build vector.
6244   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
6245     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6246     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6247 
6248     APInt UndefSrcElts(NumSrcElts, 0);
6249     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6250     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6251       const SDValue &Src = Op.getOperand(i);
6252       if (Src.isUndef()) {
6253         UndefSrcElts.setBit(i);
6254         continue;
6255       }
6256       auto *Cst = cast<ConstantSDNode>(Src);
6257       SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
6258     }
6259     return CastBitData(UndefSrcElts, SrcEltBits);
6260   }
6261   if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
6262     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6263     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6264 
6265     APInt UndefSrcElts(NumSrcElts, 0);
6266     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6267     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6268       const SDValue &Src = Op.getOperand(i);
6269       if (Src.isUndef()) {
6270         UndefSrcElts.setBit(i);
6271         continue;
6272       }
6273       auto *Cst = cast<ConstantFPSDNode>(Src);
6274       APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6275       SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
6276     }
6277     return CastBitData(UndefSrcElts, SrcEltBits);
6278   }
6279 
6280   // Extract constant bits from constant pool vector.
6281   if (auto *Cst = getTargetConstantFromNode(Op)) {
6282     Type *CstTy = Cst->getType();
6283     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6284     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
6285       return false;
6286 
6287     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
6288     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6289 
6290     APInt UndefSrcElts(NumSrcElts, 0);
6291     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6292     for (unsigned i = 0; i != NumSrcElts; ++i)
6293       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
6294                                UndefSrcElts, i))
6295         return false;
6296 
6297     return CastBitData(UndefSrcElts, SrcEltBits);
6298   }
6299 
6300   // Extract constant bits from a broadcasted constant pool scalar.
6301   if (Op.getOpcode() == X86ISD::VBROADCAST &&
6302       EltSizeInBits <= VT.getScalarSizeInBits()) {
6303     if (auto *Broadcast = getTargetConstantFromNode(Op.getOperand(0))) {
6304       unsigned SrcEltSizeInBits = Broadcast->getType()->getScalarSizeInBits();
6305       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6306 
6307       APInt UndefSrcElts(NumSrcElts, 0);
6308       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
6309       if (CollectConstantBits(Broadcast, SrcEltBits[0], UndefSrcElts, 0)) {
6310         if (UndefSrcElts[0])
6311           UndefSrcElts.setBits(0, NumSrcElts);
6312         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
6313         return CastBitData(UndefSrcElts, SrcEltBits);
6314       }
6315     }
6316   }
6317 
6318   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
6319       EltSizeInBits <= VT.getScalarSizeInBits()) {
6320     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6321     if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
6322       return false;
6323 
6324     SDValue Ptr = MemIntr->getBasePtr();
6325     if (Ptr->getOpcode() == X86ISD::Wrapper ||
6326         Ptr->getOpcode() == X86ISD::WrapperRIP)
6327       Ptr = Ptr->getOperand(0);
6328 
6329     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6330     if (!CNode || CNode->isMachineConstantPoolEntry() ||
6331         CNode->getOffset() != 0)
6332       return false;
6333 
6334     if (const Constant *C = CNode->getConstVal()) {
6335       unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
6336       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6337 
6338       APInt UndefSrcElts(NumSrcElts, 0);
6339       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
6340       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
6341         if (UndefSrcElts[0])
6342           UndefSrcElts.setBits(0, NumSrcElts);
6343         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
6344         return CastBitData(UndefSrcElts, SrcEltBits);
6345       }
6346     }
6347   }
6348 
6349   // Extract constant bits from a subvector broadcast.
6350   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST) {
6351     SmallVector<APInt, 16> SubEltBits;
6352     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6353                                       UndefElts, SubEltBits, AllowWholeUndefs,
6354                                       AllowPartialUndefs)) {
6355       UndefElts = APInt::getSplat(NumElts, UndefElts);
6356       while (EltBits.size() < NumElts)
6357         EltBits.append(SubEltBits.begin(), SubEltBits.end());
6358       return true;
6359     }
6360   }
6361 
6362   // Extract a rematerialized scalar constant insertion.
6363   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
6364       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6365       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
6366     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6367     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6368 
6369     APInt UndefSrcElts(NumSrcElts, 0);
6370     SmallVector<APInt, 64> SrcEltBits;
6371     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
6372     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
6373     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
6374     return CastBitData(UndefSrcElts, SrcEltBits);
6375   }
6376 
6377   // Insert constant bits from a base and sub vector sources.
6378   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR &&
6379       isa<ConstantSDNode>(Op.getOperand(2))) {
6380     // TODO - support insert_subvector through bitcasts.
6381     if (EltSizeInBits != VT.getScalarSizeInBits())
6382       return false;
6383 
6384     APInt UndefSubElts;
6385     SmallVector<APInt, 32> EltSubBits;
6386     if (getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6387                                       UndefSubElts, EltSubBits,
6388                                       AllowWholeUndefs, AllowPartialUndefs) &&
6389         getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6390                                       UndefElts, EltBits, AllowWholeUndefs,
6391                                       AllowPartialUndefs)) {
6392       unsigned BaseIdx = Op.getConstantOperandVal(2);
6393       UndefElts.insertBits(UndefSubElts, BaseIdx);
6394       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
6395         EltBits[BaseIdx + i] = EltSubBits[i];
6396       return true;
6397     }
6398   }
6399 
6400   // Extract constant bits from a subvector's source.
6401   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6402       isa<ConstantSDNode>(Op.getOperand(1))) {
6403     // TODO - support extract_subvector through bitcasts.
6404     if (EltSizeInBits != VT.getScalarSizeInBits())
6405       return false;
6406 
6407     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6408                                       UndefElts, EltBits, AllowWholeUndefs,
6409                                       AllowPartialUndefs)) {
6410       EVT SrcVT = Op.getOperand(0).getValueType();
6411       unsigned NumSrcElts = SrcVT.getVectorNumElements();
6412       unsigned NumSubElts = VT.getVectorNumElements();
6413       unsigned BaseIdx = Op.getConstantOperandVal(1);
6414       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
6415       if ((BaseIdx + NumSubElts) != NumSrcElts)
6416         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
6417       if (BaseIdx != 0)
6418         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
6419       return true;
6420     }
6421   }
6422 
6423   // Extract constant bits from shuffle node sources.
6424   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
6425     // TODO - support shuffle through bitcasts.
6426     if (EltSizeInBits != VT.getScalarSizeInBits())
6427       return false;
6428 
6429     ArrayRef<int> Mask = SVN->getMask();
6430     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
6431         llvm::any_of(Mask, [](int M) { return M < 0; }))
6432       return false;
6433 
6434     APInt UndefElts0, UndefElts1;
6435     SmallVector<APInt, 32> EltBits0, EltBits1;
6436     if (isAnyInRange(Mask, 0, NumElts) &&
6437         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6438                                        UndefElts0, EltBits0, AllowWholeUndefs,
6439                                        AllowPartialUndefs))
6440       return false;
6441     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
6442         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6443                                        UndefElts1, EltBits1, AllowWholeUndefs,
6444                                        AllowPartialUndefs))
6445       return false;
6446 
6447     UndefElts = APInt::getNullValue(NumElts);
6448     for (int i = 0; i != (int)NumElts; ++i) {
6449       int M = Mask[i];
6450       if (M < 0) {
6451         UndefElts.setBit(i);
6452         EltBits.push_back(APInt::getNullValue(EltSizeInBits));
6453       } else if (M < (int)NumElts) {
6454         if (UndefElts0[M])
6455           UndefElts.setBit(i);
6456         EltBits.push_back(EltBits0[M]);
6457       } else {
6458         if (UndefElts1[M - NumElts])
6459           UndefElts.setBit(i);
6460         EltBits.push_back(EltBits1[M - NumElts]);
6461       }
6462     }
6463     return true;
6464   }
6465 
6466   return false;
6467 }
6468 
6469 namespace llvm {
6470 namespace X86 {
isConstantSplat(SDValue Op,APInt & SplatVal)6471 bool isConstantSplat(SDValue Op, APInt &SplatVal) {
6472   APInt UndefElts;
6473   SmallVector<APInt, 16> EltBits;
6474   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
6475                                     UndefElts, EltBits, true, false)) {
6476     int SplatIndex = -1;
6477     for (int i = 0, e = EltBits.size(); i != e; ++i) {
6478       if (UndefElts[i])
6479         continue;
6480       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
6481         SplatIndex = -1;
6482         break;
6483       }
6484       SplatIndex = i;
6485     }
6486     if (0 <= SplatIndex) {
6487       SplatVal = EltBits[SplatIndex];
6488       return true;
6489     }
6490   }
6491 
6492   return false;
6493 }
6494 } // namespace X86
6495 } // namespace llvm
6496 
getTargetShuffleMaskIndices(SDValue MaskNode,unsigned MaskEltSizeInBits,SmallVectorImpl<uint64_t> & RawMask,APInt & UndefElts)6497 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6498                                         unsigned MaskEltSizeInBits,
6499                                         SmallVectorImpl<uint64_t> &RawMask,
6500                                         APInt &UndefElts) {
6501   // Extract the raw target constant bits.
6502   SmallVector<APInt, 64> EltBits;
6503   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6504                                      EltBits, /* AllowWholeUndefs */ true,
6505                                      /* AllowPartialUndefs */ false))
6506     return false;
6507 
6508   // Insert the extracted elements into the mask.
6509   for (APInt Elt : EltBits)
6510     RawMask.push_back(Elt.getZExtValue());
6511 
6512   return true;
6513 }
6514 
6515 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6516 /// Note: This ignores saturation, so inputs must be checked first.
createPackShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Unary)6517 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6518                                   bool Unary) {
6519   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6520   unsigned NumElts = VT.getVectorNumElements();
6521   unsigned NumLanes = VT.getSizeInBits() / 128;
6522   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6523   unsigned Offset = Unary ? 0 : NumElts;
6524 
6525   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6526     for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6527       Mask.push_back(Elt + (Lane * NumEltsPerLane));
6528     for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6529       Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6530   }
6531 }
6532 
6533 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
getPackDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)6534 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6535                                 APInt &DemandedLHS, APInt &DemandedRHS) {
6536   int NumLanes = VT.getSizeInBits() / 128;
6537   int NumElts = DemandedElts.getBitWidth();
6538   int NumInnerElts = NumElts / 2;
6539   int NumEltsPerLane = NumElts / NumLanes;
6540   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6541 
6542   DemandedLHS = APInt::getNullValue(NumInnerElts);
6543   DemandedRHS = APInt::getNullValue(NumInnerElts);
6544 
6545   // Map DemandedElts to the packed operands.
6546   for (int Lane = 0; Lane != NumLanes; ++Lane) {
6547     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6548       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6549       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6550       if (DemandedElts[OuterIdx])
6551         DemandedLHS.setBit(InnerIdx);
6552       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6553         DemandedRHS.setBit(InnerIdx);
6554     }
6555   }
6556 }
6557 
6558 // Split the demanded elts of a HADD/HSUB node between its operands.
getHorizDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)6559 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6560                                  APInt &DemandedLHS, APInt &DemandedRHS) {
6561   int NumLanes = VT.getSizeInBits() / 128;
6562   int NumElts = DemandedElts.getBitWidth();
6563   int NumEltsPerLane = NumElts / NumLanes;
6564   int HalfEltsPerLane = NumEltsPerLane / 2;
6565 
6566   DemandedLHS = APInt::getNullValue(NumElts);
6567   DemandedRHS = APInt::getNullValue(NumElts);
6568 
6569   // Map DemandedElts to the horizontal operands.
6570   for (int Idx = 0; Idx != NumElts; ++Idx) {
6571     if (!DemandedElts[Idx])
6572       continue;
6573     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
6574     int LocalIdx = Idx % NumEltsPerLane;
6575     if (LocalIdx < HalfEltsPerLane) {
6576       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6577       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6578     } else {
6579       LocalIdx -= HalfEltsPerLane;
6580       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6581       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6582     }
6583   }
6584 }
6585 
6586 /// Calculates the shuffle mask corresponding to the target-specific opcode.
6587 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6588 /// operands in \p Ops, and returns true.
6589 /// Sets \p IsUnary to true if only one source is used. Note that this will set
6590 /// IsUnary for shuffles which use a single input multiple times, and in those
6591 /// cases it will adjust the mask to only have indices within that single input.
6592 /// It is an error to call this with non-empty Mask/Ops vectors.
getTargetShuffleMask(SDNode * N,MVT VT,bool AllowSentinelZero,SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<int> & Mask,bool & IsUnary)6593 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6594                                  SmallVectorImpl<SDValue> &Ops,
6595                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
6596   unsigned NumElems = VT.getVectorNumElements();
6597   unsigned MaskEltSize = VT.getScalarSizeInBits();
6598   SmallVector<uint64_t, 32> RawMask;
6599   APInt RawUndefs;
6600   SDValue ImmN;
6601 
6602   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6603   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6604 
6605   IsUnary = false;
6606   bool IsFakeUnary = false;
6607   switch (N->getOpcode()) {
6608   case X86ISD::BLENDI:
6609     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6610     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6611     ImmN = N->getOperand(N->getNumOperands() - 1);
6612     DecodeBLENDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6613     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6614     break;
6615   case X86ISD::SHUFP:
6616     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6617     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6618     ImmN = N->getOperand(N->getNumOperands() - 1);
6619     DecodeSHUFPMask(NumElems, MaskEltSize,
6620                     cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6621     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6622     break;
6623   case X86ISD::INSERTPS:
6624     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6625     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6626     ImmN = N->getOperand(N->getNumOperands() - 1);
6627     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6628     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6629     break;
6630   case X86ISD::EXTRQI:
6631     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6632     if (isa<ConstantSDNode>(N->getOperand(1)) &&
6633         isa<ConstantSDNode>(N->getOperand(2))) {
6634       int BitLen = N->getConstantOperandVal(1);
6635       int BitIdx = N->getConstantOperandVal(2);
6636       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6637       IsUnary = true;
6638     }
6639     break;
6640   case X86ISD::INSERTQI:
6641     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6642     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6643     if (isa<ConstantSDNode>(N->getOperand(2)) &&
6644         isa<ConstantSDNode>(N->getOperand(3))) {
6645       int BitLen = N->getConstantOperandVal(2);
6646       int BitIdx = N->getConstantOperandVal(3);
6647       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6648       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6649     }
6650     break;
6651   case X86ISD::UNPCKH:
6652     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6653     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6654     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6655     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6656     break;
6657   case X86ISD::UNPCKL:
6658     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6659     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6660     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6661     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6662     break;
6663   case X86ISD::MOVHLPS:
6664     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6665     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6666     DecodeMOVHLPSMask(NumElems, Mask);
6667     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6668     break;
6669   case X86ISD::MOVLHPS:
6670     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6671     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6672     DecodeMOVLHPSMask(NumElems, Mask);
6673     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6674     break;
6675   case X86ISD::PALIGNR:
6676     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6677     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6678     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6679     ImmN = N->getOperand(N->getNumOperands() - 1);
6680     DecodePALIGNRMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6681                       Mask);
6682     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6683     Ops.push_back(N->getOperand(1));
6684     Ops.push_back(N->getOperand(0));
6685     break;
6686   case X86ISD::VSHLDQ:
6687     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6688     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6689     ImmN = N->getOperand(N->getNumOperands() - 1);
6690     DecodePSLLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6691                      Mask);
6692     IsUnary = true;
6693     break;
6694   case X86ISD::VSRLDQ:
6695     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6696     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6697     ImmN = N->getOperand(N->getNumOperands() - 1);
6698     DecodePSRLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6699                      Mask);
6700     IsUnary = true;
6701     break;
6702   case X86ISD::PSHUFD:
6703   case X86ISD::VPERMILPI:
6704     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6705     ImmN = N->getOperand(N->getNumOperands() - 1);
6706     DecodePSHUFMask(NumElems, MaskEltSize,
6707                     cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6708     IsUnary = true;
6709     break;
6710   case X86ISD::PSHUFHW:
6711     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6712     ImmN = N->getOperand(N->getNumOperands() - 1);
6713     DecodePSHUFHWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6714                       Mask);
6715     IsUnary = true;
6716     break;
6717   case X86ISD::PSHUFLW:
6718     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6719     ImmN = N->getOperand(N->getNumOperands() - 1);
6720     DecodePSHUFLWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6721                       Mask);
6722     IsUnary = true;
6723     break;
6724   case X86ISD::VZEXT_MOVL:
6725     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6726     DecodeZeroMoveLowMask(NumElems, Mask);
6727     IsUnary = true;
6728     break;
6729   case X86ISD::VBROADCAST: {
6730     SDValue N0 = N->getOperand(0);
6731     // See if we're broadcasting from index 0 of an EXTRACT_SUBVECTOR. If so,
6732     // add the pre-extracted value to the Ops vector.
6733     if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6734         N0.getOperand(0).getValueType() == VT &&
6735         N0.getConstantOperandVal(1) == 0)
6736       Ops.push_back(N0.getOperand(0));
6737 
6738     // We only decode broadcasts of same-sized vectors, unless the broadcast
6739     // came from an extract from the original width. If we found one, we
6740     // pushed it the Ops vector above.
6741     if (N0.getValueType() == VT || !Ops.empty()) {
6742       DecodeVectorBroadcast(NumElems, Mask);
6743       IsUnary = true;
6744       break;
6745     }
6746     return false;
6747   }
6748   case X86ISD::VPERMILPV: {
6749     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6750     IsUnary = true;
6751     SDValue MaskNode = N->getOperand(1);
6752     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6753                                     RawUndefs)) {
6754       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6755       break;
6756     }
6757     return false;
6758   }
6759   case X86ISD::PSHUFB: {
6760     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6761     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6762     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6763     IsUnary = true;
6764     SDValue MaskNode = N->getOperand(1);
6765     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6766       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6767       break;
6768     }
6769     return false;
6770   }
6771   case X86ISD::VPERMI:
6772     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6773     ImmN = N->getOperand(N->getNumOperands() - 1);
6774     DecodeVPERMMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6775     IsUnary = true;
6776     break;
6777   case X86ISD::MOVSS:
6778   case X86ISD::MOVSD:
6779     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6780     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6781     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6782     break;
6783   case X86ISD::VPERM2X128:
6784     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6785     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6786     ImmN = N->getOperand(N->getNumOperands() - 1);
6787     DecodeVPERM2X128Mask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6788                          Mask);
6789     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6790     break;
6791   case X86ISD::SHUF128:
6792     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6793     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6794     ImmN = N->getOperand(N->getNumOperands() - 1);
6795     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize,
6796                               cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6797     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6798     break;
6799   case X86ISD::MOVSLDUP:
6800     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6801     DecodeMOVSLDUPMask(NumElems, Mask);
6802     IsUnary = true;
6803     break;
6804   case X86ISD::MOVSHDUP:
6805     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6806     DecodeMOVSHDUPMask(NumElems, Mask);
6807     IsUnary = true;
6808     break;
6809   case X86ISD::MOVDDUP:
6810     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6811     DecodeMOVDDUPMask(NumElems, Mask);
6812     IsUnary = true;
6813     break;
6814   case X86ISD::VPERMIL2: {
6815     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6816     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6817     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6818     SDValue MaskNode = N->getOperand(2);
6819     SDValue CtrlNode = N->getOperand(3);
6820     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6821       unsigned CtrlImm = CtrlOp->getZExtValue();
6822       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6823                                       RawUndefs)) {
6824         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6825                             Mask);
6826         break;
6827       }
6828     }
6829     return false;
6830   }
6831   case X86ISD::VPPERM: {
6832     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6833     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6834     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6835     SDValue MaskNode = N->getOperand(2);
6836     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6837       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6838       break;
6839     }
6840     return false;
6841   }
6842   case X86ISD::VPERMV: {
6843     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6844     IsUnary = true;
6845     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6846     Ops.push_back(N->getOperand(1));
6847     SDValue MaskNode = N->getOperand(0);
6848     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6849                                     RawUndefs)) {
6850       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6851       break;
6852     }
6853     return false;
6854   }
6855   case X86ISD::VPERMV3: {
6856     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6857     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
6858     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
6859     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6860     Ops.push_back(N->getOperand(0));
6861     Ops.push_back(N->getOperand(2));
6862     SDValue MaskNode = N->getOperand(1);
6863     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6864                                     RawUndefs)) {
6865       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6866       break;
6867     }
6868     return false;
6869   }
6870   default: llvm_unreachable("unknown target shuffle node");
6871   }
6872 
6873   // Empty mask indicates the decode failed.
6874   if (Mask.empty())
6875     return false;
6876 
6877   // Check if we're getting a shuffle mask with zero'd elements.
6878   if (!AllowSentinelZero)
6879     if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
6880       return false;
6881 
6882   // If we have a fake unary shuffle, the shuffle mask is spread across two
6883   // inputs that are actually the same node. Re-map the mask to always point
6884   // into the first input.
6885   if (IsFakeUnary)
6886     for (int &M : Mask)
6887       if (M >= (int)Mask.size())
6888         M -= Mask.size();
6889 
6890   // If we didn't already add operands in the opcode-specific code, default to
6891   // adding 1 or 2 operands starting at 0.
6892   if (Ops.empty()) {
6893     Ops.push_back(N->getOperand(0));
6894     if (!IsUnary || IsFakeUnary)
6895       Ops.push_back(N->getOperand(1));
6896   }
6897 
6898   return true;
6899 }
6900 
6901 /// Compute whether each element of a shuffle is zeroable.
6902 ///
6903 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6904 /// Either it is an undef element in the shuffle mask, the element of the input
6905 /// referenced is undef, or the element of the input referenced is known to be
6906 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6907 /// as many lanes with this technique as possible to simplify the remaining
6908 /// shuffle.
computeZeroableShuffleElements(ArrayRef<int> Mask,SDValue V1,SDValue V2,APInt & KnownUndef,APInt & KnownZero)6909 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
6910                                            SDValue V1, SDValue V2,
6911                                            APInt &KnownUndef, APInt &KnownZero) {
6912   int Size = Mask.size();
6913   KnownUndef = KnownZero = APInt::getNullValue(Size);
6914 
6915   V1 = peekThroughBitcasts(V1);
6916   V2 = peekThroughBitcasts(V2);
6917 
6918   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6919   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6920 
6921   int VectorSizeInBits = V1.getValueSizeInBits();
6922   int ScalarSizeInBits = VectorSizeInBits / Size;
6923   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
6924 
6925   for (int i = 0; i < Size; ++i) {
6926     int M = Mask[i];
6927     // Handle the easy cases.
6928     if (M < 0) {
6929       KnownUndef.setBit(i);
6930       continue;
6931     }
6932     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6933       KnownZero.setBit(i);
6934       continue;
6935     }
6936 
6937     // Determine shuffle input and normalize the mask.
6938     SDValue V = M < Size ? V1 : V2;
6939     M %= Size;
6940 
6941     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
6942     if (V.getOpcode() != ISD::BUILD_VECTOR)
6943       continue;
6944 
6945     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
6946     // the (larger) source element must be UNDEF/ZERO.
6947     if ((Size % V.getNumOperands()) == 0) {
6948       int Scale = Size / V->getNumOperands();
6949       SDValue Op = V.getOperand(M / Scale);
6950       if (Op.isUndef())
6951         KnownUndef.setBit(i);
6952       if (X86::isZeroNode(Op))
6953         KnownZero.setBit(i);
6954       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
6955         APInt Val = Cst->getAPIntValue();
6956         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6957         if (Val == 0)
6958           KnownZero.setBit(i);
6959       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6960         APInt Val = Cst->getValueAPF().bitcastToAPInt();
6961         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6962         if (Val == 0)
6963           KnownZero.setBit(i);
6964       }
6965       continue;
6966     }
6967 
6968     // If the BUILD_VECTOR has more elements then all the (smaller) source
6969     // elements must be UNDEF or ZERO.
6970     if ((V.getNumOperands() % Size) == 0) {
6971       int Scale = V->getNumOperands() / Size;
6972       bool AllUndef = true;
6973       bool AllZero = true;
6974       for (int j = 0; j < Scale; ++j) {
6975         SDValue Op = V.getOperand((M * Scale) + j);
6976         AllUndef &= Op.isUndef();
6977         AllZero &= X86::isZeroNode(Op);
6978       }
6979       if (AllUndef)
6980         KnownUndef.setBit(i);
6981       if (AllZero)
6982         KnownZero.setBit(i);
6983       continue;
6984     }
6985   }
6986 }
6987 
6988 /// Decode a target shuffle mask and inputs and see if any values are
6989 /// known to be undef or zero from their inputs.
6990 /// Returns true if the target shuffle mask was decoded.
6991 /// FIXME: Merge this with computeZeroableShuffleElements?
getTargetShuffleAndZeroables(SDValue N,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,APInt & KnownUndef,APInt & KnownZero)6992 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
6993                                          SmallVectorImpl<SDValue> &Ops,
6994                                          APInt &KnownUndef, APInt &KnownZero) {
6995   bool IsUnary;
6996   if (!isTargetShuffle(N.getOpcode()))
6997     return false;
6998 
6999   MVT VT = N.getSimpleValueType();
7000   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
7001     return false;
7002 
7003   int Size = Mask.size();
7004   SDValue V1 = Ops[0];
7005   SDValue V2 = IsUnary ? V1 : Ops[1];
7006   KnownUndef = KnownZero = APInt::getNullValue(Size);
7007 
7008   V1 = peekThroughBitcasts(V1);
7009   V2 = peekThroughBitcasts(V2);
7010 
7011   assert((VT.getSizeInBits() % Size) == 0 &&
7012          "Illegal split of shuffle value type");
7013   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
7014 
7015   // Extract known constant input data.
7016   APInt UndefSrcElts[2];
7017   SmallVector<APInt, 32> SrcEltBits[2];
7018   bool IsSrcConstant[2] = {
7019       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
7020                                     SrcEltBits[0], true, false),
7021       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
7022                                     SrcEltBits[1], true, false)};
7023 
7024   for (int i = 0; i < Size; ++i) {
7025     int M = Mask[i];
7026 
7027     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
7028     if (M < 0) {
7029       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
7030       if (SM_SentinelUndef == M)
7031         KnownUndef.setBit(i);
7032       if (SM_SentinelZero == M)
7033         KnownZero.setBit(i);
7034       continue;
7035     }
7036 
7037     // Determine shuffle input and normalize the mask.
7038     unsigned SrcIdx = M / Size;
7039     SDValue V = M < Size ? V1 : V2;
7040     M %= Size;
7041 
7042     // We are referencing an UNDEF input.
7043     if (V.isUndef()) {
7044       KnownUndef.setBit(i);
7045       continue;
7046     }
7047 
7048     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
7049     // TODO: We currently only set UNDEF for integer types - floats use the same
7050     // registers as vectors and many of the scalar folded loads rely on the
7051     // SCALAR_TO_VECTOR pattern.
7052     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7053         (Size % V.getValueType().getVectorNumElements()) == 0) {
7054       int Scale = Size / V.getValueType().getVectorNumElements();
7055       int Idx = M / Scale;
7056       if (Idx != 0 && !VT.isFloatingPoint())
7057         KnownUndef.setBit(i);
7058       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
7059         KnownZero.setBit(i);
7060       continue;
7061     }
7062 
7063     // Attempt to extract from the source's constant bits.
7064     if (IsSrcConstant[SrcIdx]) {
7065       if (UndefSrcElts[SrcIdx][M])
7066         KnownUndef.setBit(i);
7067       else if (SrcEltBits[SrcIdx][M] == 0)
7068         KnownZero.setBit(i);
7069     }
7070   }
7071 
7072   assert(VT.getVectorNumElements() == (unsigned)Size &&
7073          "Different mask size from vector size!");
7074   return true;
7075 }
7076 
7077 // Replace target shuffle mask elements with known undef/zero sentinels.
resolveTargetShuffleFromZeroables(SmallVectorImpl<int> & Mask,const APInt & KnownUndef,const APInt & KnownZero,bool ResolveKnownZeros=true)7078 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
7079                                               const APInt &KnownUndef,
7080                                               const APInt &KnownZero,
7081                                               bool ResolveKnownZeros= true) {
7082   unsigned NumElts = Mask.size();
7083   assert(KnownUndef.getBitWidth() == NumElts &&
7084          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
7085 
7086   for (unsigned i = 0; i != NumElts; ++i) {
7087     if (KnownUndef[i])
7088       Mask[i] = SM_SentinelUndef;
7089     else if (ResolveKnownZeros && KnownZero[i])
7090       Mask[i] = SM_SentinelZero;
7091   }
7092 }
7093 
7094 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> & Mask,APInt & KnownUndef,APInt & KnownZero)7095 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
7096                                               APInt &KnownUndef,
7097                                               APInt &KnownZero) {
7098   unsigned NumElts = Mask.size();
7099   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
7100 
7101   for (unsigned i = 0; i != NumElts; ++i) {
7102     int M = Mask[i];
7103     if (SM_SentinelUndef == M)
7104       KnownUndef.setBit(i);
7105     if (SM_SentinelZero == M)
7106       KnownZero.setBit(i);
7107   }
7108 }
7109 
7110 // Forward declaration (for getFauxShuffleMask recursive check).
7111 // TODO: Use DemandedElts variant.
7112 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7113                                    SmallVectorImpl<int> &Mask,
7114                                    SelectionDAG &DAG, unsigned Depth,
7115                                    bool ResolveKnownElts);
7116 
7117 // Attempt to decode ops that could be represented as a shuffle mask.
7118 // The decoded shuffle mask may contain a different number of elements to the
7119 // destination value type.
getFauxShuffleMask(SDValue N,const APInt & DemandedElts,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)7120 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
7121                                SmallVectorImpl<int> &Mask,
7122                                SmallVectorImpl<SDValue> &Ops,
7123                                SelectionDAG &DAG, unsigned Depth,
7124                                bool ResolveKnownElts) {
7125   if (Depth > SelectionDAG::MaxRecursionDepth)
7126     return false;
7127 
7128   Mask.clear();
7129   Ops.clear();
7130 
7131   MVT VT = N.getSimpleValueType();
7132   unsigned NumElts = VT.getVectorNumElements();
7133   unsigned NumSizeInBits = VT.getSizeInBits();
7134   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7135   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
7136     return false;
7137   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
7138 
7139   unsigned Opcode = N.getOpcode();
7140   switch (Opcode) {
7141   case ISD::VECTOR_SHUFFLE: {
7142     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
7143     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
7144     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
7145       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
7146       Ops.push_back(N.getOperand(0));
7147       Ops.push_back(N.getOperand(1));
7148       return true;
7149     }
7150     return false;
7151   }
7152   case ISD::AND:
7153   case X86ISD::ANDNP: {
7154     // Attempt to decode as a per-byte mask.
7155     APInt UndefElts;
7156     SmallVector<APInt, 32> EltBits;
7157     SDValue N0 = N.getOperand(0);
7158     SDValue N1 = N.getOperand(1);
7159     bool IsAndN = (X86ISD::ANDNP == Opcode);
7160     uint64_t ZeroMask = IsAndN ? 255 : 0;
7161     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
7162       return false;
7163     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
7164       if (UndefElts[i]) {
7165         Mask.push_back(SM_SentinelUndef);
7166         continue;
7167       }
7168       const APInt &ByteBits = EltBits[i];
7169       if (ByteBits != 0 && ByteBits != 255)
7170         return false;
7171       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
7172     }
7173     Ops.push_back(IsAndN ? N1 : N0);
7174     return true;
7175   }
7176   case ISD::OR: {
7177     // Inspect each operand at the byte level. We can merge these into a
7178     // blend shuffle mask if for each byte at least one is masked out (zero).
7179     KnownBits Known0 =
7180         DAG.computeKnownBits(N.getOperand(0), DemandedElts, Depth + 1);
7181     KnownBits Known1 =
7182         DAG.computeKnownBits(N.getOperand(1), DemandedElts, Depth + 1);
7183     if (Known0.One.isNullValue() && Known1.One.isNullValue()) {
7184       bool IsByteMask = true;
7185       unsigned NumSizeInBytes = NumSizeInBits / 8;
7186       unsigned NumBytesPerElt = NumBitsPerElt / 8;
7187       APInt ZeroMask = APInt::getNullValue(NumBytesPerElt);
7188       APInt SelectMask = APInt::getNullValue(NumBytesPerElt);
7189       for (unsigned i = 0; i != NumBytesPerElt && IsByteMask; ++i) {
7190         unsigned LHS = Known0.Zero.extractBits(8, i * 8).getZExtValue();
7191         unsigned RHS = Known1.Zero.extractBits(8, i * 8).getZExtValue();
7192         if (LHS == 255 && RHS == 0)
7193           SelectMask.setBit(i);
7194         else if (LHS == 255 && RHS == 255)
7195           ZeroMask.setBit(i);
7196         else if (!(LHS == 0 && RHS == 255))
7197           IsByteMask = false;
7198       }
7199       if (IsByteMask) {
7200         for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt) {
7201           for (unsigned j = 0; j != NumBytesPerElt; ++j) {
7202             unsigned Ofs = (SelectMask[j] ? NumSizeInBytes : 0);
7203             int Idx = (ZeroMask[j] ? (int)SM_SentinelZero : (i + j + Ofs));
7204             Mask.push_back(Idx);
7205           }
7206         }
7207         Ops.push_back(N.getOperand(0));
7208         Ops.push_back(N.getOperand(1));
7209         return true;
7210       }
7211     }
7212 
7213     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
7214     // is a valid shuffle index.
7215     SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
7216     SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
7217     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
7218       return false;
7219     SmallVector<int, 64> SrcMask0, SrcMask1;
7220     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
7221     if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
7222                                 true) ||
7223         !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
7224                                 true))
7225       return false;
7226     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
7227     SmallVector<int, 64> Mask0, Mask1;
7228     scaleShuffleMask<int>(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
7229     scaleShuffleMask<int>(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
7230     for (size_t i = 0; i != MaskSize; ++i) {
7231       if (Mask0[i] == SM_SentinelUndef && Mask1[i] == SM_SentinelUndef)
7232         Mask.push_back(SM_SentinelUndef);
7233       else if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
7234         Mask.push_back(SM_SentinelZero);
7235       else if (Mask1[i] == SM_SentinelZero)
7236         Mask.push_back(Mask0[i]);
7237       else if (Mask0[i] == SM_SentinelZero)
7238         Mask.push_back(Mask1[i] + (int)(MaskSize * SrcInputs0.size()));
7239       else
7240         return false;
7241     }
7242     Ops.append(SrcInputs0.begin(), SrcInputs0.end());
7243     Ops.append(SrcInputs1.begin(), SrcInputs1.end());
7244     return true;
7245   }
7246   case ISD::INSERT_SUBVECTOR: {
7247     SDValue Src = N.getOperand(0);
7248     SDValue Sub = N.getOperand(1);
7249     EVT SubVT = Sub.getValueType();
7250     unsigned NumSubElts = SubVT.getVectorNumElements();
7251     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
7252         !N->isOnlyUserOf(Sub.getNode()))
7253       return false;
7254     uint64_t InsertIdx = N.getConstantOperandVal(2);
7255     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
7256     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7257         Sub.getOperand(0).getValueType() == VT &&
7258         isa<ConstantSDNode>(Sub.getOperand(1))) {
7259       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
7260       for (int i = 0; i != (int)NumElts; ++i)
7261         Mask.push_back(i);
7262       for (int i = 0; i != (int)NumSubElts; ++i)
7263         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
7264       Ops.push_back(Src);
7265       Ops.push_back(Sub.getOperand(0));
7266       return true;
7267     }
7268     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
7269     SmallVector<int, 64> SubMask;
7270     SmallVector<SDValue, 2> SubInputs;
7271     if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
7272                                 SubMask, DAG, Depth + 1, ResolveKnownElts))
7273       return false;
7274     if (SubMask.size() != NumSubElts) {
7275       assert(((SubMask.size() % NumSubElts) == 0 ||
7276               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
7277       if ((NumSubElts % SubMask.size()) == 0) {
7278         int Scale = NumSubElts / SubMask.size();
7279         SmallVector<int,64> ScaledSubMask;
7280         scaleShuffleMask<int>(Scale, SubMask, ScaledSubMask);
7281         SubMask = ScaledSubMask;
7282       } else {
7283         int Scale = SubMask.size() / NumSubElts;
7284         NumSubElts = SubMask.size();
7285         NumElts *= Scale;
7286         InsertIdx *= Scale;
7287       }
7288     }
7289     Ops.push_back(Src);
7290     for (SDValue &SubInput : SubInputs) {
7291       EVT SubSVT = SubInput.getValueType().getScalarType();
7292       EVT AltVT = EVT::getVectorVT(*DAG.getContext(), SubSVT,
7293                                    NumSizeInBits / SubSVT.getSizeInBits());
7294       Ops.push_back(DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), AltVT,
7295                                 DAG.getUNDEF(AltVT), SubInput,
7296                                 DAG.getIntPtrConstant(0, SDLoc(N))));
7297     }
7298     for (int i = 0; i != (int)NumElts; ++i)
7299       Mask.push_back(i);
7300     for (int i = 0; i != (int)NumSubElts; ++i) {
7301       int M = SubMask[i];
7302       if (0 <= M) {
7303         int InputIdx = M / NumSubElts;
7304         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
7305       }
7306       Mask[i + InsertIdx] = M;
7307     }
7308     return true;
7309   }
7310   case ISD::SCALAR_TO_VECTOR: {
7311     // Match against a scalar_to_vector of an extract from a vector,
7312     // for PEXTRW/PEXTRB we must handle the implicit zext of the scalar.
7313     SDValue N0 = N.getOperand(0);
7314     SDValue SrcExtract;
7315 
7316     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7317          N0.getOperand(0).getValueType() == VT) ||
7318         (N0.getOpcode() == X86ISD::PEXTRW &&
7319          N0.getOperand(0).getValueType() == MVT::v8i16) ||
7320         (N0.getOpcode() == X86ISD::PEXTRB &&
7321          N0.getOperand(0).getValueType() == MVT::v16i8)) {
7322       SrcExtract = N0;
7323     }
7324 
7325     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
7326       return false;
7327 
7328     SDValue SrcVec = SrcExtract.getOperand(0);
7329     EVT SrcVT = SrcVec.getValueType();
7330     unsigned NumSrcElts = SrcVT.getVectorNumElements();
7331     unsigned NumZeros = (NumBitsPerElt / SrcVT.getScalarSizeInBits()) - 1;
7332 
7333     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
7334     if (NumSrcElts <= SrcIdx)
7335       return false;
7336 
7337     Ops.push_back(SrcVec);
7338     Mask.push_back(SrcIdx);
7339     Mask.append(NumZeros, SM_SentinelZero);
7340     Mask.append(NumSrcElts - Mask.size(), SM_SentinelUndef);
7341     return true;
7342   }
7343   case X86ISD::PINSRB:
7344   case X86ISD::PINSRW: {
7345     SDValue InVec = N.getOperand(0);
7346     SDValue InScl = N.getOperand(1);
7347     SDValue InIndex = N.getOperand(2);
7348     if (!isa<ConstantSDNode>(InIndex) ||
7349         cast<ConstantSDNode>(InIndex)->getAPIntValue().uge(NumElts))
7350       return false;
7351     uint64_t InIdx = N.getConstantOperandVal(2);
7352 
7353     // Attempt to recognise a PINSR*(VEC, 0, Idx) shuffle pattern.
7354     if (X86::isZeroNode(InScl)) {
7355       Ops.push_back(InVec);
7356       for (unsigned i = 0; i != NumElts; ++i)
7357         Mask.push_back(i == InIdx ? SM_SentinelZero : (int)i);
7358       return true;
7359     }
7360 
7361     // Attempt to recognise a PINSR*(PEXTR*) shuffle pattern.
7362     // TODO: Expand this to support INSERT_VECTOR_ELT/etc.
7363     unsigned ExOp =
7364         (X86ISD::PINSRB == Opcode ? X86ISD::PEXTRB : X86ISD::PEXTRW);
7365     if (InScl.getOpcode() != ExOp)
7366       return false;
7367 
7368     SDValue ExVec = InScl.getOperand(0);
7369     SDValue ExIndex = InScl.getOperand(1);
7370     if (!isa<ConstantSDNode>(ExIndex) ||
7371         cast<ConstantSDNode>(ExIndex)->getAPIntValue().uge(NumElts))
7372       return false;
7373     uint64_t ExIdx = InScl.getConstantOperandVal(1);
7374 
7375     Ops.push_back(InVec);
7376     Ops.push_back(ExVec);
7377     for (unsigned i = 0; i != NumElts; ++i)
7378       Mask.push_back(i == InIdx ? NumElts + ExIdx : i);
7379     return true;
7380   }
7381   case X86ISD::PACKSS:
7382   case X86ISD::PACKUS: {
7383     SDValue N0 = N.getOperand(0);
7384     SDValue N1 = N.getOperand(1);
7385     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
7386            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
7387            "Unexpected input value type");
7388 
7389     APInt EltsLHS, EltsRHS;
7390     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
7391 
7392     // If we know input saturation won't happen we can treat this
7393     // as a truncation shuffle.
7394     if (Opcode == X86ISD::PACKSS) {
7395       if ((!N0.isUndef() &&
7396            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
7397           (!N1.isUndef() &&
7398            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
7399         return false;
7400     } else {
7401       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
7402       if ((!N0.isUndef() &&
7403            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
7404           (!N1.isUndef() &&
7405            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
7406         return false;
7407     }
7408 
7409     bool IsUnary = (N0 == N1);
7410 
7411     Ops.push_back(N0);
7412     if (!IsUnary)
7413       Ops.push_back(N1);
7414 
7415     createPackShuffleMask(VT, Mask, IsUnary);
7416     return true;
7417   }
7418   case X86ISD::VSHLI:
7419   case X86ISD::VSRLI: {
7420     uint64_t ShiftVal = N.getConstantOperandVal(1);
7421     // Out of range bit shifts are guaranteed to be zero.
7422     if (NumBitsPerElt <= ShiftVal) {
7423       Mask.append(NumElts, SM_SentinelZero);
7424       return true;
7425     }
7426 
7427     // We can only decode 'whole byte' bit shifts as shuffles.
7428     if ((ShiftVal % 8) != 0)
7429       break;
7430 
7431     uint64_t ByteShift = ShiftVal / 8;
7432     unsigned NumBytes = NumSizeInBits / 8;
7433     unsigned NumBytesPerElt = NumBitsPerElt / 8;
7434     Ops.push_back(N.getOperand(0));
7435 
7436     // Clear mask to all zeros and insert the shifted byte indices.
7437     Mask.append(NumBytes, SM_SentinelZero);
7438 
7439     if (X86ISD::VSHLI == Opcode) {
7440       for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
7441         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7442           Mask[i + j] = i + j - ByteShift;
7443     } else {
7444       for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
7445         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7446           Mask[i + j - ByteShift] = i + j;
7447     }
7448     return true;
7449   }
7450   case X86ISD::VBROADCAST: {
7451     SDValue Src = N.getOperand(0);
7452     MVT SrcVT = Src.getSimpleValueType();
7453     if (!SrcVT.isVector())
7454       return false;
7455 
7456     if (NumSizeInBits != SrcVT.getSizeInBits()) {
7457       assert((NumSizeInBits % SrcVT.getSizeInBits()) == 0 &&
7458              "Illegal broadcast type");
7459       SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
7460                                NumSizeInBits / SrcVT.getScalarSizeInBits());
7461       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), SrcVT,
7462                         DAG.getUNDEF(SrcVT), Src,
7463                         DAG.getIntPtrConstant(0, SDLoc(N)));
7464     }
7465 
7466     Ops.push_back(Src);
7467     Mask.append(NumElts, 0);
7468     return true;
7469   }
7470   case ISD::ZERO_EXTEND:
7471   case ISD::ANY_EXTEND:
7472   case ISD::ZERO_EXTEND_VECTOR_INREG:
7473   case ISD::ANY_EXTEND_VECTOR_INREG: {
7474     SDValue Src = N.getOperand(0);
7475     EVT SrcVT = Src.getValueType();
7476 
7477     // Extended source must be a simple vector.
7478     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7479         (SrcVT.getScalarSizeInBits() % 8) != 0)
7480       return false;
7481 
7482     unsigned NumSrcBitsPerElt = SrcVT.getScalarSizeInBits();
7483     bool IsAnyExtend =
7484         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7485     DecodeZeroExtendMask(NumSrcBitsPerElt, NumBitsPerElt, NumElts, IsAnyExtend,
7486                          Mask);
7487 
7488     if (NumSizeInBits != SrcVT.getSizeInBits()) {
7489       assert((NumSizeInBits % SrcVT.getSizeInBits()) == 0 &&
7490              "Illegal zero-extension type");
7491       SrcVT = MVT::getVectorVT(SrcVT.getSimpleVT().getScalarType(),
7492                                NumSizeInBits / NumSrcBitsPerElt);
7493       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), SrcVT,
7494                         DAG.getUNDEF(SrcVT), Src,
7495                         DAG.getIntPtrConstant(0, SDLoc(N)));
7496     }
7497 
7498     Ops.push_back(Src);
7499     return true;
7500   }
7501   }
7502 
7503   return false;
7504 }
7505 
7506 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask)7507 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
7508                                               SmallVectorImpl<int> &Mask) {
7509   int MaskWidth = Mask.size();
7510   SmallVector<SDValue, 16> UsedInputs;
7511   for (int i = 0, e = Inputs.size(); i < e; ++i) {
7512     int lo = UsedInputs.size() * MaskWidth;
7513     int hi = lo + MaskWidth;
7514 
7515     // Strip UNDEF input usage.
7516     if (Inputs[i].isUndef())
7517       for (int &M : Mask)
7518         if ((lo <= M) && (M < hi))
7519           M = SM_SentinelUndef;
7520 
7521     // Check for unused inputs.
7522     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7523       for (int &M : Mask)
7524         if (lo <= M)
7525           M -= MaskWidth;
7526       continue;
7527     }
7528 
7529     // Check for repeated inputs.
7530     bool IsRepeat = false;
7531     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7532       if (UsedInputs[j] != Inputs[i])
7533         continue;
7534       for (int &M : Mask)
7535         if (lo <= M)
7536           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7537       IsRepeat = true;
7538       break;
7539     }
7540     if (IsRepeat)
7541       continue;
7542 
7543     UsedInputs.push_back(Inputs[i]);
7544   }
7545   Inputs = UsedInputs;
7546 }
7547 
7548 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7549 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7550 /// Returns true if the target shuffle mask was decoded.
getTargetShuffleInputs(SDValue Op,const APInt & DemandedElts,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,APInt & KnownUndef,APInt & KnownZero,SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)7551 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7552                                    SmallVectorImpl<SDValue> &Inputs,
7553                                    SmallVectorImpl<int> &Mask,
7554                                    APInt &KnownUndef, APInt &KnownZero,
7555                                    SelectionDAG &DAG, unsigned Depth,
7556                                    bool ResolveKnownElts) {
7557   EVT VT = Op.getValueType();
7558   if (!VT.isSimple() || !VT.isVector())
7559     return false;
7560 
7561   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7562     if (ResolveKnownElts)
7563       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7564     return true;
7565   }
7566   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7567                          ResolveKnownElts)) {
7568     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7569     return true;
7570   }
7571   return false;
7572 }
7573 
getTargetShuffleInputs(SDValue Op,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,SelectionDAG & DAG,unsigned Depth=0,bool ResolveKnownElts=true)7574 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7575                                    SmallVectorImpl<int> &Mask,
7576                                    SelectionDAG &DAG, unsigned Depth = 0,
7577                                    bool ResolveKnownElts = true) {
7578   EVT VT = Op.getValueType();
7579   if (!VT.isSimple() || !VT.isVector())
7580     return false;
7581 
7582   APInt KnownUndef, KnownZero;
7583   unsigned NumElts = Op.getValueType().getVectorNumElements();
7584   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
7585   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7586                                 KnownZero, DAG, Depth, ResolveKnownElts);
7587 }
7588 
7589 /// Returns the scalar element that will make up the ith
7590 /// element of the result of the vector shuffle.
getShuffleScalarElt(SDNode * N,unsigned Index,SelectionDAG & DAG,unsigned Depth)7591 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
7592                                    unsigned Depth) {
7593   if (Depth == 6)
7594     return SDValue();  // Limit search depth.
7595 
7596   SDValue V = SDValue(N, 0);
7597   EVT VT = V.getValueType();
7598   unsigned Opcode = V.getOpcode();
7599 
7600   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7601   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
7602     int Elt = SV->getMaskElt(Index);
7603 
7604     if (Elt < 0)
7605       return DAG.getUNDEF(VT.getVectorElementType());
7606 
7607     unsigned NumElems = VT.getVectorNumElements();
7608     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
7609                                          : SV->getOperand(1);
7610     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
7611   }
7612 
7613   // Recurse into target specific vector shuffles to find scalars.
7614   if (isTargetShuffle(Opcode)) {
7615     MVT ShufVT = V.getSimpleValueType();
7616     MVT ShufSVT = ShufVT.getVectorElementType();
7617     int NumElems = (int)ShufVT.getVectorNumElements();
7618     SmallVector<int, 16> ShuffleMask;
7619     SmallVector<SDValue, 16> ShuffleOps;
7620     bool IsUnary;
7621 
7622     if (!getTargetShuffleMask(N, ShufVT, true, ShuffleOps, ShuffleMask, IsUnary))
7623       return SDValue();
7624 
7625     int Elt = ShuffleMask[Index];
7626     if (Elt == SM_SentinelZero)
7627       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(N), ShufSVT)
7628                                  : DAG.getConstantFP(+0.0, SDLoc(N), ShufSVT);
7629     if (Elt == SM_SentinelUndef)
7630       return DAG.getUNDEF(ShufSVT);
7631 
7632     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
7633     SDValue NewV = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7634     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
7635                                Depth+1);
7636   }
7637 
7638   // Recurse into insert_subvector base/sub vector to find scalars.
7639   if (Opcode == ISD::INSERT_SUBVECTOR &&
7640       isa<ConstantSDNode>(N->getOperand(2))) {
7641     SDValue Vec = N->getOperand(0);
7642     SDValue Sub = N->getOperand(1);
7643     EVT SubVT = Sub.getValueType();
7644     unsigned NumSubElts = SubVT.getVectorNumElements();
7645     uint64_t SubIdx = N->getConstantOperandVal(2);
7646 
7647     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7648       return getShuffleScalarElt(Sub.getNode(), Index - SubIdx, DAG, Depth + 1);
7649     return getShuffleScalarElt(Vec.getNode(), Index, DAG, Depth + 1);
7650   }
7651 
7652   // Recurse into extract_subvector src vector to find scalars.
7653   if (Opcode == ISD::EXTRACT_SUBVECTOR &&
7654       isa<ConstantSDNode>(N->getOperand(1))) {
7655     SDValue Src = N->getOperand(0);
7656     uint64_t SrcIdx = N->getConstantOperandVal(1);
7657     return getShuffleScalarElt(Src.getNode(), Index + SrcIdx, DAG, Depth + 1);
7658   }
7659 
7660   // Actual nodes that may contain scalar elements
7661   if (Opcode == ISD::BITCAST) {
7662     V = V.getOperand(0);
7663     EVT SrcVT = V.getValueType();
7664     unsigned NumElems = VT.getVectorNumElements();
7665 
7666     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
7667       return SDValue();
7668   }
7669 
7670   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7671     return (Index == 0) ? V.getOperand(0)
7672                         : DAG.getUNDEF(VT.getVectorElementType());
7673 
7674   if (V.getOpcode() == ISD::BUILD_VECTOR)
7675     return V.getOperand(Index);
7676 
7677   return SDValue();
7678 }
7679 
7680 // Use PINSRB/PINSRW/PINSRD to create a build vector.
LowerBuildVectorAsInsert(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)7681 static SDValue LowerBuildVectorAsInsert(SDValue Op, unsigned NonZeros,
7682                                         unsigned NumNonZero, unsigned NumZero,
7683                                         SelectionDAG &DAG,
7684                                         const X86Subtarget &Subtarget) {
7685   MVT VT = Op.getSimpleValueType();
7686   unsigned NumElts = VT.getVectorNumElements();
7687   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7688           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7689          "Illegal vector insertion");
7690 
7691   SDLoc dl(Op);
7692   SDValue V;
7693   bool First = true;
7694 
7695   for (unsigned i = 0; i < NumElts; ++i) {
7696     bool IsNonZero = (NonZeros & (1 << i)) != 0;
7697     if (!IsNonZero)
7698       continue;
7699 
7700     // If the build vector contains zeros or our first insertion is not the
7701     // first index then insert into zero vector to break any register
7702     // dependency else use SCALAR_TO_VECTOR.
7703     if (First) {
7704       First = false;
7705       if (NumZero || 0 != i)
7706         V = getZeroVector(VT, Subtarget, DAG, dl);
7707       else {
7708         assert(0 == i && "Expected insertion into zero-index");
7709         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7710         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
7711         V = DAG.getBitcast(VT, V);
7712         continue;
7713       }
7714     }
7715     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
7716                     DAG.getIntPtrConstant(i, dl));
7717   }
7718 
7719   return V;
7720 }
7721 
7722 /// Custom lower build_vector of v16i8.
LowerBuildVectorv16i8(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)7723 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
7724                                      unsigned NumNonZero, unsigned NumZero,
7725                                      SelectionDAG &DAG,
7726                                      const X86Subtarget &Subtarget) {
7727   if (NumNonZero > 8 && !Subtarget.hasSSE41())
7728     return SDValue();
7729 
7730   // SSE4.1 - use PINSRB to insert each byte directly.
7731   if (Subtarget.hasSSE41())
7732     return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
7733                                     Subtarget);
7734 
7735   SDLoc dl(Op);
7736   SDValue V;
7737 
7738   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7739   for (unsigned i = 0; i < 16; i += 2) {
7740     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
7741     bool NextIsNonZero = (NonZeros & (1 << (i + 1))) != 0;
7742     if (!ThisIsNonZero && !NextIsNonZero)
7743       continue;
7744 
7745     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
7746     SDValue Elt;
7747     if (ThisIsNonZero) {
7748       if (NumZero || NextIsNonZero)
7749         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7750       else
7751         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7752     }
7753 
7754     if (NextIsNonZero) {
7755       SDValue NextElt = Op.getOperand(i + 1);
7756       if (i == 0 && NumZero)
7757         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
7758       else
7759         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
7760       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
7761                             DAG.getConstant(8, dl, MVT::i8));
7762       if (ThisIsNonZero)
7763         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
7764       else
7765         Elt = NextElt;
7766     }
7767 
7768     // If our first insertion is not the first index then insert into zero
7769     // vector to break any register dependency else use SCALAR_TO_VECTOR.
7770     if (!V) {
7771       if (i != 0)
7772         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
7773       else {
7774         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
7775         V = DAG.getBitcast(MVT::v8i16, V);
7776         continue;
7777       }
7778     }
7779     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
7780     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
7781                     DAG.getIntPtrConstant(i / 2, dl));
7782   }
7783 
7784   return DAG.getBitcast(MVT::v16i8, V);
7785 }
7786 
7787 /// Custom lower build_vector of v8i16.
LowerBuildVectorv8i16(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)7788 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
7789                                      unsigned NumNonZero, unsigned NumZero,
7790                                      SelectionDAG &DAG,
7791                                      const X86Subtarget &Subtarget) {
7792   if (NumNonZero > 4 && !Subtarget.hasSSE41())
7793     return SDValue();
7794 
7795   // Use PINSRW to insert each byte directly.
7796   return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
7797                                   Subtarget);
7798 }
7799 
7800 /// Custom lower build_vector of v4i32 or v4f32.
LowerBuildVectorv4x32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)7801 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
7802                                      const X86Subtarget &Subtarget) {
7803   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
7804   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
7805   // Because we're creating a less complicated build vector here, we may enable
7806   // further folding of the MOVDDUP via shuffle transforms.
7807   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
7808       Op.getOperand(0) == Op.getOperand(2) &&
7809       Op.getOperand(1) == Op.getOperand(3) &&
7810       Op.getOperand(0) != Op.getOperand(1)) {
7811     SDLoc DL(Op);
7812     MVT VT = Op.getSimpleValueType();
7813     MVT EltVT = VT.getVectorElementType();
7814     // Create a new build vector with the first 2 elements followed by undef
7815     // padding, bitcast to v2f64, duplicate, and bitcast back.
7816     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
7817                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
7818     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7819     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7820     return DAG.getBitcast(VT, Dup);
7821   }
7822 
7823   // Find all zeroable elements.
7824   std::bitset<4> Zeroable, Undefs;
7825   for (int i = 0; i < 4; ++i) {
7826     SDValue Elt = Op.getOperand(i);
7827     Undefs[i] = Elt.isUndef();
7828     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7829   }
7830   assert(Zeroable.size() - Zeroable.count() > 1 &&
7831          "We expect at least two non-zero elements!");
7832 
7833   // We only know how to deal with build_vector nodes where elements are either
7834   // zeroable or extract_vector_elt with constant index.
7835   SDValue FirstNonZero;
7836   unsigned FirstNonZeroIdx;
7837   for (unsigned i = 0; i < 4; ++i) {
7838     if (Zeroable[i])
7839       continue;
7840     SDValue Elt = Op.getOperand(i);
7841     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7842         !isa<ConstantSDNode>(Elt.getOperand(1)))
7843       return SDValue();
7844     // Make sure that this node is extracting from a 128-bit vector.
7845     MVT VT = Elt.getOperand(0).getSimpleValueType();
7846     if (!VT.is128BitVector())
7847       return SDValue();
7848     if (!FirstNonZero.getNode()) {
7849       FirstNonZero = Elt;
7850       FirstNonZeroIdx = i;
7851     }
7852   }
7853 
7854   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
7855   SDValue V1 = FirstNonZero.getOperand(0);
7856   MVT VT = V1.getSimpleValueType();
7857 
7858   // See if this build_vector can be lowered as a blend with zero.
7859   SDValue Elt;
7860   unsigned EltMaskIdx, EltIdx;
7861   int Mask[4];
7862   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7863     if (Zeroable[EltIdx]) {
7864       // The zero vector will be on the right hand side.
7865       Mask[EltIdx] = EltIdx+4;
7866       continue;
7867     }
7868 
7869     Elt = Op->getOperand(EltIdx);
7870     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7871     EltMaskIdx = Elt.getConstantOperandVal(1);
7872     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7873       break;
7874     Mask[EltIdx] = EltIdx;
7875   }
7876 
7877   if (EltIdx == 4) {
7878     // Let the shuffle legalizer deal with blend operations.
7879     SDValue VZeroOrUndef = (Zeroable == Undefs)
7880                                ? DAG.getUNDEF(VT)
7881                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
7882     if (V1.getSimpleValueType() != VT)
7883       V1 = DAG.getBitcast(VT, V1);
7884     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
7885   }
7886 
7887   // See if we can lower this build_vector to a INSERTPS.
7888   if (!Subtarget.hasSSE41())
7889     return SDValue();
7890 
7891   SDValue V2 = Elt.getOperand(0);
7892   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7893     V1 = SDValue();
7894 
7895   bool CanFold = true;
7896   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7897     if (Zeroable[i])
7898       continue;
7899 
7900     SDValue Current = Op->getOperand(i);
7901     SDValue SrcVector = Current->getOperand(0);
7902     if (!V1.getNode())
7903       V1 = SrcVector;
7904     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
7905   }
7906 
7907   if (!CanFold)
7908     return SDValue();
7909 
7910   assert(V1.getNode() && "Expected at least two non-zero elements!");
7911   if (V1.getSimpleValueType() != MVT::v4f32)
7912     V1 = DAG.getBitcast(MVT::v4f32, V1);
7913   if (V2.getSimpleValueType() != MVT::v4f32)
7914     V2 = DAG.getBitcast(MVT::v4f32, V2);
7915 
7916   // Ok, we can emit an INSERTPS instruction.
7917   unsigned ZMask = Zeroable.to_ulong();
7918 
7919   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7920   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7921   SDLoc DL(Op);
7922   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7923                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
7924   return DAG.getBitcast(VT, Result);
7925 }
7926 
7927 /// Return a vector logical shift node.
getVShift(bool isLeft,EVT VT,SDValue SrcOp,unsigned NumBits,SelectionDAG & DAG,const TargetLowering & TLI,const SDLoc & dl)7928 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7929                          SelectionDAG &DAG, const TargetLowering &TLI,
7930                          const SDLoc &dl) {
7931   assert(VT.is128BitVector() && "Unknown type for VShift");
7932   MVT ShVT = MVT::v16i8;
7933   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7934   SrcOp = DAG.getBitcast(ShVT, SrcOp);
7935   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
7936   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
7937   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7938 }
7939 
LowerAsSplatVectorLoad(SDValue SrcOp,MVT VT,const SDLoc & dl,SelectionDAG & DAG)7940 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
7941                                       SelectionDAG &DAG) {
7942 
7943   // Check if the scalar load can be widened into a vector load. And if
7944   // the address is "base + cst" see if the cst can be "absorbed" into
7945   // the shuffle mask.
7946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
7947     SDValue Ptr = LD->getBasePtr();
7948     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
7949       return SDValue();
7950     EVT PVT = LD->getValueType(0);
7951     if (PVT != MVT::i32 && PVT != MVT::f32)
7952       return SDValue();
7953 
7954     int FI = -1;
7955     int64_t Offset = 0;
7956     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7957       FI = FINode->getIndex();
7958       Offset = 0;
7959     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7960                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7961       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7962       Offset = Ptr.getConstantOperandVal(1);
7963       Ptr = Ptr.getOperand(0);
7964     } else {
7965       return SDValue();
7966     }
7967 
7968     // FIXME: 256-bit vector instructions don't require a strict alignment,
7969     // improve this code to support it better.
7970     unsigned RequiredAlign = VT.getSizeInBits()/8;
7971     SDValue Chain = LD->getChain();
7972     // Make sure the stack object alignment is at least 16 or 32.
7973     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7974     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
7975       if (MFI.isFixedObjectIndex(FI)) {
7976         // Can't change the alignment. FIXME: It's possible to compute
7977         // the exact stack offset and reference FI + adjust offset instead.
7978         // If someone *really* cares about this. That's the way to implement it.
7979         return SDValue();
7980       } else {
7981         MFI.setObjectAlignment(FI, RequiredAlign);
7982       }
7983     }
7984 
7985     // (Offset % 16 or 32) must be multiple of 4. Then address is then
7986     // Ptr + (Offset & ~15).
7987     if (Offset < 0)
7988       return SDValue();
7989     if ((Offset % RequiredAlign) & 3)
7990       return SDValue();
7991     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
7992     if (StartOffset) {
7993       SDLoc DL(Ptr);
7994       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7995                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7996     }
7997 
7998     int EltNo = (Offset - StartOffset) >> 2;
7999     unsigned NumElems = VT.getVectorNumElements();
8000 
8001     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
8002     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
8003                              LD->getPointerInfo().getWithOffset(StartOffset));
8004 
8005     SmallVector<int, 8> Mask(NumElems, EltNo);
8006 
8007     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
8008   }
8009 
8010   return SDValue();
8011 }
8012 
8013 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
findEltLoadSrc(SDValue Elt,LoadSDNode * & Ld,int64_t & ByteOffset)8014 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
8015   if (ISD::isNON_EXTLoad(Elt.getNode())) {
8016     auto *BaseLd = cast<LoadSDNode>(Elt);
8017     if (!BaseLd->isSimple())
8018       return false;
8019     Ld = BaseLd;
8020     ByteOffset = 0;
8021     return true;
8022   }
8023 
8024   switch (Elt.getOpcode()) {
8025   case ISD::BITCAST:
8026   case ISD::TRUNCATE:
8027   case ISD::SCALAR_TO_VECTOR:
8028     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
8029   case ISD::SRL:
8030     if (isa<ConstantSDNode>(Elt.getOperand(1))) {
8031       uint64_t Idx = Elt.getConstantOperandVal(1);
8032       if ((Idx % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
8033         ByteOffset += Idx / 8;
8034         return true;
8035       }
8036     }
8037     break;
8038   case ISD::EXTRACT_VECTOR_ELT:
8039     if (isa<ConstantSDNode>(Elt.getOperand(1))) {
8040       SDValue Src = Elt.getOperand(0);
8041       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
8042       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
8043       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
8044           findEltLoadSrc(Src, Ld, ByteOffset)) {
8045         uint64_t Idx = Elt.getConstantOperandVal(1);
8046         ByteOffset += Idx * (SrcSizeInBits / 8);
8047         return true;
8048       }
8049     }
8050     break;
8051   }
8052 
8053   return false;
8054 }
8055 
8056 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
8057 /// elements can be replaced by a single large load which has the same value as
8058 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
8059 ///
8060 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
EltsFromConsecutiveLoads(EVT VT,ArrayRef<SDValue> Elts,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool isAfterLegalize)8061 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
8062                                         const SDLoc &DL, SelectionDAG &DAG,
8063                                         const X86Subtarget &Subtarget,
8064                                         bool isAfterLegalize) {
8065   if ((VT.getScalarSizeInBits() % 8) != 0)
8066     return SDValue();
8067 
8068   unsigned NumElems = Elts.size();
8069 
8070   int LastLoadedElt = -1;
8071   APInt LoadMask = APInt::getNullValue(NumElems);
8072   APInt ZeroMask = APInt::getNullValue(NumElems);
8073   APInt UndefMask = APInt::getNullValue(NumElems);
8074 
8075   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
8076   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
8077 
8078   // For each element in the initializer, see if we've found a load, zero or an
8079   // undef.
8080   for (unsigned i = 0; i < NumElems; ++i) {
8081     SDValue Elt = peekThroughBitcasts(Elts[i]);
8082     if (!Elt.getNode())
8083       return SDValue();
8084     if (Elt.isUndef()) {
8085       UndefMask.setBit(i);
8086       continue;
8087     }
8088     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
8089       ZeroMask.setBit(i);
8090       continue;
8091     }
8092 
8093     // Each loaded element must be the correct fractional portion of the
8094     // requested vector load.
8095     unsigned EltSizeInBits = Elt.getValueSizeInBits();
8096     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
8097       return SDValue();
8098 
8099     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
8100       return SDValue();
8101     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
8102     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
8103       return SDValue();
8104 
8105     LoadMask.setBit(i);
8106     LastLoadedElt = i;
8107   }
8108   assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +
8109           LoadMask.countPopulation()) == NumElems &&
8110          "Incomplete element masks");
8111 
8112   // Handle Special Cases - all undef or undef/zero.
8113   if (UndefMask.countPopulation() == NumElems)
8114     return DAG.getUNDEF(VT);
8115 
8116   // FIXME: Should we return this as a BUILD_VECTOR instead?
8117   if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
8118     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
8119                           : DAG.getConstantFP(0.0, DL, VT);
8120 
8121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8122   int FirstLoadedElt = LoadMask.countTrailingZeros();
8123   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
8124   EVT EltBaseVT = EltBase.getValueType();
8125   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
8126          "Register/Memory size mismatch");
8127   LoadSDNode *LDBase = Loads[FirstLoadedElt];
8128   assert(LDBase && "Did not find base load for merging consecutive loads");
8129   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
8130   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
8131   int LoadSizeInBits = (1 + LastLoadedElt - FirstLoadedElt) * BaseSizeInBits;
8132   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
8133 
8134   // TODO: Support offsetting the base load.
8135   if (ByteOffsets[FirstLoadedElt] != 0)
8136     return SDValue();
8137 
8138   // Check to see if the element's load is consecutive to the base load
8139   // or offset from a previous (already checked) load.
8140   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
8141     LoadSDNode *Ld = Loads[EltIdx];
8142     int64_t ByteOffset = ByteOffsets[EltIdx];
8143     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
8144       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
8145       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
8146               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
8147     }
8148     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
8149                                               EltIdx - FirstLoadedElt);
8150   };
8151 
8152   // Consecutive loads can contain UNDEFS but not ZERO elements.
8153   // Consecutive loads with UNDEFs and ZEROs elements require a
8154   // an additional shuffle stage to clear the ZERO elements.
8155   bool IsConsecutiveLoad = true;
8156   bool IsConsecutiveLoadWithZeros = true;
8157   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
8158     if (LoadMask[i]) {
8159       if (!CheckConsecutiveLoad(LDBase, i)) {
8160         IsConsecutiveLoad = false;
8161         IsConsecutiveLoadWithZeros = false;
8162         break;
8163       }
8164     } else if (ZeroMask[i]) {
8165       IsConsecutiveLoad = false;
8166     }
8167   }
8168 
8169   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
8170     auto MMOFlags = LDBase->getMemOperand()->getFlags();
8171     assert(LDBase->isSimple() &&
8172            "Cannot merge volatile or atomic loads.");
8173     SDValue NewLd =
8174         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
8175                     LDBase->getPointerInfo(), LDBase->getAlignment(), MMOFlags);
8176     for (auto *LD : Loads)
8177       if (LD)
8178         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
8179     return NewLd;
8180   };
8181 
8182   // Check if the base load is entirely dereferenceable.
8183   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
8184       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
8185 
8186   // LOAD - all consecutive load/undefs (must start/end with a load or be
8187   // entirely dereferenceable). If we have found an entire vector of loads and
8188   // undefs, then return a large load of the entire vector width starting at the
8189   // base pointer. If the vector contains zeros, then attempt to shuffle those
8190   // elements.
8191   if (FirstLoadedElt == 0 &&
8192       (LastLoadedElt == (int)(NumElems - 1) || IsDereferenceable) &&
8193       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8194     if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8195       return SDValue();
8196 
8197     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8198     // will lower to regular temporal loads and use the cache.
8199     if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
8200         VT.is256BitVector() && !Subtarget.hasInt256())
8201       return SDValue();
8202 
8203     if (NumElems == 1)
8204       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8205 
8206     if (!ZeroMask)
8207       return CreateLoad(VT, LDBase);
8208 
8209     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8210     // vector and a zero vector to clear out the zero elements.
8211     if (!isAfterLegalize && VT.isVector()) {
8212       unsigned NumMaskElts = VT.getVectorNumElements();
8213       if ((NumMaskElts % NumElems) == 0) {
8214         unsigned Scale = NumMaskElts / NumElems;
8215         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8216         for (unsigned i = 0; i < NumElems; ++i) {
8217           if (UndefMask[i])
8218             continue;
8219           int Offset = ZeroMask[i] ? NumMaskElts : 0;
8220           for (unsigned j = 0; j != Scale; ++j)
8221             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8222         }
8223         SDValue V = CreateLoad(VT, LDBase);
8224         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8225                                    : DAG.getConstantFP(0.0, DL, VT);
8226         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8227       }
8228     }
8229   }
8230 
8231   // If the upper half of a ymm/zmm load is undef then just load the lower half.
8232   if (VT.is256BitVector() || VT.is512BitVector()) {
8233     unsigned HalfNumElems = NumElems / 2;
8234     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnesValue()) {
8235       EVT HalfVT =
8236           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8237       SDValue HalfLD =
8238           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8239                                    DAG, Subtarget, isAfterLegalize);
8240       if (HalfLD)
8241         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8242                            HalfLD, DAG.getIntPtrConstant(0, DL));
8243     }
8244   }
8245 
8246   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8247   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8248       (LoadSizeInBits == 32 || LoadSizeInBits == 64) &&
8249       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8250     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8251                                       : MVT::getIntegerVT(LoadSizeInBits);
8252     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8253     if (TLI.isTypeLegal(VecVT)) {
8254       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8255       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8256       SDValue ResNode =
8257           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT,
8258                                   LDBase->getPointerInfo(),
8259                                   LDBase->getAlignment(),
8260                                   MachineMemOperand::MOLoad);
8261       for (auto *LD : Loads)
8262         if (LD)
8263           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8264       return DAG.getBitcast(VT, ResNode);
8265     }
8266   }
8267 
8268   // BROADCAST - match the smallest possible repetition pattern, load that
8269   // scalar/subvector element and then broadcast to the entire vector.
8270   if (ZeroMask.isNullValue() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8271       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8272     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8273       unsigned RepeatSize = SubElems * BaseSizeInBits;
8274       unsigned ScalarSize = std::min(RepeatSize, 64u);
8275       if (!Subtarget.hasAVX2() && ScalarSize < 32)
8276         continue;
8277 
8278       bool Match = true;
8279       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8280       for (unsigned i = 0; i != NumElems && Match; ++i) {
8281         if (!LoadMask[i])
8282           continue;
8283         SDValue Elt = peekThroughBitcasts(Elts[i]);
8284         if (RepeatedLoads[i % SubElems].isUndef())
8285           RepeatedLoads[i % SubElems] = Elt;
8286         else
8287           Match &= (RepeatedLoads[i % SubElems] == Elt);
8288       }
8289 
8290       // We must have loads at both ends of the repetition.
8291       Match &= !RepeatedLoads.front().isUndef();
8292       Match &= !RepeatedLoads.back().isUndef();
8293       if (!Match)
8294         continue;
8295 
8296       EVT RepeatVT =
8297           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8298               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8299               : EVT::getFloatingPointVT(ScalarSize);
8300       if (RepeatSize > ScalarSize)
8301         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8302                                     RepeatSize / ScalarSize);
8303       EVT BroadcastVT =
8304           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8305                            VT.getSizeInBits() / ScalarSize);
8306       if (TLI.isTypeLegal(BroadcastVT)) {
8307         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8308                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, isAfterLegalize)) {
8309           unsigned Opcode = RepeatSize > ScalarSize ? X86ISD::SUBV_BROADCAST
8310                                                     : X86ISD::VBROADCAST;
8311           SDValue Broadcast = DAG.getNode(Opcode, DL, BroadcastVT, RepeatLoad);
8312           return DAG.getBitcast(VT, Broadcast);
8313         }
8314       }
8315     }
8316   }
8317 
8318   return SDValue();
8319 }
8320 
8321 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8322 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8323 // are consecutive, non-overlapping, and in the right order.
combineToConsecutiveLoads(EVT VT,SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool isAfterLegalize)8324 static SDValue combineToConsecutiveLoads(EVT VT, SDNode *N, const SDLoc &DL,
8325                                          SelectionDAG &DAG,
8326                                          const X86Subtarget &Subtarget,
8327                                          bool isAfterLegalize) {
8328   SmallVector<SDValue, 64> Elts;
8329   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8330     if (SDValue Elt = getShuffleScalarElt(N, i, DAG, 0)) {
8331       Elts.push_back(Elt);
8332       continue;
8333     }
8334     return SDValue();
8335   }
8336   assert(Elts.size() == VT.getVectorNumElements());
8337   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8338                                   isAfterLegalize);
8339 }
8340 
getConstantVector(MVT VT,const APInt & SplatValue,unsigned SplatBitSize,LLVMContext & C)8341 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8342                                    unsigned SplatBitSize, LLVMContext &C) {
8343   unsigned ScalarSize = VT.getScalarSizeInBits();
8344   unsigned NumElm = SplatBitSize / ScalarSize;
8345 
8346   SmallVector<Constant *, 32> ConstantVec;
8347   for (unsigned i = 0; i < NumElm; i++) {
8348     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
8349     Constant *Const;
8350     if (VT.isFloatingPoint()) {
8351       if (ScalarSize == 32) {
8352         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8353       } else {
8354         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8355         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8356       }
8357     } else
8358       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8359     ConstantVec.push_back(Const);
8360   }
8361   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8362 }
8363 
isFoldableUseOfShuffle(SDNode * N)8364 static bool isFoldableUseOfShuffle(SDNode *N) {
8365   for (auto *U : N->uses()) {
8366     unsigned Opc = U->getOpcode();
8367     // VPERMV/VPERMV3 shuffles can never fold their index operands.
8368     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8369       return false;
8370     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8371       return false;
8372     if (isTargetShuffle(Opc))
8373       return true;
8374     if (Opc == ISD::BITCAST) // Ignore bitcasts
8375       return isFoldableUseOfShuffle(U);
8376     if (N->hasOneUse())
8377       return true;
8378   }
8379   return false;
8380 }
8381 
8382 // Check if the current node of build vector is a zero extended vector.
8383 // // If so, return the value extended.
8384 // // For example: (0,0,0,a,0,0,0,a,0,0,0,a,0,0,0,a) returns a.
8385 // // NumElt - return the number of zero extended identical values.
8386 // // EltType - return the type of the value include the zero extend.
isSplatZeroExtended(const BuildVectorSDNode * Op,unsigned & NumElt,MVT & EltType)8387 static SDValue isSplatZeroExtended(const BuildVectorSDNode *Op,
8388                                    unsigned &NumElt, MVT &EltType) {
8389   SDValue ExtValue = Op->getOperand(0);
8390   unsigned NumElts = Op->getNumOperands();
8391   unsigned Delta = NumElts;
8392 
8393   for (unsigned i = 1; i < NumElts; i++) {
8394     if (Op->getOperand(i) == ExtValue) {
8395       Delta = i;
8396       break;
8397     }
8398     if (!(Op->getOperand(i).isUndef() || isNullConstant(Op->getOperand(i))))
8399       return SDValue();
8400   }
8401   if (!isPowerOf2_32(Delta) || Delta == 1)
8402     return SDValue();
8403 
8404   for (unsigned i = Delta; i < NumElts; i++) {
8405     if (i % Delta == 0) {
8406       if (Op->getOperand(i) != ExtValue)
8407         return SDValue();
8408     } else if (!(isNullConstant(Op->getOperand(i)) ||
8409                  Op->getOperand(i).isUndef()))
8410       return SDValue();
8411   }
8412   unsigned EltSize = Op->getSimpleValueType(0).getScalarSizeInBits();
8413   unsigned ExtVTSize = EltSize * Delta;
8414   EltType = MVT::getIntegerVT(ExtVTSize);
8415   NumElt = NumElts / Delta;
8416   return ExtValue;
8417 }
8418 
8419 /// Attempt to use the vbroadcast instruction to generate a splat value
8420 /// from a splat BUILD_VECTOR which uses:
8421 ///  a. A single scalar load, or a constant.
8422 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8423 ///
8424 /// The VBROADCAST node is returned when a pattern is found,
8425 /// or SDValue() otherwise.
lowerBuildVectorAsBroadcast(BuildVectorSDNode * BVOp,const X86Subtarget & Subtarget,SelectionDAG & DAG)8426 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
8427                                            const X86Subtarget &Subtarget,
8428                                            SelectionDAG &DAG) {
8429   // VBROADCAST requires AVX.
8430   // TODO: Splats could be generated for non-AVX CPUs using SSE
8431   // instructions, but there's less potential gain for only 128-bit vectors.
8432   if (!Subtarget.hasAVX())
8433     return SDValue();
8434 
8435   MVT VT = BVOp->getSimpleValueType(0);
8436   SDLoc dl(BVOp);
8437 
8438   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8439          "Unsupported vector type for broadcast.");
8440 
8441   BitVector UndefElements;
8442   SDValue Ld = BVOp->getSplatValue(&UndefElements);
8443 
8444   // Attempt to use VBROADCASTM
8445   // From this paterrn:
8446   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8447   // b. t1 = (build_vector t0 t0)
8448   //
8449   // Create (VBROADCASTM v2i1 X)
8450   if (Subtarget.hasCDI() && (VT.is512BitVector() || Subtarget.hasVLX())) {
8451     MVT EltType = VT.getScalarType();
8452     unsigned NumElts = VT.getVectorNumElements();
8453     SDValue BOperand;
8454     SDValue ZeroExtended = isSplatZeroExtended(BVOp, NumElts, EltType);
8455     if ((ZeroExtended && ZeroExtended.getOpcode() == ISD::BITCAST) ||
8456         (Ld && Ld.getOpcode() == ISD::ZERO_EXTEND &&
8457          Ld.getOperand(0).getOpcode() == ISD::BITCAST)) {
8458       if (ZeroExtended)
8459         BOperand = ZeroExtended.getOperand(0);
8460       else
8461         BOperand = Ld.getOperand(0).getOperand(0);
8462       MVT MaskVT = BOperand.getSimpleValueType();
8463       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8464           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8465         SDValue Brdcst =
8466             DAG.getNode(X86ISD::VBROADCASTM, dl,
8467                         MVT::getVectorVT(EltType, NumElts), BOperand);
8468         return DAG.getBitcast(VT, Brdcst);
8469       }
8470     }
8471   }
8472 
8473   unsigned NumElts = VT.getVectorNumElements();
8474   unsigned NumUndefElts = UndefElements.count();
8475   if (!Ld || (NumElts - NumUndefElts) <= 1) {
8476     APInt SplatValue, Undef;
8477     unsigned SplatBitSize;
8478     bool HasUndef;
8479     // Check if this is a repeated constant pattern suitable for broadcasting.
8480     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8481         SplatBitSize > VT.getScalarSizeInBits() &&
8482         SplatBitSize < VT.getSizeInBits()) {
8483       // Avoid replacing with broadcast when it's a use of a shuffle
8484       // instruction to preserve the present custom lowering of shuffles.
8485       if (isFoldableUseOfShuffle(BVOp))
8486         return SDValue();
8487       // replace BUILD_VECTOR with broadcast of the repeated constants.
8488       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8489       LLVMContext *Ctx = DAG.getContext();
8490       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8491       if (Subtarget.hasAVX()) {
8492         if (SplatBitSize <= 64 && Subtarget.hasAVX2() &&
8493             !(SplatBitSize == 64 && Subtarget.is32Bit())) {
8494           // Splatted value can fit in one INTEGER constant in constant pool.
8495           // Load the constant and broadcast it.
8496           MVT CVT = MVT::getIntegerVT(SplatBitSize);
8497           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
8498           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
8499           SDValue CP = DAG.getConstantPool(C, PVT);
8500           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8501 
8502           unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8503           Ld = DAG.getLoad(
8504               CVT, dl, DAG.getEntryNode(), CP,
8505               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
8506               Alignment);
8507           SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
8508                                        MVT::getVectorVT(CVT, Repeat), Ld);
8509           return DAG.getBitcast(VT, Brdcst);
8510         } else if (SplatBitSize == 32 || SplatBitSize == 64) {
8511           // Splatted value can fit in one FLOAT constant in constant pool.
8512           // Load the constant and broadcast it.
8513           // AVX have support for 32 and 64 bit broadcast for floats only.
8514           // No 64bit integer in 32bit subtarget.
8515           MVT CVT = MVT::getFloatingPointVT(SplatBitSize);
8516           // Lower the splat via APFloat directly, to avoid any conversion.
8517           Constant *C =
8518               SplatBitSize == 32
8519                   ? ConstantFP::get(*Ctx,
8520                                     APFloat(APFloat::IEEEsingle(), SplatValue))
8521                   : ConstantFP::get(*Ctx,
8522                                     APFloat(APFloat::IEEEdouble(), SplatValue));
8523           SDValue CP = DAG.getConstantPool(C, PVT);
8524           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8525 
8526           unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8527           Ld = DAG.getLoad(
8528               CVT, dl, DAG.getEntryNode(), CP,
8529               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
8530               Alignment);
8531           SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
8532                                        MVT::getVectorVT(CVT, Repeat), Ld);
8533           return DAG.getBitcast(VT, Brdcst);
8534         } else if (SplatBitSize > 64) {
8535           // Load the vector of constants and broadcast it.
8536           MVT CVT = VT.getScalarType();
8537           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
8538                                              *Ctx);
8539           SDValue VCP = DAG.getConstantPool(VecC, PVT);
8540           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8541           unsigned Alignment = cast<ConstantPoolSDNode>(VCP)->getAlignment();
8542           Ld = DAG.getLoad(
8543               MVT::getVectorVT(CVT, NumElm), dl, DAG.getEntryNode(), VCP,
8544               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
8545               Alignment);
8546           SDValue Brdcst = DAG.getNode(X86ISD::SUBV_BROADCAST, dl, VT, Ld);
8547           return DAG.getBitcast(VT, Brdcst);
8548         }
8549       }
8550     }
8551 
8552     // If we are moving a scalar into a vector (Ld must be set and all elements
8553     // but 1 are undef) and that operation is not obviously supported by
8554     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8555     // That's better than general shuffling and may eliminate a load to GPR and
8556     // move from scalar to vector register.
8557     if (!Ld || NumElts - NumUndefElts != 1)
8558       return SDValue();
8559     unsigned ScalarSize = Ld.getValueSizeInBits();
8560     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8561       return SDValue();
8562   }
8563 
8564   bool ConstSplatVal =
8565       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8566 
8567   // Make sure that all of the users of a non-constant load are from the
8568   // BUILD_VECTOR node.
8569   if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
8570     return SDValue();
8571 
8572   unsigned ScalarSize = Ld.getValueSizeInBits();
8573   bool IsGE256 = (VT.getSizeInBits() >= 256);
8574 
8575   // When optimizing for size, generate up to 5 extra bytes for a broadcast
8576   // instruction to save 8 or more bytes of constant pool data.
8577   // TODO: If multiple splats are generated to load the same constant,
8578   // it may be detrimental to overall size. There needs to be a way to detect
8579   // that condition to know if this is truly a size win.
8580   bool OptForSize = DAG.shouldOptForSize();
8581 
8582   // Handle broadcasting a single constant scalar from the constant pool
8583   // into a vector.
8584   // On Sandybridge (no AVX2), it is still better to load a constant vector
8585   // from the constant pool and not to broadcast it from a scalar.
8586   // But override that restriction when optimizing for size.
8587   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8588   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8589     EVT CVT = Ld.getValueType();
8590     assert(!CVT.isVector() && "Must not broadcast a vector type");
8591 
8592     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
8593     // For size optimization, also splat v2f64 and v2i64, and for size opt
8594     // with AVX2, also splat i8 and i16.
8595     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8596     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8597         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8598       const Constant *C = nullptr;
8599       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
8600         C = CI->getConstantIntValue();
8601       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
8602         C = CF->getConstantFPValue();
8603 
8604       assert(C && "Invalid constant type");
8605 
8606       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8607       SDValue CP =
8608           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
8609       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8610       Ld = DAG.getLoad(
8611           CVT, dl, DAG.getEntryNode(), CP,
8612           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
8613           Alignment);
8614 
8615       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8616     }
8617   }
8618 
8619   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8620 
8621   // Handle AVX2 in-register broadcasts.
8622   if (!IsLoad && Subtarget.hasInt256() &&
8623       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8624     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8625 
8626   // The scalar source must be a normal load.
8627   if (!IsLoad)
8628     return SDValue();
8629 
8630   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8631       (Subtarget.hasVLX() && ScalarSize == 64))
8632     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8633 
8634   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8635   // double since there is no vbroadcastsd xmm
8636   if (Subtarget.hasInt256() && Ld.getValueType().isInteger()) {
8637     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
8638       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8639   }
8640 
8641   // Unsupported broadcast.
8642   return SDValue();
8643 }
8644 
8645 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
8646 /// underlying vector and index.
8647 ///
8648 /// Modifies \p ExtractedFromVec to the real vector and returns the real
8649 /// index.
getUnderlyingExtractedFromVec(SDValue & ExtractedFromVec,SDValue ExtIdx)8650 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
8651                                          SDValue ExtIdx) {
8652   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
8653   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
8654     return Idx;
8655 
8656   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
8657   // lowered this:
8658   //   (extract_vector_elt (v8f32 %1), Constant<6>)
8659   // to:
8660   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
8661   //                           (extract_subvector (v8f32 %0), Constant<4>),
8662   //                           undef)
8663   //                       Constant<0>)
8664   // In this case the vector is the extract_subvector expression and the index
8665   // is 2, as specified by the shuffle.
8666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
8667   SDValue ShuffleVec = SVOp->getOperand(0);
8668   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
8669   assert(ShuffleVecVT.getVectorElementType() ==
8670          ExtractedFromVec.getSimpleValueType().getVectorElementType());
8671 
8672   int ShuffleIdx = SVOp->getMaskElt(Idx);
8673   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
8674     ExtractedFromVec = ShuffleVec;
8675     return ShuffleIdx;
8676   }
8677   return Idx;
8678 }
8679 
buildFromShuffleMostly(SDValue Op,SelectionDAG & DAG)8680 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
8681   MVT VT = Op.getSimpleValueType();
8682 
8683   // Skip if insert_vec_elt is not supported.
8684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8685   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
8686     return SDValue();
8687 
8688   SDLoc DL(Op);
8689   unsigned NumElems = Op.getNumOperands();
8690 
8691   SDValue VecIn1;
8692   SDValue VecIn2;
8693   SmallVector<unsigned, 4> InsertIndices;
8694   SmallVector<int, 8> Mask(NumElems, -1);
8695 
8696   for (unsigned i = 0; i != NumElems; ++i) {
8697     unsigned Opc = Op.getOperand(i).getOpcode();
8698 
8699     if (Opc == ISD::UNDEF)
8700       continue;
8701 
8702     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
8703       // Quit if more than 1 elements need inserting.
8704       if (InsertIndices.size() > 1)
8705         return SDValue();
8706 
8707       InsertIndices.push_back(i);
8708       continue;
8709     }
8710 
8711     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
8712     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
8713 
8714     // Quit if non-constant index.
8715     if (!isa<ConstantSDNode>(ExtIdx))
8716       return SDValue();
8717     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
8718 
8719     // Quit if extracted from vector of different type.
8720     if (ExtractedFromVec.getValueType() != VT)
8721       return SDValue();
8722 
8723     if (!VecIn1.getNode())
8724       VecIn1 = ExtractedFromVec;
8725     else if (VecIn1 != ExtractedFromVec) {
8726       if (!VecIn2.getNode())
8727         VecIn2 = ExtractedFromVec;
8728       else if (VecIn2 != ExtractedFromVec)
8729         // Quit if more than 2 vectors to shuffle
8730         return SDValue();
8731     }
8732 
8733     if (ExtractedFromVec == VecIn1)
8734       Mask[i] = Idx;
8735     else if (ExtractedFromVec == VecIn2)
8736       Mask[i] = Idx + NumElems;
8737   }
8738 
8739   if (!VecIn1.getNode())
8740     return SDValue();
8741 
8742   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
8743   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
8744 
8745   for (unsigned Idx : InsertIndices)
8746     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8747                      DAG.getIntPtrConstant(Idx, DL));
8748 
8749   return NV;
8750 }
8751 
ConvertI1VectorToInteger(SDValue Op,SelectionDAG & DAG)8752 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
8753   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
8754          Op.getScalarValueSizeInBits() == 1 &&
8755          "Can not convert non-constant vector");
8756   uint64_t Immediate = 0;
8757   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8758     SDValue In = Op.getOperand(idx);
8759     if (!In.isUndef())
8760       Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
8761   }
8762   SDLoc dl(Op);
8763   MVT VT = MVT::getIntegerVT(std::max((int)Op.getValueSizeInBits(), 8));
8764   return DAG.getConstant(Immediate, dl, VT);
8765 }
8766 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
LowerBUILD_VECTORvXi1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)8767 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
8768                                      const X86Subtarget &Subtarget) {
8769 
8770   MVT VT = Op.getSimpleValueType();
8771   assert((VT.getVectorElementType() == MVT::i1) &&
8772          "Unexpected type in LowerBUILD_VECTORvXi1!");
8773 
8774   SDLoc dl(Op);
8775   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
8776       ISD::isBuildVectorAllOnes(Op.getNode()))
8777     return Op;
8778 
8779   uint64_t Immediate = 0;
8780   SmallVector<unsigned, 16> NonConstIdx;
8781   bool IsSplat = true;
8782   bool HasConstElts = false;
8783   int SplatIdx = -1;
8784   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8785     SDValue In = Op.getOperand(idx);
8786     if (In.isUndef())
8787       continue;
8788     if (!isa<ConstantSDNode>(In))
8789       NonConstIdx.push_back(idx);
8790     else {
8791       Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
8792       HasConstElts = true;
8793     }
8794     if (SplatIdx < 0)
8795       SplatIdx = idx;
8796     else if (In != Op.getOperand(SplatIdx))
8797       IsSplat = false;
8798   }
8799 
8800   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
8801   if (IsSplat) {
8802     // The build_vector allows the scalar element to be larger than the vector
8803     // element type. We need to mask it to use as a condition unless we know
8804     // the upper bits are zero.
8805     // FIXME: Use computeKnownBits instead of checking specific opcode?
8806     SDValue Cond = Op.getOperand(SplatIdx);
8807     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
8808     if (Cond.getOpcode() != ISD::SETCC)
8809       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
8810                          DAG.getConstant(1, dl, MVT::i8));
8811     return DAG.getSelect(dl, VT, Cond,
8812                          DAG.getConstant(1, dl, VT),
8813                          DAG.getConstant(0, dl, VT));
8814   }
8815 
8816   // insert elements one by one
8817   SDValue DstVec;
8818   if (HasConstElts) {
8819     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8820       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
8821       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
8822       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
8823       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
8824       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
8825     } else {
8826       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8827       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
8828       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8829       DstVec = DAG.getBitcast(VecVT, Imm);
8830       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
8831                            DAG.getIntPtrConstant(0, dl));
8832     }
8833   } else
8834     DstVec = DAG.getUNDEF(VT);
8835 
8836   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
8837     unsigned InsertIdx = NonConstIdx[i];
8838     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8839                          Op.getOperand(InsertIdx),
8840                          DAG.getIntPtrConstant(InsertIdx, dl));
8841   }
8842   return DstVec;
8843 }
8844 
8845 /// This is a helper function of LowerToHorizontalOp().
8846 /// This function checks that the build_vector \p N in input implements a
8847 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
8848 /// may not match the layout of an x86 256-bit horizontal instruction.
8849 /// In other words, if this returns true, then some extraction/insertion will
8850 /// be required to produce a valid horizontal instruction.
8851 ///
8852 /// Parameter \p Opcode defines the kind of horizontal operation to match.
8853 /// For example, if \p Opcode is equal to ISD::ADD, then this function
8854 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
8855 /// is equal to ISD::SUB, then this function checks if this is a horizontal
8856 /// arithmetic sub.
8857 ///
8858 /// This function only analyzes elements of \p N whose indices are
8859 /// in range [BaseIdx, LastIdx).
8860 ///
8861 /// TODO: This function was originally used to match both real and fake partial
8862 /// horizontal operations, but the index-matching logic is incorrect for that.
8863 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
8864 /// code because it is only used for partial h-op matching now?
isHorizontalBinOpPart(const BuildVectorSDNode * N,unsigned Opcode,SelectionDAG & DAG,unsigned BaseIdx,unsigned LastIdx,SDValue & V0,SDValue & V1)8865 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
8866                                   SelectionDAG &DAG,
8867                                   unsigned BaseIdx, unsigned LastIdx,
8868                                   SDValue &V0, SDValue &V1) {
8869   EVT VT = N->getValueType(0);
8870   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
8871   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
8872   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
8873          "Invalid Vector in input!");
8874 
8875   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
8876   bool CanFold = true;
8877   unsigned ExpectedVExtractIdx = BaseIdx;
8878   unsigned NumElts = LastIdx - BaseIdx;
8879   V0 = DAG.getUNDEF(VT);
8880   V1 = DAG.getUNDEF(VT);
8881 
8882   // Check if N implements a horizontal binop.
8883   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
8884     SDValue Op = N->getOperand(i + BaseIdx);
8885 
8886     // Skip UNDEFs.
8887     if (Op->isUndef()) {
8888       // Update the expected vector extract index.
8889       if (i * 2 == NumElts)
8890         ExpectedVExtractIdx = BaseIdx;
8891       ExpectedVExtractIdx += 2;
8892       continue;
8893     }
8894 
8895     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
8896 
8897     if (!CanFold)
8898       break;
8899 
8900     SDValue Op0 = Op.getOperand(0);
8901     SDValue Op1 = Op.getOperand(1);
8902 
8903     // Try to match the following pattern:
8904     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
8905     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8906         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8907         Op0.getOperand(0) == Op1.getOperand(0) &&
8908         isa<ConstantSDNode>(Op0.getOperand(1)) &&
8909         isa<ConstantSDNode>(Op1.getOperand(1)));
8910     if (!CanFold)
8911       break;
8912 
8913     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
8914     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
8915 
8916     if (i * 2 < NumElts) {
8917       if (V0.isUndef()) {
8918         V0 = Op0.getOperand(0);
8919         if (V0.getValueType() != VT)
8920           return false;
8921       }
8922     } else {
8923       if (V1.isUndef()) {
8924         V1 = Op0.getOperand(0);
8925         if (V1.getValueType() != VT)
8926           return false;
8927       }
8928       if (i * 2 == NumElts)
8929         ExpectedVExtractIdx = BaseIdx;
8930     }
8931 
8932     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
8933     if (I0 == ExpectedVExtractIdx)
8934       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
8935     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
8936       // Try to match the following dag sequence:
8937       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
8938       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
8939     } else
8940       CanFold = false;
8941 
8942     ExpectedVExtractIdx += 2;
8943   }
8944 
8945   return CanFold;
8946 }
8947 
8948 /// Emit a sequence of two 128-bit horizontal add/sub followed by
8949 /// a concat_vector.
8950 ///
8951 /// This is a helper function of LowerToHorizontalOp().
8952 /// This function expects two 256-bit vectors called V0 and V1.
8953 /// At first, each vector is split into two separate 128-bit vectors.
8954 /// Then, the resulting 128-bit vectors are used to implement two
8955 /// horizontal binary operations.
8956 ///
8957 /// The kind of horizontal binary operation is defined by \p X86Opcode.
8958 ///
8959 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
8960 /// the two new horizontal binop.
8961 /// When Mode is set, the first horizontal binop dag node would take as input
8962 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
8963 /// horizontal binop dag node would take as input the lower 128-bit of V1
8964 /// and the upper 128-bit of V1.
8965 ///   Example:
8966 ///     HADD V0_LO, V0_HI
8967 ///     HADD V1_LO, V1_HI
8968 ///
8969 /// Otherwise, the first horizontal binop dag node takes as input the lower
8970 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
8971 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
8972 ///   Example:
8973 ///     HADD V0_LO, V1_LO
8974 ///     HADD V0_HI, V1_HI
8975 ///
8976 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
8977 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
8978 /// the upper 128-bits of the result.
ExpandHorizontalBinOp(const SDValue & V0,const SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,unsigned X86Opcode,bool Mode,bool isUndefLO,bool isUndefHI)8979 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
8980                                      const SDLoc &DL, SelectionDAG &DAG,
8981                                      unsigned X86Opcode, bool Mode,
8982                                      bool isUndefLO, bool isUndefHI) {
8983   MVT VT = V0.getSimpleValueType();
8984   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
8985          "Invalid nodes in input!");
8986 
8987   unsigned NumElts = VT.getVectorNumElements();
8988   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
8989   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
8990   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
8991   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
8992   MVT NewVT = V0_LO.getSimpleValueType();
8993 
8994   SDValue LO = DAG.getUNDEF(NewVT);
8995   SDValue HI = DAG.getUNDEF(NewVT);
8996 
8997   if (Mode) {
8998     // Don't emit a horizontal binop if the result is expected to be UNDEF.
8999     if (!isUndefLO && !V0->isUndef())
9000       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
9001     if (!isUndefHI && !V1->isUndef())
9002       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
9003   } else {
9004     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9005     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
9006       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
9007 
9008     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
9009       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
9010   }
9011 
9012   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
9013 }
9014 
9015 /// Returns true iff \p BV builds a vector with the result equivalent to
9016 /// the result of ADDSUB/SUBADD operation.
9017 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
9018 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
9019 /// \p Opnd0 and \p Opnd1.
isAddSubOrSubAdd(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,unsigned & NumExtracts,bool & IsSubAdd)9020 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
9021                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
9022                              SDValue &Opnd0, SDValue &Opnd1,
9023                              unsigned &NumExtracts,
9024                              bool &IsSubAdd) {
9025 
9026   MVT VT = BV->getSimpleValueType(0);
9027   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
9028     return false;
9029 
9030   unsigned NumElts = VT.getVectorNumElements();
9031   SDValue InVec0 = DAG.getUNDEF(VT);
9032   SDValue InVec1 = DAG.getUNDEF(VT);
9033 
9034   NumExtracts = 0;
9035 
9036   // Odd-numbered elements in the input build vector are obtained from
9037   // adding/subtracting two integer/float elements.
9038   // Even-numbered elements in the input build vector are obtained from
9039   // subtracting/adding two integer/float elements.
9040   unsigned Opc[2] = {0, 0};
9041   for (unsigned i = 0, e = NumElts; i != e; ++i) {
9042     SDValue Op = BV->getOperand(i);
9043 
9044     // Skip 'undef' values.
9045     unsigned Opcode = Op.getOpcode();
9046     if (Opcode == ISD::UNDEF)
9047       continue;
9048 
9049     // Early exit if we found an unexpected opcode.
9050     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
9051       return false;
9052 
9053     SDValue Op0 = Op.getOperand(0);
9054     SDValue Op1 = Op.getOperand(1);
9055 
9056     // Try to match the following pattern:
9057     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
9058     // Early exit if we cannot match that sequence.
9059     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9060         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9061         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9062         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
9063         Op0.getOperand(1) != Op1.getOperand(1))
9064       return false;
9065 
9066     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
9067     if (I0 != i)
9068       return false;
9069 
9070     // We found a valid add/sub node, make sure its the same opcode as previous
9071     // elements for this parity.
9072     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
9073       return false;
9074     Opc[i % 2] = Opcode;
9075 
9076     // Update InVec0 and InVec1.
9077     if (InVec0.isUndef()) {
9078       InVec0 = Op0.getOperand(0);
9079       if (InVec0.getSimpleValueType() != VT)
9080         return false;
9081     }
9082     if (InVec1.isUndef()) {
9083       InVec1 = Op1.getOperand(0);
9084       if (InVec1.getSimpleValueType() != VT)
9085         return false;
9086     }
9087 
9088     // Make sure that operands in input to each add/sub node always
9089     // come from a same pair of vectors.
9090     if (InVec0 != Op0.getOperand(0)) {
9091       if (Opcode == ISD::FSUB)
9092         return false;
9093 
9094       // FADD is commutable. Try to commute the operands
9095       // and then test again.
9096       std::swap(Op0, Op1);
9097       if (InVec0 != Op0.getOperand(0))
9098         return false;
9099     }
9100 
9101     if (InVec1 != Op1.getOperand(0))
9102       return false;
9103 
9104     // Increment the number of extractions done.
9105     ++NumExtracts;
9106   }
9107 
9108   // Ensure we have found an opcode for both parities and that they are
9109   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
9110   // inputs are undef.
9111   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
9112       InVec0.isUndef() || InVec1.isUndef())
9113     return false;
9114 
9115   IsSubAdd = Opc[0] == ISD::FADD;
9116 
9117   Opnd0 = InVec0;
9118   Opnd1 = InVec1;
9119   return true;
9120 }
9121 
9122 /// Returns true if is possible to fold MUL and an idiom that has already been
9123 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
9124 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
9125 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
9126 ///
9127 /// Prior to calling this function it should be known that there is some
9128 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
9129 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
9130 /// before replacement of such SDNode with ADDSUB operation. Thus the number
9131 /// of \p Opnd0 uses is expected to be equal to 2.
9132 /// For example, this function may be called for the following IR:
9133 ///    %AB = fmul fast <2 x double> %A, %B
9134 ///    %Sub = fsub fast <2 x double> %AB, %C
9135 ///    %Add = fadd fast <2 x double> %AB, %C
9136 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
9137 ///                            <2 x i32> <i32 0, i32 3>
9138 /// There is a def for %Addsub here, which potentially can be replaced by
9139 /// X86ISD::ADDSUB operation:
9140 ///    %Addsub = X86ISD::ADDSUB %AB, %C
9141 /// and such ADDSUB can further be replaced with FMADDSUB:
9142 ///    %Addsub = FMADDSUB %A, %B, %C.
9143 ///
9144 /// The main reason why this method is called before the replacement of the
9145 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
9146 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
9147 /// FMADDSUB is.
isFMAddSubOrFMSubAdd(const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,SDValue & Opnd2,unsigned ExpectedUses)9148 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
9149                                  SelectionDAG &DAG,
9150                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
9151                                  unsigned ExpectedUses) {
9152   if (Opnd0.getOpcode() != ISD::FMUL ||
9153       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
9154     return false;
9155 
9156   // FIXME: These checks must match the similar ones in
9157   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
9158   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
9159   // or MUL + ADDSUB to FMADDSUB.
9160   const TargetOptions &Options = DAG.getTarget().Options;
9161   bool AllowFusion =
9162       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
9163   if (!AllowFusion)
9164     return false;
9165 
9166   Opnd2 = Opnd1;
9167   Opnd1 = Opnd0.getOperand(1);
9168   Opnd0 = Opnd0.getOperand(0);
9169 
9170   return true;
9171 }
9172 
9173 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
9174 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
9175 /// X86ISD::FMSUBADD node.
lowerToAddSubOrFMAddSub(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)9176 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
9177                                        const X86Subtarget &Subtarget,
9178                                        SelectionDAG &DAG) {
9179   SDValue Opnd0, Opnd1;
9180   unsigned NumExtracts;
9181   bool IsSubAdd;
9182   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
9183                         IsSubAdd))
9184     return SDValue();
9185 
9186   MVT VT = BV->getSimpleValueType(0);
9187   SDLoc DL(BV);
9188 
9189   // Try to generate X86ISD::FMADDSUB node here.
9190   SDValue Opnd2;
9191   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
9192     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
9193     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
9194   }
9195 
9196   // We only support ADDSUB.
9197   if (IsSubAdd)
9198     return SDValue();
9199 
9200   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
9201   // the ADDSUB idiom has been successfully recognized. There are no known
9202   // X86 targets with 512-bit ADDSUB instructions!
9203   // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
9204   // recognition.
9205   if (VT.is512BitVector())
9206     return SDValue();
9207 
9208   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
9209 }
9210 
isHopBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned & HOpcode,SDValue & V0,SDValue & V1)9211 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
9212                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
9213   // Initialize outputs to known values.
9214   MVT VT = BV->getSimpleValueType(0);
9215   HOpcode = ISD::DELETED_NODE;
9216   V0 = DAG.getUNDEF(VT);
9217   V1 = DAG.getUNDEF(VT);
9218 
9219   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
9220   // half of the result is calculated independently from the 128-bit halves of
9221   // the inputs, so that makes the index-checking logic below more complicated.
9222   unsigned NumElts = VT.getVectorNumElements();
9223   unsigned GenericOpcode = ISD::DELETED_NODE;
9224   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
9225   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
9226   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
9227   for (unsigned i = 0; i != Num128BitChunks; ++i) {
9228     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
9229       // Ignore undef elements.
9230       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
9231       if (Op.isUndef())
9232         continue;
9233 
9234       // If there's an opcode mismatch, we're done.
9235       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
9236         return false;
9237 
9238       // Initialize horizontal opcode.
9239       if (HOpcode == ISD::DELETED_NODE) {
9240         GenericOpcode = Op.getOpcode();
9241         switch (GenericOpcode) {
9242         case ISD::ADD: HOpcode = X86ISD::HADD; break;
9243         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
9244         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
9245         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
9246         default: return false;
9247         }
9248       }
9249 
9250       SDValue Op0 = Op.getOperand(0);
9251       SDValue Op1 = Op.getOperand(1);
9252       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9253           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9254           Op0.getOperand(0) != Op1.getOperand(0) ||
9255           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9256           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
9257         return false;
9258 
9259       // The source vector is chosen based on which 64-bit half of the
9260       // destination vector is being calculated.
9261       if (j < NumEltsIn64Bits) {
9262         if (V0.isUndef())
9263           V0 = Op0.getOperand(0);
9264       } else {
9265         if (V1.isUndef())
9266           V1 = Op0.getOperand(0);
9267       }
9268 
9269       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
9270       if (SourceVec != Op0.getOperand(0))
9271         return false;
9272 
9273       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
9274       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
9275       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
9276       unsigned ExpectedIndex = i * NumEltsIn128Bits +
9277                                (j % NumEltsIn64Bits) * 2;
9278       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
9279         continue;
9280 
9281       // If this is not a commutative op, this does not match.
9282       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
9283         return false;
9284 
9285       // Addition is commutative, so try swapping the extract indexes.
9286       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
9287       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
9288         continue;
9289 
9290       // Extract indexes do not match horizontal requirement.
9291       return false;
9292     }
9293   }
9294   // We matched. Opcode and operands are returned by reference as arguments.
9295   return true;
9296 }
9297 
getHopForBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned HOpcode,SDValue V0,SDValue V1)9298 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
9299                                     SelectionDAG &DAG, unsigned HOpcode,
9300                                     SDValue V0, SDValue V1) {
9301   // If either input vector is not the same size as the build vector,
9302   // extract/insert the low bits to the correct size.
9303   // This is free (examples: zmm --> xmm, xmm --> ymm).
9304   MVT VT = BV->getSimpleValueType(0);
9305   unsigned Width = VT.getSizeInBits();
9306   if (V0.getValueSizeInBits() > Width)
9307     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
9308   else if (V0.getValueSizeInBits() < Width)
9309     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
9310 
9311   if (V1.getValueSizeInBits() > Width)
9312     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
9313   else if (V1.getValueSizeInBits() < Width)
9314     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
9315 
9316   unsigned NumElts = VT.getVectorNumElements();
9317   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
9318   for (unsigned i = 0; i != NumElts; ++i)
9319     if (BV->getOperand(i).isUndef())
9320       DemandedElts.clearBit(i);
9321 
9322   // If we don't need the upper xmm, then perform as a xmm hop.
9323   unsigned HalfNumElts = NumElts / 2;
9324   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
9325     MVT HalfVT = VT.getHalfNumVectorElementsVT();
9326     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
9327     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
9328     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
9329     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
9330   }
9331 
9332   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
9333 }
9334 
9335 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
LowerToHorizontalOp(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)9336 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
9337                                    const X86Subtarget &Subtarget,
9338                                    SelectionDAG &DAG) {
9339   // We need at least 2 non-undef elements to make this worthwhile by default.
9340   unsigned NumNonUndefs =
9341       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
9342   if (NumNonUndefs < 2)
9343     return SDValue();
9344 
9345   // There are 4 sets of horizontal math operations distinguished by type:
9346   // int/FP at 128-bit/256-bit. Each type was introduced with a different
9347   // subtarget feature. Try to match those "native" patterns first.
9348   MVT VT = BV->getSimpleValueType(0);
9349   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
9350       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
9351       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
9352       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
9353     unsigned HOpcode;
9354     SDValue V0, V1;
9355     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
9356       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
9357   }
9358 
9359   // Try harder to match 256-bit ops by using extract/concat.
9360   if (!Subtarget.hasAVX() || !VT.is256BitVector())
9361     return SDValue();
9362 
9363   // Count the number of UNDEF operands in the build_vector in input.
9364   unsigned NumElts = VT.getVectorNumElements();
9365   unsigned Half = NumElts / 2;
9366   unsigned NumUndefsLO = 0;
9367   unsigned NumUndefsHI = 0;
9368   for (unsigned i = 0, e = Half; i != e; ++i)
9369     if (BV->getOperand(i)->isUndef())
9370       NumUndefsLO++;
9371 
9372   for (unsigned i = Half, e = NumElts; i != e; ++i)
9373     if (BV->getOperand(i)->isUndef())
9374       NumUndefsHI++;
9375 
9376   SDLoc DL(BV);
9377   SDValue InVec0, InVec1;
9378   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
9379     SDValue InVec2, InVec3;
9380     unsigned X86Opcode;
9381     bool CanFold = true;
9382 
9383     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
9384         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
9385                               InVec3) &&
9386         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9387         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9388       X86Opcode = X86ISD::HADD;
9389     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
9390                                    InVec1) &&
9391              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
9392                                    InVec3) &&
9393              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9394              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9395       X86Opcode = X86ISD::HSUB;
9396     else
9397       CanFold = false;
9398 
9399     if (CanFold) {
9400       // Do not try to expand this build_vector into a pair of horizontal
9401       // add/sub if we can emit a pair of scalar add/sub.
9402       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9403         return SDValue();
9404 
9405       // Convert this build_vector into a pair of horizontal binops followed by
9406       // a concat vector. We must adjust the outputs from the partial horizontal
9407       // matching calls above to account for undefined vector halves.
9408       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
9409       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
9410       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
9411       bool isUndefLO = NumUndefsLO == Half;
9412       bool isUndefHI = NumUndefsHI == Half;
9413       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
9414                                    isUndefHI);
9415     }
9416   }
9417 
9418   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
9419       VT == MVT::v16i16) {
9420     unsigned X86Opcode;
9421     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
9422       X86Opcode = X86ISD::HADD;
9423     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
9424                                    InVec1))
9425       X86Opcode = X86ISD::HSUB;
9426     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
9427                                    InVec1))
9428       X86Opcode = X86ISD::FHADD;
9429     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
9430                                    InVec1))
9431       X86Opcode = X86ISD::FHSUB;
9432     else
9433       return SDValue();
9434 
9435     // Don't try to expand this build_vector into a pair of horizontal add/sub
9436     // if we can simply emit a pair of scalar add/sub.
9437     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9438       return SDValue();
9439 
9440     // Convert this build_vector into two horizontal add/sub followed by
9441     // a concat vector.
9442     bool isUndefLO = NumUndefsLO == Half;
9443     bool isUndefHI = NumUndefsHI == Half;
9444     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
9445                                  isUndefLO, isUndefHI);
9446   }
9447 
9448   return SDValue();
9449 }
9450 
9451 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
9452 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
9453 /// just apply the bit to the vectors.
9454 /// NOTE: Its not in our interest to start make a general purpose vectorizer
9455 /// from this, but enough scalar bit operations are created from the later
9456 /// legalization + scalarization stages to need basic support.
lowerBuildVectorToBitOp(BuildVectorSDNode * Op,SelectionDAG & DAG)9457 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
9458                                        SelectionDAG &DAG) {
9459   SDLoc DL(Op);
9460   MVT VT = Op->getSimpleValueType(0);
9461   unsigned NumElems = VT.getVectorNumElements();
9462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9463 
9464   // Check that all elements have the same opcode.
9465   // TODO: Should we allow UNDEFS and if so how many?
9466   unsigned Opcode = Op->getOperand(0).getOpcode();
9467   for (unsigned i = 1; i < NumElems; ++i)
9468     if (Opcode != Op->getOperand(i).getOpcode())
9469       return SDValue();
9470 
9471   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
9472   bool IsShift = false;
9473   switch (Opcode) {
9474   default:
9475     return SDValue();
9476   case ISD::SHL:
9477   case ISD::SRL:
9478   case ISD::SRA:
9479     IsShift = true;
9480     break;
9481   case ISD::AND:
9482   case ISD::XOR:
9483   case ISD::OR:
9484     // Don't do this if the buildvector is a splat - we'd replace one
9485     // constant with an entire vector.
9486     if (Op->getSplatValue())
9487       return SDValue();
9488     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
9489       return SDValue();
9490     break;
9491   }
9492 
9493   SmallVector<SDValue, 4> LHSElts, RHSElts;
9494   for (SDValue Elt : Op->ops()) {
9495     SDValue LHS = Elt.getOperand(0);
9496     SDValue RHS = Elt.getOperand(1);
9497 
9498     // We expect the canonicalized RHS operand to be the constant.
9499     if (!isa<ConstantSDNode>(RHS))
9500       return SDValue();
9501 
9502     // Extend shift amounts.
9503     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
9504       if (!IsShift)
9505         return SDValue();
9506       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
9507     }
9508 
9509     LHSElts.push_back(LHS);
9510     RHSElts.push_back(RHS);
9511   }
9512 
9513   // Limit to shifts by uniform immediates.
9514   // TODO: Only accept vXi8/vXi64 special cases?
9515   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
9516   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
9517     return SDValue();
9518 
9519   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
9520   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
9521   return DAG.getNode(Opcode, DL, VT, LHS, RHS);
9522 }
9523 
9524 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
9525 /// functionality to do this, so it's all zeros, all ones, or some derivation
9526 /// that is cheap to calculate.
materializeVectorConstant(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)9527 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
9528                                          const X86Subtarget &Subtarget) {
9529   SDLoc DL(Op);
9530   MVT VT = Op.getSimpleValueType();
9531 
9532   // Vectors containing all zeros can be matched by pxor and xorps.
9533   if (ISD::isBuildVectorAllZeros(Op.getNode()))
9534     return Op;
9535 
9536   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9537   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9538   // vpcmpeqd on 256-bit vectors.
9539   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9540     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9541       return Op;
9542 
9543     return getOnesVector(VT, DAG, DL);
9544   }
9545 
9546   return SDValue();
9547 }
9548 
9549 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9550 /// from a vector of source values and a vector of extraction indices.
9551 /// The vectors might be manipulated to match the type of the permute op.
createVariablePermute(MVT VT,SDValue SrcVec,SDValue IndicesVec,SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)9552 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9553                                      SDLoc &DL, SelectionDAG &DAG,
9554                                      const X86Subtarget &Subtarget) {
9555   MVT ShuffleVT = VT;
9556   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9557   unsigned NumElts = VT.getVectorNumElements();
9558   unsigned SizeInBits = VT.getSizeInBits();
9559 
9560   // Adjust IndicesVec to match VT size.
9561   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9562          "Illegal variable permute mask size");
9563   if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9564     IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9565                                   NumElts * VT.getScalarSizeInBits());
9566   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9567 
9568   // Handle SrcVec that don't match VT type.
9569   if (SrcVec.getValueSizeInBits() != SizeInBits) {
9570     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9571       // Handle larger SrcVec by treating it as a larger permute.
9572       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9573       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9574       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9575       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9576                                   Subtarget, DAG, SDLoc(IndicesVec));
9577       return extractSubVector(
9578           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget), 0,
9579           DAG, DL, SizeInBits);
9580     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9581       // Widen smaller SrcVec to match VT.
9582       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9583     } else
9584       return SDValue();
9585   }
9586 
9587   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9588     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9589     EVT SrcVT = Idx.getValueType();
9590     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9591     uint64_t IndexScale = 0;
9592     uint64_t IndexOffset = 0;
9593 
9594     // If we're scaling a smaller permute op, then we need to repeat the
9595     // indices, scaling and offsetting them as well.
9596     // e.g. v4i32 -> v16i8 (Scale = 4)
9597     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9598     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9599     for (uint64_t i = 0; i != Scale; ++i) {
9600       IndexScale |= Scale << (i * NumDstBits);
9601       IndexOffset |= i << (i * NumDstBits);
9602     }
9603 
9604     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9605                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9606     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9607                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9608     return Idx;
9609   };
9610 
9611   unsigned Opcode = 0;
9612   switch (VT.SimpleTy) {
9613   default:
9614     break;
9615   case MVT::v16i8:
9616     if (Subtarget.hasSSSE3())
9617       Opcode = X86ISD::PSHUFB;
9618     break;
9619   case MVT::v8i16:
9620     if (Subtarget.hasVLX() && Subtarget.hasBWI())
9621       Opcode = X86ISD::VPERMV;
9622     else if (Subtarget.hasSSSE3()) {
9623       Opcode = X86ISD::PSHUFB;
9624       ShuffleVT = MVT::v16i8;
9625     }
9626     break;
9627   case MVT::v4f32:
9628   case MVT::v4i32:
9629     if (Subtarget.hasAVX()) {
9630       Opcode = X86ISD::VPERMILPV;
9631       ShuffleVT = MVT::v4f32;
9632     } else if (Subtarget.hasSSSE3()) {
9633       Opcode = X86ISD::PSHUFB;
9634       ShuffleVT = MVT::v16i8;
9635     }
9636     break;
9637   case MVT::v2f64:
9638   case MVT::v2i64:
9639     if (Subtarget.hasAVX()) {
9640       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
9641       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9642       Opcode = X86ISD::VPERMILPV;
9643       ShuffleVT = MVT::v2f64;
9644     } else if (Subtarget.hasSSE41()) {
9645       // SSE41 can compare v2i64 - select between indices 0 and 1.
9646       return DAG.getSelectCC(
9647           DL, IndicesVec,
9648           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
9649           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
9650           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
9651           ISD::CondCode::SETEQ);
9652     }
9653     break;
9654   case MVT::v32i8:
9655     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
9656       Opcode = X86ISD::VPERMV;
9657     else if (Subtarget.hasXOP()) {
9658       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
9659       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
9660       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
9661       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
9662       return DAG.getNode(
9663           ISD::CONCAT_VECTORS, DL, VT,
9664           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
9665           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
9666     } else if (Subtarget.hasAVX()) {
9667       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
9668       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
9669       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
9670       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
9671       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
9672                               ArrayRef<SDValue> Ops) {
9673         // Permute Lo and Hi and then select based on index range.
9674         // This works as SHUFB uses bits[3:0] to permute elements and we don't
9675         // care about the bit[7] as its just an index vector.
9676         SDValue Idx = Ops[2];
9677         EVT VT = Idx.getValueType();
9678         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
9679                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
9680                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
9681                                ISD::CondCode::SETGT);
9682       };
9683       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
9684       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
9685                               PSHUFBBuilder);
9686     }
9687     break;
9688   case MVT::v16i16:
9689     if (Subtarget.hasVLX() && Subtarget.hasBWI())
9690       Opcode = X86ISD::VPERMV;
9691     else if (Subtarget.hasAVX()) {
9692       // Scale to v32i8 and perform as v32i8.
9693       IndicesVec = ScaleIndices(IndicesVec, 2);
9694       return DAG.getBitcast(
9695           VT, createVariablePermute(
9696                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
9697                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
9698     }
9699     break;
9700   case MVT::v8f32:
9701   case MVT::v8i32:
9702     if (Subtarget.hasAVX2())
9703       Opcode = X86ISD::VPERMV;
9704     else if (Subtarget.hasAVX()) {
9705       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
9706       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9707                                           {0, 1, 2, 3, 0, 1, 2, 3});
9708       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9709                                           {4, 5, 6, 7, 4, 5, 6, 7});
9710       if (Subtarget.hasXOP())
9711         return DAG.getBitcast(
9712             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
9713                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9714       // Permute Lo and Hi and then select based on index range.
9715       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
9716       SDValue Res = DAG.getSelectCC(
9717           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
9718           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
9719           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
9720           ISD::CondCode::SETGT);
9721       return DAG.getBitcast(VT, Res);
9722     }
9723     break;
9724   case MVT::v4i64:
9725   case MVT::v4f64:
9726     if (Subtarget.hasAVX512()) {
9727       if (!Subtarget.hasVLX()) {
9728         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9729         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9730                                 SDLoc(SrcVec));
9731         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9732                                     DAG, SDLoc(IndicesVec));
9733         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9734                                             DAG, Subtarget);
9735         return extract256BitVector(Res, 0, DAG, DL);
9736       }
9737       Opcode = X86ISD::VPERMV;
9738     } else if (Subtarget.hasAVX()) {
9739       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9740       SDValue LoLo =
9741           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9742       SDValue HiHi =
9743           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9744       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
9745       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9746       if (Subtarget.hasXOP())
9747         return DAG.getBitcast(
9748             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
9749                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9750       // Permute Lo and Hi and then select based on index range.
9751       // This works as VPERMILPD only uses index bit[1] to permute elements.
9752       SDValue Res = DAG.getSelectCC(
9753           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
9754           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
9755           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
9756           ISD::CondCode::SETGT);
9757       return DAG.getBitcast(VT, Res);
9758     }
9759     break;
9760   case MVT::v64i8:
9761     if (Subtarget.hasVBMI())
9762       Opcode = X86ISD::VPERMV;
9763     break;
9764   case MVT::v32i16:
9765     if (Subtarget.hasBWI())
9766       Opcode = X86ISD::VPERMV;
9767     break;
9768   case MVT::v16f32:
9769   case MVT::v16i32:
9770   case MVT::v8f64:
9771   case MVT::v8i64:
9772     if (Subtarget.hasAVX512())
9773       Opcode = X86ISD::VPERMV;
9774     break;
9775   }
9776   if (!Opcode)
9777     return SDValue();
9778 
9779   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
9780          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
9781          "Illegal variable permute shuffle type");
9782 
9783   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
9784   if (Scale > 1)
9785     IndicesVec = ScaleIndices(IndicesVec, Scale);
9786 
9787   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
9788   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
9789 
9790   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
9791   SDValue Res = Opcode == X86ISD::VPERMV
9792                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
9793                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
9794   return DAG.getBitcast(VT, Res);
9795 }
9796 
9797 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
9798 // reasoned to be a permutation of a vector by indices in a non-constant vector.
9799 // (build_vector (extract_elt V, (extract_elt I, 0)),
9800 //               (extract_elt V, (extract_elt I, 1)),
9801 //                    ...
9802 // ->
9803 // (vpermv I, V)
9804 //
9805 // TODO: Handle undefs
9806 // TODO: Utilize pshufb and zero mask blending to support more efficient
9807 // construction of vectors with constant-0 elements.
9808 static SDValue
LowerBUILD_VECTORAsVariablePermute(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)9809 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
9810                                    const X86Subtarget &Subtarget) {
9811   SDValue SrcVec, IndicesVec;
9812   // Check for a match of the permute source vector and permute index elements.
9813   // This is done by checking that the i-th build_vector operand is of the form:
9814   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
9815   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
9816     SDValue Op = V.getOperand(Idx);
9817     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9818       return SDValue();
9819 
9820     // If this is the first extract encountered in V, set the source vector,
9821     // otherwise verify the extract is from the previously defined source
9822     // vector.
9823     if (!SrcVec)
9824       SrcVec = Op.getOperand(0);
9825     else if (SrcVec != Op.getOperand(0))
9826       return SDValue();
9827     SDValue ExtractedIndex = Op->getOperand(1);
9828     // Peek through extends.
9829     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
9830         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
9831       ExtractedIndex = ExtractedIndex.getOperand(0);
9832     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9833       return SDValue();
9834 
9835     // If this is the first extract from the index vector candidate, set the
9836     // indices vector, otherwise verify the extract is from the previously
9837     // defined indices vector.
9838     if (!IndicesVec)
9839       IndicesVec = ExtractedIndex.getOperand(0);
9840     else if (IndicesVec != ExtractedIndex.getOperand(0))
9841       return SDValue();
9842 
9843     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
9844     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
9845       return SDValue();
9846   }
9847 
9848   SDLoc DL(V);
9849   MVT VT = V.getSimpleValueType();
9850   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9851 }
9852 
9853 SDValue
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const9854 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
9855   SDLoc dl(Op);
9856 
9857   MVT VT = Op.getSimpleValueType();
9858   MVT EltVT = VT.getVectorElementType();
9859   unsigned NumElems = Op.getNumOperands();
9860 
9861   // Generate vectors for predicate vectors.
9862   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
9863     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
9864 
9865   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
9866     return VectorConstant;
9867 
9868   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9869   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
9870     return AddSub;
9871   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
9872     return HorizontalOp;
9873   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
9874     return Broadcast;
9875   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, DAG))
9876     return BitOp;
9877 
9878   unsigned EVTBits = EltVT.getSizeInBits();
9879 
9880   unsigned NumZero  = 0;
9881   unsigned NumNonZero = 0;
9882   uint64_t NonZeros = 0;
9883   bool IsAllConstants = true;
9884   SmallSet<SDValue, 8> Values;
9885   unsigned NumConstants = NumElems;
9886   for (unsigned i = 0; i < NumElems; ++i) {
9887     SDValue Elt = Op.getOperand(i);
9888     if (Elt.isUndef())
9889       continue;
9890     Values.insert(Elt);
9891     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
9892       IsAllConstants = false;
9893       NumConstants--;
9894     }
9895     if (X86::isZeroNode(Elt))
9896       NumZero++;
9897     else {
9898       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
9899       NonZeros |= ((uint64_t)1 << i);
9900       NumNonZero++;
9901     }
9902   }
9903 
9904   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
9905   if (NumNonZero == 0)
9906     return DAG.getUNDEF(VT);
9907 
9908   // If we are inserting one variable into a vector of non-zero constants, try
9909   // to avoid loading each constant element as a scalar. Load the constants as a
9910   // vector and then insert the variable scalar element. If insertion is not
9911   // supported, fall back to a shuffle to get the scalar blended with the
9912   // constants. Insertion into a zero vector is handled as a special-case
9913   // somewhere below here.
9914   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9915       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
9916        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
9917     // Create an all-constant vector. The variable element in the old
9918     // build vector is replaced by undef in the constant vector. Save the
9919     // variable scalar element and its index for use in the insertelement.
9920     LLVMContext &Context = *DAG.getContext();
9921     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9922     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9923     SDValue VarElt;
9924     SDValue InsIndex;
9925     for (unsigned i = 0; i != NumElems; ++i) {
9926       SDValue Elt = Op.getOperand(i);
9927       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9928         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9929       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9930         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9931       else if (!Elt.isUndef()) {
9932         assert(!VarElt.getNode() && !InsIndex.getNode() &&
9933                "Expected one variable element in this vector");
9934         VarElt = Elt;
9935         InsIndex = DAG.getConstant(i, dl, getVectorIdxTy(DAG.getDataLayout()));
9936       }
9937     }
9938     Constant *CV = ConstantVector::get(ConstVecOps);
9939     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9940 
9941     // The constants we just created may not be legal (eg, floating point). We
9942     // must lower the vector right here because we can not guarantee that we'll
9943     // legalize it before loading it. This is also why we could not just create
9944     // a new build vector here. If the build vector contains illegal constants,
9945     // it could get split back up into a series of insert elements.
9946     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9947     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9948     MachineFunction &MF = DAG.getMachineFunction();
9949     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9950     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9951     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
9952     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9953     if (InsertC < NumEltsInLow128Bits)
9954       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9955 
9956     // There's no good way to insert into the high elements of a >128-bit
9957     // vector, so use shuffles to avoid an extract/insert sequence.
9958     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
9959     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
9960     SmallVector<int, 8> ShuffleMask;
9961     unsigned NumElts = VT.getVectorNumElements();
9962     for (unsigned i = 0; i != NumElts; ++i)
9963       ShuffleMask.push_back(i == InsertC ? NumElts : i);
9964     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9965     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9966   }
9967 
9968   // Special case for single non-zero, non-undef, element.
9969   if (NumNonZero == 1) {
9970     unsigned Idx = countTrailingZeros(NonZeros);
9971     SDValue Item = Op.getOperand(Idx);
9972 
9973     // If we have a constant or non-constant insertion into the low element of
9974     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9975     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
9976     // depending on what the source datatype is.
9977     if (Idx == 0) {
9978       if (NumZero == 0)
9979         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9980 
9981       if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
9982           (EltVT == MVT::i64 && Subtarget.is64Bit())) {
9983         assert((VT.is128BitVector() || VT.is256BitVector() ||
9984                 VT.is512BitVector()) &&
9985                "Expected an SSE value type!");
9986         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9987         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
9988         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9989       }
9990 
9991       // We can't directly insert an i8 or i16 into a vector, so zero extend
9992       // it to i32 first.
9993       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9994         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9995         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
9996         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9997         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9998         return DAG.getBitcast(VT, Item);
9999       }
10000     }
10001 
10002     // Is it a vector logical left shift?
10003     if (NumElems == 2 && Idx == 1 &&
10004         X86::isZeroNode(Op.getOperand(0)) &&
10005         !X86::isZeroNode(Op.getOperand(1))) {
10006       unsigned NumBits = VT.getSizeInBits();
10007       return getVShift(true, VT,
10008                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10009                                    VT, Op.getOperand(1)),
10010                        NumBits/2, DAG, *this, dl);
10011     }
10012 
10013     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
10014       return SDValue();
10015 
10016     // Otherwise, if this is a vector with i32 or f32 elements, and the element
10017     // is a non-constant being inserted into an element other than the low one,
10018     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
10019     // movd/movss) to move this into the low element, then shuffle it into
10020     // place.
10021     if (EVTBits == 32) {
10022       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10023       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
10024     }
10025   }
10026 
10027   // Splat is obviously ok. Let legalizer expand it to a shuffle.
10028   if (Values.size() == 1) {
10029     if (EVTBits == 32) {
10030       // Instead of a shuffle like this:
10031       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
10032       // Check if it's possible to issue this instead.
10033       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
10034       unsigned Idx = countTrailingZeros(NonZeros);
10035       SDValue Item = Op.getOperand(Idx);
10036       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
10037         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
10038     }
10039     return SDValue();
10040   }
10041 
10042   // A vector full of immediates; various special cases are already
10043   // handled, so this is best done with a single constant-pool load.
10044   if (IsAllConstants)
10045     return SDValue();
10046 
10047   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
10048       return V;
10049 
10050   // See if we can use a vector load to get all of the elements.
10051   {
10052     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
10053     if (SDValue LD =
10054             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
10055       return LD;
10056   }
10057 
10058   // If this is a splat of pairs of 32-bit elements, we can use a narrower
10059   // build_vector and broadcast it.
10060   // TODO: We could probably generalize this more.
10061   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
10062     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
10063                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
10064     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
10065       // Make sure all the even/odd operands match.
10066       for (unsigned i = 2; i != NumElems; ++i)
10067         if (Ops[i % 2] != Op.getOperand(i))
10068           return false;
10069       return true;
10070     };
10071     if (CanSplat(Op, NumElems, Ops)) {
10072       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
10073       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
10074       // Create a new build vector and cast to v2i64/v2f64.
10075       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
10076                                      DAG.getBuildVector(NarrowVT, dl, Ops));
10077       // Broadcast from v2i64/v2f64 and cast to final VT.
10078       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems/2);
10079       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
10080                                             NewBV));
10081     }
10082   }
10083 
10084   // For AVX-length vectors, build the individual 128-bit pieces and use
10085   // shuffles to put them in place.
10086   if (VT.getSizeInBits() > 128) {
10087     MVT HVT = MVT::getVectorVT(EltVT, NumElems/2);
10088 
10089     // Build both the lower and upper subvector.
10090     SDValue Lower =
10091         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
10092     SDValue Upper = DAG.getBuildVector(
10093         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
10094 
10095     // Recreate the wider vector with the lower and upper part.
10096     return concatSubVectors(Lower, Upper, DAG, dl);
10097   }
10098 
10099   // Let legalizer expand 2-wide build_vectors.
10100   if (EVTBits == 64) {
10101     if (NumNonZero == 1) {
10102       // One half is zero or undef.
10103       unsigned Idx = countTrailingZeros(NonZeros);
10104       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
10105                                Op.getOperand(Idx));
10106       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
10107     }
10108     return SDValue();
10109   }
10110 
10111   // If element VT is < 32 bits, convert it to inserts into a zero vector.
10112   if (EVTBits == 8 && NumElems == 16)
10113     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
10114                                           DAG, Subtarget))
10115       return V;
10116 
10117   if (EVTBits == 16 && NumElems == 8)
10118     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
10119                                           DAG, Subtarget))
10120       return V;
10121 
10122   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
10123   if (EVTBits == 32 && NumElems == 4)
10124     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
10125       return V;
10126 
10127   // If element VT is == 32 bits, turn it into a number of shuffles.
10128   if (NumElems == 4 && NumZero > 0) {
10129     SmallVector<SDValue, 8> Ops(NumElems);
10130     for (unsigned i = 0; i < 4; ++i) {
10131       bool isZero = !(NonZeros & (1ULL << i));
10132       if (isZero)
10133         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
10134       else
10135         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10136     }
10137 
10138     for (unsigned i = 0; i < 2; ++i) {
10139       switch ((NonZeros >> (i*2)) & 0x3) {
10140         default: llvm_unreachable("Unexpected NonZero count");
10141         case 0:
10142           Ops[i] = Ops[i*2];  // Must be a zero vector.
10143           break;
10144         case 1:
10145           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
10146           break;
10147         case 2:
10148           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10149           break;
10150         case 3:
10151           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10152           break;
10153       }
10154     }
10155 
10156     bool Reverse1 = (NonZeros & 0x3) == 2;
10157     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
10158     int MaskVec[] = {
10159       Reverse1 ? 1 : 0,
10160       Reverse1 ? 0 : 1,
10161       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
10162       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
10163     };
10164     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
10165   }
10166 
10167   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
10168 
10169   // Check for a build vector from mostly shuffle plus few inserting.
10170   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
10171     return Sh;
10172 
10173   // For SSE 4.1, use insertps to put the high elements into the low element.
10174   if (Subtarget.hasSSE41()) {
10175     SDValue Result;
10176     if (!Op.getOperand(0).isUndef())
10177       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
10178     else
10179       Result = DAG.getUNDEF(VT);
10180 
10181     for (unsigned i = 1; i < NumElems; ++i) {
10182       if (Op.getOperand(i).isUndef()) continue;
10183       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
10184                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
10185     }
10186     return Result;
10187   }
10188 
10189   // Otherwise, expand into a number of unpckl*, start by extending each of
10190   // our (non-undef) elements to the full vector width with the element in the
10191   // bottom slot of the vector (which generates no code for SSE).
10192   SmallVector<SDValue, 8> Ops(NumElems);
10193   for (unsigned i = 0; i < NumElems; ++i) {
10194     if (!Op.getOperand(i).isUndef())
10195       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10196     else
10197       Ops[i] = DAG.getUNDEF(VT);
10198   }
10199 
10200   // Next, we iteratively mix elements, e.g. for v4f32:
10201   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
10202   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
10203   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
10204   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
10205     // Generate scaled UNPCKL shuffle mask.
10206     SmallVector<int, 16> Mask;
10207     for(unsigned i = 0; i != Scale; ++i)
10208       Mask.push_back(i);
10209     for (unsigned i = 0; i != Scale; ++i)
10210       Mask.push_back(NumElems+i);
10211     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
10212 
10213     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
10214       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
10215   }
10216   return Ops[0];
10217 }
10218 
10219 // 256-bit AVX can use the vinsertf128 instruction
10220 // to create 256-bit vectors from two other 128-bit ones.
10221 // TODO: Detect subvector broadcast here instead of DAG combine?
LowerAVXCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)10222 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
10223                                       const X86Subtarget &Subtarget) {
10224   SDLoc dl(Op);
10225   MVT ResVT = Op.getSimpleValueType();
10226 
10227   assert((ResVT.is256BitVector() ||
10228           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
10229 
10230   unsigned NumOperands = Op.getNumOperands();
10231   unsigned NumZero = 0;
10232   unsigned NumNonZero = 0;
10233   unsigned NonZeros = 0;
10234   for (unsigned i = 0; i != NumOperands; ++i) {
10235     SDValue SubVec = Op.getOperand(i);
10236     if (SubVec.isUndef())
10237       continue;
10238     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10239       ++NumZero;
10240     else {
10241       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10242       NonZeros |= 1 << i;
10243       ++NumNonZero;
10244     }
10245   }
10246 
10247   // If we have more than 2 non-zeros, build each half separately.
10248   if (NumNonZero > 2) {
10249     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10250     ArrayRef<SDUse> Ops = Op->ops();
10251     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10252                              Ops.slice(0, NumOperands/2));
10253     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10254                              Ops.slice(NumOperands/2));
10255     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10256   }
10257 
10258   // Otherwise, build it up through insert_subvectors.
10259   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
10260                         : DAG.getUNDEF(ResVT);
10261 
10262   MVT SubVT = Op.getOperand(0).getSimpleValueType();
10263   unsigned NumSubElems = SubVT.getVectorNumElements();
10264   for (unsigned i = 0; i != NumOperands; ++i) {
10265     if ((NonZeros & (1 << i)) == 0)
10266       continue;
10267 
10268     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
10269                       Op.getOperand(i),
10270                       DAG.getIntPtrConstant(i * NumSubElems, dl));
10271   }
10272 
10273   return Vec;
10274 }
10275 
10276 // Returns true if the given node is a type promotion (by concatenating i1
10277 // zeros) of the result of a node that already zeros all upper bits of
10278 // k-register.
10279 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
LowerCONCAT_VECTORSvXi1(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)10280 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
10281                                        const X86Subtarget &Subtarget,
10282                                        SelectionDAG & DAG) {
10283   SDLoc dl(Op);
10284   MVT ResVT = Op.getSimpleValueType();
10285   unsigned NumOperands = Op.getNumOperands();
10286 
10287   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10288          "Unexpected number of operands in CONCAT_VECTORS");
10289 
10290   uint64_t Zeros = 0;
10291   uint64_t NonZeros = 0;
10292   for (unsigned i = 0; i != NumOperands; ++i) {
10293     SDValue SubVec = Op.getOperand(i);
10294     if (SubVec.isUndef())
10295       continue;
10296     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10297     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10298       Zeros |= (uint64_t)1 << i;
10299     else
10300       NonZeros |= (uint64_t)1 << i;
10301   }
10302 
10303   unsigned NumElems = ResVT.getVectorNumElements();
10304 
10305   // If we are inserting non-zero vector and there are zeros in LSBs and undef
10306   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10307   // insert_subvector will give us two kshifts.
10308   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10309       Log2_64(NonZeros) != NumOperands - 1) {
10310     MVT ShiftVT = ResVT;
10311     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
10312       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
10313     unsigned Idx = Log2_64(NonZeros);
10314     SDValue SubVec = Op.getOperand(Idx);
10315     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10316     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
10317                          DAG.getUNDEF(ShiftVT), SubVec,
10318                          DAG.getIntPtrConstant(0, dl));
10319     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
10320                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10321     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10322                        DAG.getIntPtrConstant(0, dl));
10323   }
10324 
10325   // If there are zero or one non-zeros we can handle this very simply.
10326   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10327     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10328     if (!NonZeros)
10329       return Vec;
10330     unsigned Idx = Log2_64(NonZeros);
10331     SDValue SubVec = Op.getOperand(Idx);
10332     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10333     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10334                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
10335   }
10336 
10337   if (NumOperands > 2) {
10338     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10339     ArrayRef<SDUse> Ops = Op->ops();
10340     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10341                              Ops.slice(0, NumOperands/2));
10342     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10343                              Ops.slice(NumOperands/2));
10344     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10345   }
10346 
10347   assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?");
10348 
10349   if (ResVT.getVectorNumElements() >= 16)
10350     return Op; // The operation is legal with KUNPCK
10351 
10352   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
10353                             DAG.getUNDEF(ResVT), Op.getOperand(0),
10354                             DAG.getIntPtrConstant(0, dl));
10355   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10356                      DAG.getIntPtrConstant(NumElems/2, dl));
10357 }
10358 
LowerCONCAT_VECTORS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)10359 static SDValue LowerCONCAT_VECTORS(SDValue Op,
10360                                    const X86Subtarget &Subtarget,
10361                                    SelectionDAG &DAG) {
10362   MVT VT = Op.getSimpleValueType();
10363   if (VT.getVectorElementType() == MVT::i1)
10364     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
10365 
10366   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10367          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
10368           Op.getNumOperands() == 4)));
10369 
10370   // AVX can use the vinsertf128 instruction to create 256-bit vectors
10371   // from two other 128-bit ones.
10372 
10373   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10374   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
10375 }
10376 
10377 //===----------------------------------------------------------------------===//
10378 // Vector shuffle lowering
10379 //
10380 // This is an experimental code path for lowering vector shuffles on x86. It is
10381 // designed to handle arbitrary vector shuffles and blends, gracefully
10382 // degrading performance as necessary. It works hard to recognize idiomatic
10383 // shuffles and lower them to optimal instruction patterns without leaving
10384 // a framework that allows reasonably efficient handling of all vector shuffle
10385 // patterns.
10386 //===----------------------------------------------------------------------===//
10387 
10388 /// Tiny helper function to identify a no-op mask.
10389 ///
10390 /// This is a somewhat boring predicate function. It checks whether the mask
10391 /// array input, which is assumed to be a single-input shuffle mask of the kind
10392 /// used by the X86 shuffle instructions (not a fully general
10393 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10394 /// in-place shuffle are 'no-op's.
isNoopShuffleMask(ArrayRef<int> Mask)10395 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
10396   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10397     assert(Mask[i] >= -1 && "Out of bound mask element!");
10398     if (Mask[i] >= 0 && Mask[i] != i)
10399       return false;
10400   }
10401   return true;
10402 }
10403 
10404 /// Test whether there are elements crossing LaneSizeInBits lanes in this
10405 /// shuffle mask.
10406 ///
10407 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10408 /// and we routinely test for these.
isLaneCrossingShuffleMask(unsigned LaneSizeInBits,unsigned ScalarSizeInBits,ArrayRef<int> Mask)10409 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10410                                       unsigned ScalarSizeInBits,
10411                                       ArrayRef<int> Mask) {
10412   assert(LaneSizeInBits && ScalarSizeInBits &&
10413          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10414          "Illegal shuffle lane size");
10415   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10416   int Size = Mask.size();
10417   for (int i = 0; i < Size; ++i)
10418     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10419       return true;
10420   return false;
10421 }
10422 
10423 /// Test whether there are elements crossing 128-bit lanes in this
10424 /// shuffle mask.
is128BitLaneCrossingShuffleMask(MVT VT,ArrayRef<int> Mask)10425 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
10426   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10427 }
10428 
10429 /// Test whether a shuffle mask is equivalent within each sub-lane.
10430 ///
10431 /// This checks a shuffle mask to see if it is performing the same
10432 /// lane-relative shuffle in each sub-lane. This trivially implies
10433 /// that it is also not lane-crossing. It may however involve a blend from the
10434 /// same lane of a second vector.
10435 ///
10436 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10437 /// non-trivial to compute in the face of undef lanes. The representation is
10438 /// suitable for use with existing 128-bit shuffles as entries from the second
10439 /// vector have been remapped to [LaneSize, 2*LaneSize).
isRepeatedShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10440 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10441                                   ArrayRef<int> Mask,
10442                                   SmallVectorImpl<int> &RepeatedMask) {
10443   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10444   RepeatedMask.assign(LaneSize, -1);
10445   int Size = Mask.size();
10446   for (int i = 0; i < Size; ++i) {
10447     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10448     if (Mask[i] < 0)
10449       continue;
10450     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10451       // This entry crosses lanes, so there is no way to model this shuffle.
10452       return false;
10453 
10454     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10455     // Adjust second vector indices to start at LaneSize instead of Size.
10456     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10457                                 : Mask[i] % LaneSize + LaneSize;
10458     if (RepeatedMask[i % LaneSize] < 0)
10459       // This is the first non-undef entry in this slot of a 128-bit lane.
10460       RepeatedMask[i % LaneSize] = LocalM;
10461     else if (RepeatedMask[i % LaneSize] != LocalM)
10462       // Found a mismatch with the repeated mask.
10463       return false;
10464   }
10465   return true;
10466 }
10467 
10468 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
10469 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10470 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10471                                 SmallVectorImpl<int> &RepeatedMask) {
10472   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10473 }
10474 
10475 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask)10476 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
10477   SmallVector<int, 32> RepeatedMask;
10478   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10479 }
10480 
10481 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
10482 static bool
is256BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10483 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10484                                 SmallVectorImpl<int> &RepeatedMask) {
10485   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10486 }
10487 
10488 /// Test whether a target shuffle mask is equivalent within each sub-lane.
10489 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10490 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10491                                         ArrayRef<int> Mask,
10492                                         SmallVectorImpl<int> &RepeatedMask) {
10493   int LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10494   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10495   int Size = Mask.size();
10496   for (int i = 0; i < Size; ++i) {
10497     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10498     if (Mask[i] == SM_SentinelUndef)
10499       continue;
10500     if (Mask[i] == SM_SentinelZero) {
10501       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10502         return false;
10503       RepeatedMask[i % LaneSize] = SM_SentinelZero;
10504       continue;
10505     }
10506     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10507       // This entry crosses lanes, so there is no way to model this shuffle.
10508       return false;
10509 
10510     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10511     // Adjust second vector indices to start at LaneSize instead of Size.
10512     int LocalM =
10513         Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
10514     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10515       // This is the first non-undef entry in this slot of a 128-bit lane.
10516       RepeatedMask[i % LaneSize] = LocalM;
10517     else if (RepeatedMask[i % LaneSize] != LocalM)
10518       // Found a mismatch with the repeated mask.
10519       return false;
10520   }
10521   return true;
10522 }
10523 
10524 /// Checks whether a shuffle mask is equivalent to an explicit list of
10525 /// arguments.
10526 ///
10527 /// This is a fast way to test a shuffle mask against a fixed pattern:
10528 ///
10529 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
10530 ///
10531 /// It returns true if the mask is exactly as wide as the argument list, and
10532 /// each element of the mask is either -1 (signifying undef) or the value given
10533 /// in the argument.
isShuffleEquivalent(SDValue V1,SDValue V2,ArrayRef<int> Mask,ArrayRef<int> ExpectedMask)10534 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
10535                                 ArrayRef<int> ExpectedMask) {
10536   if (Mask.size() != ExpectedMask.size())
10537     return false;
10538 
10539   int Size = Mask.size();
10540 
10541   // If the values are build vectors, we can look through them to find
10542   // equivalent inputs that make the shuffles equivalent.
10543   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
10544   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
10545 
10546   for (int i = 0; i < Size; ++i) {
10547     assert(Mask[i] >= -1 && "Out of bound mask element!");
10548     if (Mask[i] >= 0 && Mask[i] != ExpectedMask[i]) {
10549       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
10550       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
10551       if (!MaskBV || !ExpectedBV ||
10552           MaskBV->getOperand(Mask[i] % Size) !=
10553               ExpectedBV->getOperand(ExpectedMask[i] % Size))
10554         return false;
10555     }
10556   }
10557 
10558   return true;
10559 }
10560 
10561 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
10562 ///
10563 /// The masks must be exactly the same width.
10564 ///
10565 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
10566 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
10567 ///
10568 /// SM_SentinelZero is accepted as a valid negative index but must match in
10569 /// both.
isTargetShuffleEquivalent(ArrayRef<int> Mask,ArrayRef<int> ExpectedMask,SDValue V1=SDValue (),SDValue V2=SDValue ())10570 static bool isTargetShuffleEquivalent(ArrayRef<int> Mask,
10571                                       ArrayRef<int> ExpectedMask,
10572                                       SDValue V1 = SDValue(),
10573                                       SDValue V2 = SDValue()) {
10574   int Size = Mask.size();
10575   if (Size != (int)ExpectedMask.size())
10576     return false;
10577   assert(isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) &&
10578          "Illegal target shuffle mask");
10579 
10580   // Check for out-of-range target shuffle mask indices.
10581   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
10582     return false;
10583 
10584   // If the values are build vectors, we can look through them to find
10585   // equivalent inputs that make the shuffles equivalent.
10586   auto *BV1 = dyn_cast_or_null<BuildVectorSDNode>(V1);
10587   auto *BV2 = dyn_cast_or_null<BuildVectorSDNode>(V2);
10588   BV1 = ((BV1 && Size != (int)BV1->getNumOperands()) ? nullptr : BV1);
10589   BV2 = ((BV2 && Size != (int)BV2->getNumOperands()) ? nullptr : BV2);
10590 
10591   for (int i = 0; i < Size; ++i) {
10592     if (Mask[i] == SM_SentinelUndef || Mask[i] == ExpectedMask[i])
10593       continue;
10594     if (0 <= Mask[i] && 0 <= ExpectedMask[i]) {
10595       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
10596       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
10597       if (MaskBV && ExpectedBV &&
10598           MaskBV->getOperand(Mask[i] % Size) ==
10599               ExpectedBV->getOperand(ExpectedMask[i] % Size))
10600         continue;
10601     }
10602     // TODO - handle SM_Sentinel equivalences.
10603     return false;
10604   }
10605   return true;
10606 }
10607 
10608 // Attempt to create a shuffle mask from a VSELECT condition mask.
createShuffleMaskFromVSELECT(SmallVectorImpl<int> & Mask,SDValue Cond)10609 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
10610                                          SDValue Cond) {
10611   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10612     return false;
10613 
10614   unsigned Size = Cond.getValueType().getVectorNumElements();
10615   Mask.resize(Size, SM_SentinelUndef);
10616 
10617   for (int i = 0; i != (int)Size; ++i) {
10618     SDValue CondElt = Cond.getOperand(i);
10619     Mask[i] = i;
10620     // Arbitrarily choose from the 2nd operand if the select condition element
10621     // is undef.
10622     // TODO: Can we do better by matching patterns such as even/odd?
10623     if (CondElt.isUndef() || isNullConstant(CondElt))
10624       Mask[i] += Size;
10625   }
10626 
10627   return true;
10628 }
10629 
10630 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
10631 // instructions.
isUnpackWdShuffleMask(ArrayRef<int> Mask,MVT VT)10632 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
10633   if (VT != MVT::v8i32 && VT != MVT::v8f32)
10634     return false;
10635 
10636   SmallVector<int, 8> Unpcklwd;
10637   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
10638                           /* Unary = */ false);
10639   SmallVector<int, 8> Unpckhwd;
10640   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
10641                           /* Unary = */ false);
10642   bool IsUnpackwdMask = (isTargetShuffleEquivalent(Mask, Unpcklwd) ||
10643                          isTargetShuffleEquivalent(Mask, Unpckhwd));
10644   return IsUnpackwdMask;
10645 }
10646 
is128BitUnpackShuffleMask(ArrayRef<int> Mask)10647 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
10648   // Create 128-bit vector type based on mask size.
10649   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
10650   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
10651 
10652   // We can't assume a canonical shuffle mask, so try the commuted version too.
10653   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
10654   ShuffleVectorSDNode::commuteMask(CommutedMask);
10655 
10656   // Match any of unary/binary or low/high.
10657   for (unsigned i = 0; i != 4; ++i) {
10658     SmallVector<int, 16> UnpackMask;
10659     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
10660     if (isTargetShuffleEquivalent(Mask, UnpackMask) ||
10661         isTargetShuffleEquivalent(CommutedMask, UnpackMask))
10662       return true;
10663   }
10664   return false;
10665 }
10666 
10667 /// Return true if a shuffle mask chooses elements identically in its top and
10668 /// bottom halves. For example, any splat mask has the same top and bottom
10669 /// halves. If an element is undefined in only one half of the mask, the halves
10670 /// are not considered identical.
hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask)10671 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
10672   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
10673   unsigned HalfSize = Mask.size() / 2;
10674   for (unsigned i = 0; i != HalfSize; ++i) {
10675     if (Mask[i] != Mask[i + HalfSize])
10676       return false;
10677   }
10678   return true;
10679 }
10680 
10681 /// Get a 4-lane 8-bit shuffle immediate for a mask.
10682 ///
10683 /// This helper function produces an 8-bit shuffle immediate corresponding to
10684 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
10685 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10686 /// example.
10687 ///
10688 /// NB: We rely heavily on "undef" masks preserving the input lane.
getV4X86ShuffleImm(ArrayRef<int> Mask)10689 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10690   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
10691   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
10692   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
10693   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
10694   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
10695 
10696   unsigned Imm = 0;
10697   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10698   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10699   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10700   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10701   return Imm;
10702 }
10703 
getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,const SDLoc & DL,SelectionDAG & DAG)10704 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
10705                                           SelectionDAG &DAG) {
10706   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10707 }
10708 
10709 // The Shuffle result is as follow:
10710 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10711 // Each Zeroable's element correspond to a particular Mask's element.
10712 // As described in computeZeroableShuffleElements function.
10713 //
10714 // The function looks for a sub-mask that the nonzero elements are in
10715 // increasing order. If such sub-mask exist. The function returns true.
isNonZeroElementsInOrder(const APInt & Zeroable,ArrayRef<int> Mask,const EVT & VectorType,bool & IsZeroSideLeft)10716 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10717                                      ArrayRef<int> Mask, const EVT &VectorType,
10718                                      bool &IsZeroSideLeft) {
10719   int NextElement = -1;
10720   // Check if the Mask's nonzero elements are in increasing order.
10721   for (int i = 0, e = Mask.size(); i < e; i++) {
10722     // Checks if the mask's zeros elements are built from only zeros.
10723     assert(Mask[i] >= -1 && "Out of bound mask element!");
10724     if (Mask[i] < 0)
10725       return false;
10726     if (Zeroable[i])
10727       continue;
10728     // Find the lowest non zero element
10729     if (NextElement < 0) {
10730       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10731       IsZeroSideLeft = NextElement != 0;
10732     }
10733     // Exit if the mask's non zero elements are not in increasing order.
10734     if (NextElement != Mask[i])
10735       return false;
10736     NextElement++;
10737   }
10738   return true;
10739 }
10740 
10741 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
lowerShuffleWithPSHUFB(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10742 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
10743                                       ArrayRef<int> Mask, SDValue V1,
10744                                       SDValue V2, const APInt &Zeroable,
10745                                       const X86Subtarget &Subtarget,
10746                                       SelectionDAG &DAG) {
10747   int Size = Mask.size();
10748   int LaneSize = 128 / VT.getScalarSizeInBits();
10749   const int NumBytes = VT.getSizeInBits() / 8;
10750   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10751 
10752   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
10753          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
10754          (Subtarget.hasBWI() && VT.is512BitVector()));
10755 
10756   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
10757   // Sign bit set in i8 mask means zero element.
10758   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
10759 
10760   SDValue V;
10761   for (int i = 0; i < NumBytes; ++i) {
10762     int M = Mask[i / NumEltBytes];
10763     if (M < 0) {
10764       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
10765       continue;
10766     }
10767     if (Zeroable[i / NumEltBytes]) {
10768       PSHUFBMask[i] = ZeroMask;
10769       continue;
10770     }
10771 
10772     // We can only use a single input of V1 or V2.
10773     SDValue SrcV = (M >= Size ? V2 : V1);
10774     if (V && V != SrcV)
10775       return SDValue();
10776     V = SrcV;
10777     M %= Size;
10778 
10779     // PSHUFB can't cross lanes, ensure this doesn't happen.
10780     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10781       return SDValue();
10782 
10783     M = M % LaneSize;
10784     M = M * NumEltBytes + (i % NumEltBytes);
10785     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
10786   }
10787   assert(V && "Failed to find a source input");
10788 
10789   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10790   return DAG.getBitcast(
10791       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
10792                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
10793 }
10794 
10795 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10796                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
10797                            const SDLoc &dl);
10798 
10799 // X86 has dedicated shuffle that can be lowered to VEXPAND
lowerShuffleToEXPAND(const SDLoc & DL,MVT VT,const APInt & Zeroable,ArrayRef<int> Mask,SDValue & V1,SDValue & V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)10800 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
10801                                     const APInt &Zeroable,
10802                                     ArrayRef<int> Mask, SDValue &V1,
10803                                     SDValue &V2, SelectionDAG &DAG,
10804                                     const X86Subtarget &Subtarget) {
10805   bool IsLeftZeroSide = true;
10806   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10807                                 IsLeftZeroSide))
10808     return SDValue();
10809   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10810   MVT IntegerType =
10811       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10812   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10813   unsigned NumElts = VT.getVectorNumElements();
10814   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
10815          "Unexpected number of vector elements");
10816   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10817                               Subtarget, DAG, DL);
10818   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10819   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10820   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10821 }
10822 
matchShuffleWithUNPCK(MVT VT,SDValue & V1,SDValue & V2,unsigned & UnpackOpcode,bool IsUnary,ArrayRef<int> TargetMask,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)10823 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
10824                                   unsigned &UnpackOpcode, bool IsUnary,
10825                                   ArrayRef<int> TargetMask, const SDLoc &DL,
10826                                   SelectionDAG &DAG,
10827                                   const X86Subtarget &Subtarget) {
10828   int NumElts = VT.getVectorNumElements();
10829 
10830   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10831   for (int i = 0; i != NumElts; i += 2) {
10832     int M1 = TargetMask[i + 0];
10833     int M2 = TargetMask[i + 1];
10834     Undef1 &= (SM_SentinelUndef == M1);
10835     Undef2 &= (SM_SentinelUndef == M2);
10836     Zero1 &= isUndefOrZero(M1);
10837     Zero2 &= isUndefOrZero(M2);
10838   }
10839   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
10840          "Zeroable shuffle detected");
10841 
10842   // Attempt to match the target mask against the unpack lo/hi mask patterns.
10843   SmallVector<int, 64> Unpckl, Unpckh;
10844   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10845   if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
10846     UnpackOpcode = X86ISD::UNPCKL;
10847     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10848     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10849     return true;
10850   }
10851 
10852   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10853   if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
10854     UnpackOpcode = X86ISD::UNPCKH;
10855     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10856     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10857     return true;
10858   }
10859 
10860   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10861   if (IsUnary && (Zero1 || Zero2)) {
10862     // Don't bother if we can blend instead.
10863     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10864         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10865       return false;
10866 
10867     bool MatchLo = true, MatchHi = true;
10868     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10869       int M = TargetMask[i];
10870 
10871       // Ignore if the input is known to be zero or the index is undef.
10872       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10873           (M == SM_SentinelUndef))
10874         continue;
10875 
10876       MatchLo &= (M == Unpckl[i]);
10877       MatchHi &= (M == Unpckh[i]);
10878     }
10879 
10880     if (MatchLo || MatchHi) {
10881       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10882       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10883       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10884       return true;
10885     }
10886   }
10887 
10888   // If a binary shuffle, commute and try again.
10889   if (!IsUnary) {
10890     ShuffleVectorSDNode::commuteMask(Unpckl);
10891     if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
10892       UnpackOpcode = X86ISD::UNPCKL;
10893       std::swap(V1, V2);
10894       return true;
10895     }
10896 
10897     ShuffleVectorSDNode::commuteMask(Unpckh);
10898     if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
10899       UnpackOpcode = X86ISD::UNPCKH;
10900       std::swap(V1, V2);
10901       return true;
10902     }
10903   }
10904 
10905   return false;
10906 }
10907 
10908 // X86 has dedicated unpack instructions that can handle specific blend
10909 // operations: UNPCKH and UNPCKL.
lowerShuffleWithUNPCK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)10910 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
10911                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
10912                                      SelectionDAG &DAG) {
10913   SmallVector<int, 8> Unpckl;
10914   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10915   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10916     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10917 
10918   SmallVector<int, 8> Unpckh;
10919   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10920   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10921     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10922 
10923   // Commute and try again.
10924   ShuffleVectorSDNode::commuteMask(Unpckl);
10925   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10926     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10927 
10928   ShuffleVectorSDNode::commuteMask(Unpckh);
10929   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10930     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10931 
10932   return SDValue();
10933 }
10934 
matchShuffleAsVPMOV(ArrayRef<int> Mask,bool SwappedOps,int Delta)10935 static bool matchShuffleAsVPMOV(ArrayRef<int> Mask, bool SwappedOps,
10936                                 int Delta) {
10937   int Size = (int)Mask.size();
10938   int Split = Size / Delta;
10939   int TruncatedVectorStart = SwappedOps ? Size : 0;
10940 
10941   // Match for mask starting with e.g.: <8, 10, 12, 14,... or <0, 2, 4, 6,...
10942   if (!isSequentialOrUndefInRange(Mask, 0, Split, TruncatedVectorStart, Delta))
10943     return false;
10944 
10945   // The rest of the mask should not refer to the truncated vector's elements.
10946   if (isAnyInRange(Mask.slice(Split, Size - Split), TruncatedVectorStart,
10947                    TruncatedVectorStart + Size))
10948     return false;
10949 
10950   return true;
10951 }
10952 
10953 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10954 //
10955 // An example is the following:
10956 //
10957 // t0: ch = EntryToken
10958 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10959 //         t25: v4i32 = truncate t2
10960 //       t41: v8i16 = bitcast t25
10961 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10962 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10963 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10964 //   t18: v2i64 = bitcast t51
10965 //
10966 // Without avx512vl, this is lowered to:
10967 //
10968 // vpmovqd %zmm0, %ymm0
10969 // vpshufb {{.*#+}} xmm0 =
10970 // xmm0[0,1,4,5,8,9,12,13],zero,zero,zero,zero,zero,zero,zero,zero
10971 //
10972 // But when avx512vl is available, one can just use a single vpmovdw
10973 // instruction.
lowerShuffleWithVPMOV(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)10974 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, ArrayRef<int> Mask,
10975                                      MVT VT, SDValue V1, SDValue V2,
10976                                      SelectionDAG &DAG,
10977                                      const X86Subtarget &Subtarget) {
10978   if (VT != MVT::v16i8 && VT != MVT::v8i16)
10979     return SDValue();
10980 
10981   if (Mask.size() != VT.getVectorNumElements())
10982     return SDValue();
10983 
10984   bool SwappedOps = false;
10985 
10986   if (!ISD::isBuildVectorAllZeros(V2.getNode())) {
10987     if (!ISD::isBuildVectorAllZeros(V1.getNode()))
10988       return SDValue();
10989 
10990     std::swap(V1, V2);
10991     SwappedOps = true;
10992   }
10993 
10994   // Look for:
10995   //
10996   // bitcast (truncate <8 x i32> %vec to <8 x i16>) to <16 x i8>
10997   // bitcast (truncate <4 x i64> %vec to <4 x i32>) to <8 x i16>
10998   //
10999   // and similar ones.
11000   if (V1.getOpcode() != ISD::BITCAST)
11001     return SDValue();
11002   if (V1.getOperand(0).getOpcode() != ISD::TRUNCATE)
11003     return SDValue();
11004 
11005   SDValue Src = V1.getOperand(0).getOperand(0);
11006   MVT SrcVT = Src.getSimpleValueType();
11007 
11008   // The vptrunc** instructions truncating 128 bit and 256 bit vectors
11009   // are only available with avx512vl.
11010   if (!SrcVT.is512BitVector() && !Subtarget.hasVLX())
11011     return SDValue();
11012 
11013   // Down Convert Word to Byte is only available with avx512bw. The case with
11014   // 256-bit output doesn't contain a shuffle and is therefore not handled here.
11015   if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
11016       !Subtarget.hasBWI())
11017     return SDValue();
11018 
11019   // The first half/quarter of the mask should refer to every second/fourth
11020   // element of the vector truncated and bitcasted.
11021   if (!matchShuffleAsVPMOV(Mask, SwappedOps, 2) &&
11022       !matchShuffleAsVPMOV(Mask, SwappedOps, 4))
11023     return SDValue();
11024 
11025   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Src);
11026 }
11027 
11028 // X86 has dedicated pack instructions that can handle specific truncation
11029 // operations: PACKSS and PACKUS.
matchShuffleWithPACK(MVT VT,MVT & SrcVT,SDValue & V1,SDValue & V2,unsigned & PackOpcode,ArrayRef<int> TargetMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)11030 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11031                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
11032                                  SelectionDAG &DAG,
11033                                  const X86Subtarget &Subtarget) {
11034   unsigned NumElts = VT.getVectorNumElements();
11035   unsigned BitSize = VT.getScalarSizeInBits();
11036   MVT PackSVT = MVT::getIntegerVT(BitSize * 2);
11037   MVT PackVT = MVT::getVectorVT(PackSVT, NumElts / 2);
11038 
11039   auto MatchPACK = [&](SDValue N1, SDValue N2) {
11040     SDValue VV1 = DAG.getBitcast(PackVT, N1);
11041     SDValue VV2 = DAG.getBitcast(PackVT, N2);
11042     if (Subtarget.hasSSE41() || PackSVT == MVT::i16) {
11043       APInt ZeroMask = APInt::getHighBitsSet(BitSize * 2, BitSize);
11044       if ((N1.isUndef() || DAG.MaskedValueIsZero(VV1, ZeroMask)) &&
11045           (N2.isUndef() || DAG.MaskedValueIsZero(VV2, ZeroMask))) {
11046         V1 = VV1;
11047         V2 = VV2;
11048         SrcVT = PackVT;
11049         PackOpcode = X86ISD::PACKUS;
11050         return true;
11051       }
11052     }
11053     if ((N1.isUndef() || DAG.ComputeNumSignBits(VV1) > BitSize) &&
11054         (N2.isUndef() || DAG.ComputeNumSignBits(VV2) > BitSize)) {
11055       V1 = VV1;
11056       V2 = VV2;
11057       SrcVT = PackVT;
11058       PackOpcode = X86ISD::PACKSS;
11059       return true;
11060     }
11061     return false;
11062   };
11063 
11064   // Try binary shuffle.
11065   SmallVector<int, 32> BinaryMask;
11066   createPackShuffleMask(VT, BinaryMask, false);
11067   if (isTargetShuffleEquivalent(TargetMask, BinaryMask, V1, V2))
11068     if (MatchPACK(V1, V2))
11069       return true;
11070 
11071   // Try unary shuffle.
11072   SmallVector<int, 32> UnaryMask;
11073   createPackShuffleMask(VT, UnaryMask, true);
11074   if (isTargetShuffleEquivalent(TargetMask, UnaryMask, V1))
11075     if (MatchPACK(V1, V1))
11076       return true;
11077 
11078   return false;
11079 }
11080 
lowerShuffleWithPACK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)11081 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
11082                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
11083                                     const X86Subtarget &Subtarget) {
11084   MVT PackVT;
11085   unsigned PackOpcode;
11086   if (matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11087                            Subtarget))
11088     return DAG.getNode(PackOpcode, DL, VT, DAG.getBitcast(PackVT, V1),
11089                        DAG.getBitcast(PackVT, V2));
11090 
11091   return SDValue();
11092 }
11093 
11094 /// Try to emit a bitmask instruction for a shuffle.
11095 ///
11096 /// This handles cases where we can model a blend exactly as a bitmask due to
11097 /// one of the inputs being zeroable.
lowerShuffleAsBitMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11098 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
11099                                      SDValue V2, ArrayRef<int> Mask,
11100                                      const APInt &Zeroable,
11101                                      const X86Subtarget &Subtarget,
11102                                      SelectionDAG &DAG) {
11103   MVT MaskVT = VT;
11104   MVT EltVT = VT.getVectorElementType();
11105   SDValue Zero, AllOnes;
11106   // Use f64 if i64 isn't legal.
11107   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
11108     EltVT = MVT::f64;
11109     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
11110   }
11111 
11112   MVT LogicVT = VT;
11113   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
11114     Zero = DAG.getConstantFP(0.0, DL, EltVT);
11115     AllOnes = DAG.getConstantFP(
11116         APFloat::getAllOnesValue(EltVT.getSizeInBits(), true), DL, EltVT);
11117     LogicVT =
11118         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
11119   } else {
11120     Zero = DAG.getConstant(0, DL, EltVT);
11121     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11122   }
11123 
11124   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
11125   SDValue V;
11126   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11127     if (Zeroable[i])
11128       continue;
11129     if (Mask[i] % Size != i)
11130       return SDValue(); // Not a blend.
11131     if (!V)
11132       V = Mask[i] < Size ? V1 : V2;
11133     else if (V != (Mask[i] < Size ? V1 : V2))
11134       return SDValue(); // Can only let one input through the mask.
11135 
11136     VMaskOps[i] = AllOnes;
11137   }
11138   if (!V)
11139     return SDValue(); // No non-zeroable elements!
11140 
11141   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
11142   VMask = DAG.getBitcast(LogicVT, VMask);
11143   V = DAG.getBitcast(LogicVT, V);
11144   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11145   return DAG.getBitcast(VT, And);
11146 }
11147 
11148 /// Try to emit a blend instruction for a shuffle using bit math.
11149 ///
11150 /// This is used as a fallback approach when first class blend instructions are
11151 /// unavailable. Currently it is only suitable for integer vectors, but could
11152 /// be generalized for floating point vectors if desirable.
lowerShuffleAsBitBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)11153 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
11154                                       SDValue V2, ArrayRef<int> Mask,
11155                                       SelectionDAG &DAG) {
11156   assert(VT.isInteger() && "Only supports integer vector types!");
11157   MVT EltVT = VT.getVectorElementType();
11158   SDValue Zero = DAG.getConstant(0, DL, EltVT);
11159   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11160   SmallVector<SDValue, 16> MaskOps;
11161   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11162     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11163       return SDValue(); // Shuffled input!
11164     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11165   }
11166 
11167   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
11168   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
11169   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
11170   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
11171 }
11172 
11173 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
11174                                     SDValue PreservedSrc,
11175                                     const X86Subtarget &Subtarget,
11176                                     SelectionDAG &DAG);
11177 
matchShuffleAsBlend(SDValue V1,SDValue V2,MutableArrayRef<int> Mask,const APInt & Zeroable,bool & ForceV1Zero,bool & ForceV2Zero,uint64_t & BlendMask)11178 static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
11179                                 MutableArrayRef<int> Mask,
11180                                 const APInt &Zeroable, bool &ForceV1Zero,
11181                                 bool &ForceV2Zero, uint64_t &BlendMask) {
11182   bool V1IsZeroOrUndef =
11183       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11184   bool V2IsZeroOrUndef =
11185       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
11186 
11187   BlendMask = 0;
11188   ForceV1Zero = false, ForceV2Zero = false;
11189   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11190 
11191   // Attempt to generate the binary blend mask. If an input is zero then
11192   // we can use any lane.
11193   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11194     int M = Mask[i];
11195     if (M == SM_SentinelUndef)
11196       continue;
11197     if (M == i)
11198       continue;
11199     if (M == i + Size) {
11200       BlendMask |= 1ull << i;
11201       continue;
11202     }
11203     if (Zeroable[i]) {
11204       if (V1IsZeroOrUndef) {
11205         ForceV1Zero = true;
11206         Mask[i] = i;
11207         continue;
11208       }
11209       if (V2IsZeroOrUndef) {
11210         ForceV2Zero = true;
11211         BlendMask |= 1ull << i;
11212         Mask[i] = i + Size;
11213         continue;
11214       }
11215     }
11216     return false;
11217   }
11218   return true;
11219 }
11220 
scaleVectorShuffleBlendMask(uint64_t BlendMask,int Size,int Scale)11221 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
11222                                             int Scale) {
11223   uint64_t ScaledMask = 0;
11224   for (int i = 0; i != Size; ++i)
11225     if (BlendMask & (1ull << i))
11226       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
11227   return ScaledMask;
11228 }
11229 
11230 /// Try to emit a blend instruction for a shuffle.
11231 ///
11232 /// This doesn't do any checks for the availability of instructions for blending
11233 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11234 /// be matched in the backend with the type given. What it does check for is
11235 /// that the shuffle mask is a blend, or convertible into a blend with zero.
lowerShuffleAsBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Original,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11236 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
11237                                    SDValue V2, ArrayRef<int> Original,
11238                                    const APInt &Zeroable,
11239                                    const X86Subtarget &Subtarget,
11240                                    SelectionDAG &DAG) {
11241   uint64_t BlendMask = 0;
11242   bool ForceV1Zero = false, ForceV2Zero = false;
11243   SmallVector<int, 64> Mask(Original.begin(), Original.end());
11244   if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11245                            BlendMask))
11246     return SDValue();
11247 
11248   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11249   if (ForceV1Zero)
11250     V1 = getZeroVector(VT, Subtarget, DAG, DL);
11251   if (ForceV2Zero)
11252     V2 = getZeroVector(VT, Subtarget, DAG, DL);
11253 
11254   switch (VT.SimpleTy) {
11255   case MVT::v4i64:
11256   case MVT::v8i32:
11257     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11258     LLVM_FALLTHROUGH;
11259   case MVT::v4f64:
11260   case MVT::v8f32:
11261     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11262     LLVM_FALLTHROUGH;
11263   case MVT::v2f64:
11264   case MVT::v2i64:
11265   case MVT::v4f32:
11266   case MVT::v4i32:
11267   case MVT::v8i16:
11268     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
11269     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
11270                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11271   case MVT::v16i16: {
11272     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
11273     SmallVector<int, 8> RepeatedMask;
11274     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11275       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
11276       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
11277       BlendMask = 0;
11278       for (int i = 0; i < 8; ++i)
11279         if (RepeatedMask[i] >= 8)
11280           BlendMask |= 1ull << i;
11281       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11282                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11283     }
11284     // Use PBLENDW for lower/upper lanes and then blend lanes.
11285     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
11286     // merge to VSELECT where useful.
11287     uint64_t LoMask = BlendMask & 0xFF;
11288     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
11289     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
11290       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11291                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
11292       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11293                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
11294       return DAG.getVectorShuffle(
11295           MVT::v16i16, DL, Lo, Hi,
11296           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
11297     }
11298     LLVM_FALLTHROUGH;
11299   }
11300   case MVT::v32i8:
11301     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
11302     LLVM_FALLTHROUGH;
11303   case MVT::v16i8: {
11304     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
11305 
11306     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
11307     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
11308                                                Subtarget, DAG))
11309       return Masked;
11310 
11311     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
11312       MVT IntegerType =
11313           MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11314       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11315       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11316     }
11317 
11318     // Scale the blend by the number of bytes per element.
11319     int Scale = VT.getScalarSizeInBits() / 8;
11320 
11321     // This form of blend is always done on bytes. Compute the byte vector
11322     // type.
11323     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11324 
11325     // x86 allows load folding with blendvb from the 2nd source operand. But
11326     // we are still using LLVM select here (see comment below), so that's V1.
11327     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
11328     // allow that load-folding possibility.
11329     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
11330       ShuffleVectorSDNode::commuteMask(Mask);
11331       std::swap(V1, V2);
11332     }
11333 
11334     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
11335     // mix of LLVM's code generator and the x86 backend. We tell the code
11336     // generator that boolean values in the elements of an x86 vector register
11337     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
11338     // mapping a select to operand #1, and 'false' mapping to operand #2. The
11339     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
11340     // of the element (the remaining are ignored) and 0 in that high bit would
11341     // mean operand #1 while 1 in the high bit would mean operand #2. So while
11342     // the LLVM model for boolean values in vector elements gets the relevant
11343     // bit set, it is set backwards and over constrained relative to x86's
11344     // actual model.
11345     SmallVector<SDValue, 32> VSELECTMask;
11346     for (int i = 0, Size = Mask.size(); i < Size; ++i)
11347       for (int j = 0; j < Scale; ++j)
11348         VSELECTMask.push_back(
11349             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
11350                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
11351                                           MVT::i8));
11352 
11353     V1 = DAG.getBitcast(BlendVT, V1);
11354     V2 = DAG.getBitcast(BlendVT, V2);
11355     return DAG.getBitcast(
11356         VT,
11357         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
11358                       V1, V2));
11359   }
11360   case MVT::v16f32:
11361   case MVT::v8f64:
11362   case MVT::v8i64:
11363   case MVT::v16i32:
11364   case MVT::v32i16:
11365   case MVT::v64i8: {
11366     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
11367     bool OptForSize = DAG.shouldOptForSize();
11368     if (!OptForSize) {
11369       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
11370                                                  Subtarget, DAG))
11371         return Masked;
11372     }
11373 
11374     // Otherwise load an immediate into a GPR, cast to k-register, and use a
11375     // masked move.
11376     MVT IntegerType =
11377         MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11378     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11379     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11380   }
11381   default:
11382     llvm_unreachable("Not a supported integer vector type!");
11383   }
11384 }
11385 
11386 /// Try to lower as a blend of elements from two inputs followed by
11387 /// a single-input permutation.
11388 ///
11389 /// This matches the pattern where we can blend elements from two inputs and
11390 /// then reduce the shuffle to a single-input permutation.
lowerShuffleAsBlendAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,bool ImmBlends=false)11391 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
11392                                              SDValue V1, SDValue V2,
11393                                              ArrayRef<int> Mask,
11394                                              SelectionDAG &DAG,
11395                                              bool ImmBlends = false) {
11396   // We build up the blend mask while checking whether a blend is a viable way
11397   // to reduce the shuffle.
11398   SmallVector<int, 32> BlendMask(Mask.size(), -1);
11399   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
11400 
11401   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11402     if (Mask[i] < 0)
11403       continue;
11404 
11405     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
11406 
11407     if (BlendMask[Mask[i] % Size] < 0)
11408       BlendMask[Mask[i] % Size] = Mask[i];
11409     else if (BlendMask[Mask[i] % Size] != Mask[i])
11410       return SDValue(); // Can't blend in the needed input!
11411 
11412     PermuteMask[i] = Mask[i] % Size;
11413   }
11414 
11415   // If only immediate blends, then bail if the blend mask can't be widened to
11416   // i16.
11417   unsigned EltSize = VT.getScalarSizeInBits();
11418   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11419     return SDValue();
11420 
11421   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11422   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11423 }
11424 
11425 /// Try to lower as an unpack of elements from two inputs followed by
11426 /// a single-input permutation.
11427 ///
11428 /// This matches the pattern where we can unpack elements from two inputs and
11429 /// then reduce the shuffle to a single-input (wider) permutation.
lowerShuffleAsUNPCKAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)11430 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
11431                                              SDValue V1, SDValue V2,
11432                                              ArrayRef<int> Mask,
11433                                              SelectionDAG &DAG) {
11434   int NumElts = Mask.size();
11435   int NumLanes = VT.getSizeInBits() / 128;
11436   int NumLaneElts = NumElts / NumLanes;
11437   int NumHalfLaneElts = NumLaneElts / 2;
11438 
11439   bool MatchLo = true, MatchHi = true;
11440   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11441 
11442   // Determine UNPCKL/UNPCKH type and operand order.
11443   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11444     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
11445       int M = Mask[Lane + Elt];
11446       if (M < 0)
11447         continue;
11448 
11449       SDValue &Op = Ops[Elt & 1];
11450       if (M < NumElts && (Op.isUndef() || Op == V1))
11451         Op = V1;
11452       else if (NumElts <= M && (Op.isUndef() || Op == V2))
11453         Op = V2;
11454       else
11455         return SDValue();
11456 
11457       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11458       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
11459                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
11460       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
11461                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
11462       if (!MatchLo && !MatchHi)
11463         return SDValue();
11464     }
11465   }
11466   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11467 
11468   // Now check that each pair of elts come from the same unpack pair
11469   // and set the permute mask based on each pair.
11470   // TODO - Investigate cases where we permute individual elements.
11471   SmallVector<int, 32> PermuteMask(NumElts, -1);
11472   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11473     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
11474       int M0 = Mask[Lane + Elt + 0];
11475       int M1 = Mask[Lane + Elt + 1];
11476       if (0 <= M0 && 0 <= M1 &&
11477           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
11478         return SDValue();
11479       if (0 <= M0)
11480         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
11481       if (0 <= M1)
11482         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
11483     }
11484   }
11485 
11486   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11487   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11488   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11489 }
11490 
11491 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11492 /// permuting the elements of the result in place.
lowerShuffleAsByteRotateAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11493 static SDValue lowerShuffleAsByteRotateAndPermute(
11494     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11495     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11496   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11497       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11498       (VT.is512BitVector() && !Subtarget.hasBWI()))
11499     return SDValue();
11500 
11501   // We don't currently support lane crossing permutes.
11502   if (is128BitLaneCrossingShuffleMask(VT, Mask))
11503     return SDValue();
11504 
11505   int Scale = VT.getScalarSizeInBits() / 8;
11506   int NumLanes = VT.getSizeInBits() / 128;
11507   int NumElts = VT.getVectorNumElements();
11508   int NumEltsPerLane = NumElts / NumLanes;
11509 
11510   // Determine range of mask elts.
11511   bool Blend1 = true;
11512   bool Blend2 = true;
11513   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11514   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11515   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11516     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11517       int M = Mask[Lane + Elt];
11518       if (M < 0)
11519         continue;
11520       if (M < NumElts) {
11521         Blend1 &= (M == (Lane + Elt));
11522         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11523         M = M % NumEltsPerLane;
11524         Range1.first = std::min(Range1.first, M);
11525         Range1.second = std::max(Range1.second, M);
11526       } else {
11527         M -= NumElts;
11528         Blend2 &= (M == (Lane + Elt));
11529         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11530         M = M % NumEltsPerLane;
11531         Range2.first = std::min(Range2.first, M);
11532         Range2.second = std::max(Range2.second, M);
11533       }
11534     }
11535   }
11536 
11537   // Bail if we don't need both elements.
11538   // TODO - it might be worth doing this for unary shuffles if the permute
11539   // can be widened.
11540   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11541       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11542     return SDValue();
11543 
11544   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11545     return SDValue();
11546 
11547   // Rotate the 2 ops so we can access both ranges, then permute the result.
11548   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11549     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11550     SDValue Rotate = DAG.getBitcast(
11551         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11552                         DAG.getBitcast(ByteVT, Lo),
11553                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11554     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11555     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11556       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11557         int M = Mask[Lane + Elt];
11558         if (M < 0)
11559           continue;
11560         if (M < NumElts)
11561           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11562         else
11563           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
11564       }
11565     }
11566     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
11567   };
11568 
11569   // Check if the ranges are small enough to rotate from either direction.
11570   if (Range2.second < Range1.first)
11571     return RotateAndPermute(V1, V2, Range1.first, 0);
11572   if (Range1.second < Range2.first)
11573     return RotateAndPermute(V2, V1, Range2.first, NumElts);
11574   return SDValue();
11575 }
11576 
11577 /// Generic routine to decompose a shuffle and blend into independent
11578 /// blends and permutes.
11579 ///
11580 /// This matches the extremely common pattern for handling combined
11581 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11582 /// operations. It will try to pick the best arrangement of shuffles and
11583 /// blends.
lowerShuffleAsDecomposedShuffleBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11584 static SDValue lowerShuffleAsDecomposedShuffleBlend(
11585     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11586     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11587   // Shuffle the input elements into the desired positions in V1 and V2 and
11588   // blend them together.
11589   SmallVector<int, 32> V1Mask(Mask.size(), -1);
11590   SmallVector<int, 32> V2Mask(Mask.size(), -1);
11591   SmallVector<int, 32> BlendMask(Mask.size(), -1);
11592   for (int i = 0, Size = Mask.size(); i < Size; ++i)
11593     if (Mask[i] >= 0 && Mask[i] < Size) {
11594       V1Mask[i] = Mask[i];
11595       BlendMask[i] = i;
11596     } else if (Mask[i] >= Size) {
11597       V2Mask[i] = Mask[i] - Size;
11598       BlendMask[i] = i + Size;
11599     }
11600 
11601   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
11602   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
11603   // the shuffle may be able to fold with a load or other benefit. However, when
11604   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
11605   // pre-shuffle first is a better strategy.
11606   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
11607     // Only prefer immediate blends to unpack/rotate.
11608     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11609                                                           DAG, true))
11610       return BlendPerm;
11611     if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
11612                                                            DAG))
11613       return UnpackPerm;
11614     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
11615             DL, VT, V1, V2, Mask, Subtarget, DAG))
11616       return RotatePerm;
11617     // Unpack/rotate failed - try again with variable blends.
11618     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11619                                                           DAG))
11620       return BlendPerm;
11621   }
11622 
11623   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11624   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11625   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11626 }
11627 
11628 /// Try to lower a vector shuffle as a rotation.
11629 ///
11630 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
matchShuffleAsRotate(SDValue & V1,SDValue & V2,ArrayRef<int> Mask)11631 static int matchShuffleAsRotate(SDValue &V1, SDValue &V2, ArrayRef<int> Mask) {
11632   int NumElts = Mask.size();
11633 
11634   // We need to detect various ways of spelling a rotation:
11635   //   [11, 12, 13, 14, 15,  0,  1,  2]
11636   //   [-1, 12, 13, 14, -1, -1,  1, -1]
11637   //   [-1, -1, -1, -1, -1, -1,  1,  2]
11638   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
11639   //   [-1,  4,  5,  6, -1, -1,  9, -1]
11640   //   [-1,  4,  5,  6, -1, -1, -1, -1]
11641   int Rotation = 0;
11642   SDValue Lo, Hi;
11643   for (int i = 0; i < NumElts; ++i) {
11644     int M = Mask[i];
11645     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
11646            "Unexpected mask index.");
11647     if (M < 0)
11648       continue;
11649 
11650     // Determine where a rotated vector would have started.
11651     int StartIdx = i - (M % NumElts);
11652     if (StartIdx == 0)
11653       // The identity rotation isn't interesting, stop.
11654       return -1;
11655 
11656     // If we found the tail of a vector the rotation must be the missing
11657     // front. If we found the head of a vector, it must be how much of the
11658     // head.
11659     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
11660 
11661     if (Rotation == 0)
11662       Rotation = CandidateRotation;
11663     else if (Rotation != CandidateRotation)
11664       // The rotations don't match, so we can't match this mask.
11665       return -1;
11666 
11667     // Compute which value this mask is pointing at.
11668     SDValue MaskV = M < NumElts ? V1 : V2;
11669 
11670     // Compute which of the two target values this index should be assigned
11671     // to. This reflects whether the high elements are remaining or the low
11672     // elements are remaining.
11673     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
11674 
11675     // Either set up this value if we've not encountered it before, or check
11676     // that it remains consistent.
11677     if (!TargetV)
11678       TargetV = MaskV;
11679     else if (TargetV != MaskV)
11680       // This may be a rotation, but it pulls from the inputs in some
11681       // unsupported interleaving.
11682       return -1;
11683   }
11684 
11685   // Check that we successfully analyzed the mask, and normalize the results.
11686   assert(Rotation != 0 && "Failed to locate a viable rotation!");
11687   assert((Lo || Hi) && "Failed to find a rotated input vector!");
11688   if (!Lo)
11689     Lo = Hi;
11690   else if (!Hi)
11691     Hi = Lo;
11692 
11693   V1 = Lo;
11694   V2 = Hi;
11695 
11696   return Rotation;
11697 }
11698 
11699 /// Try to lower a vector shuffle as a byte rotation.
11700 ///
11701 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
11702 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
11703 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
11704 /// try to generically lower a vector shuffle through such an pattern. It
11705 /// does not check for the profitability of lowering either as PALIGNR or
11706 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
11707 /// This matches shuffle vectors that look like:
11708 ///
11709 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
11710 ///
11711 /// Essentially it concatenates V1 and V2, shifts right by some number of
11712 /// elements, and takes the low elements as the result. Note that while this is
11713 /// specified as a *right shift* because x86 is little-endian, it is a *left
11714 /// rotate* of the vector lanes.
matchShuffleAsByteRotate(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask)11715 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
11716                                     ArrayRef<int> Mask) {
11717   // Don't accept any shuffles with zero elements.
11718   if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
11719     return -1;
11720 
11721   // PALIGNR works on 128-bit lanes.
11722   SmallVector<int, 16> RepeatedMask;
11723   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
11724     return -1;
11725 
11726   int Rotation = matchShuffleAsRotate(V1, V2, RepeatedMask);
11727   if (Rotation <= 0)
11728     return -1;
11729 
11730   // PALIGNR rotates bytes, so we need to scale the
11731   // rotation based on how many bytes are in the vector lane.
11732   int NumElts = RepeatedMask.size();
11733   int Scale = 16 / NumElts;
11734   return Rotation * Scale;
11735 }
11736 
lowerShuffleAsByteRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11737 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
11738                                         SDValue V2, ArrayRef<int> Mask,
11739                                         const X86Subtarget &Subtarget,
11740                                         SelectionDAG &DAG) {
11741   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11742 
11743   SDValue Lo = V1, Hi = V2;
11744   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
11745   if (ByteRotation <= 0)
11746     return SDValue();
11747 
11748   // Cast the inputs to i8 vector of correct length to match PALIGNR or
11749   // PSLLDQ/PSRLDQ.
11750   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11751   Lo = DAG.getBitcast(ByteVT, Lo);
11752   Hi = DAG.getBitcast(ByteVT, Hi);
11753 
11754   // SSSE3 targets can use the palignr instruction.
11755   if (Subtarget.hasSSSE3()) {
11756     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
11757            "512-bit PALIGNR requires BWI instructions");
11758     return DAG.getBitcast(
11759         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
11760                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
11761   }
11762 
11763   assert(VT.is128BitVector() &&
11764          "Rotate-based lowering only supports 128-bit lowering!");
11765   assert(Mask.size() <= 16 &&
11766          "Can shuffle at most 16 bytes in a 128-bit vector!");
11767   assert(ByteVT == MVT::v16i8 &&
11768          "SSE2 rotate lowering only needed for v16i8!");
11769 
11770   // Default SSE2 implementation
11771   int LoByteShift = 16 - ByteRotation;
11772   int HiByteShift = ByteRotation;
11773 
11774   SDValue LoShift =
11775       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
11776                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
11777   SDValue HiShift =
11778       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
11779                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
11780   return DAG.getBitcast(VT,
11781                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
11782 }
11783 
11784 /// Try to lower a vector shuffle as a dword/qword rotation.
11785 ///
11786 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
11787 /// rotation of the concatenation of two vectors; This routine will
11788 /// try to generically lower a vector shuffle through such an pattern.
11789 ///
11790 /// Essentially it concatenates V1 and V2, shifts right by some number of
11791 /// elements, and takes the low elements as the result. Note that while this is
11792 /// specified as a *right shift* because x86 is little-endian, it is a *left
11793 /// rotate* of the vector lanes.
lowerShuffleAsRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11794 static SDValue lowerShuffleAsRotate(const SDLoc &DL, MVT VT, SDValue V1,
11795                                     SDValue V2, ArrayRef<int> Mask,
11796                                     const X86Subtarget &Subtarget,
11797                                     SelectionDAG &DAG) {
11798   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
11799          "Only 32-bit and 64-bit elements are supported!");
11800 
11801   // 128/256-bit vectors are only supported with VLX.
11802   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
11803          && "VLX required for 128/256-bit vectors");
11804 
11805   SDValue Lo = V1, Hi = V2;
11806   int Rotation = matchShuffleAsRotate(Lo, Hi, Mask);
11807   if (Rotation <= 0)
11808     return SDValue();
11809 
11810   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
11811                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
11812 }
11813 
11814 /// Try to lower a vector shuffle as a byte shift sequence.
lowerShuffleAsByteShiftMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11815 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
11816                                            SDValue V2, ArrayRef<int> Mask,
11817                                            const APInt &Zeroable,
11818                                            const X86Subtarget &Subtarget,
11819                                            SelectionDAG &DAG) {
11820   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11821   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
11822 
11823   // We need a shuffle that has zeros at one/both ends and a sequential
11824   // shuffle from one source within.
11825   unsigned ZeroLo = Zeroable.countTrailingOnes();
11826   unsigned ZeroHi = Zeroable.countLeadingOnes();
11827   if (!ZeroLo && !ZeroHi)
11828     return SDValue();
11829 
11830   unsigned NumElts = Mask.size();
11831   unsigned Len = NumElts - (ZeroLo + ZeroHi);
11832   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
11833     return SDValue();
11834 
11835   unsigned Scale = VT.getScalarSizeInBits() / 8;
11836   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
11837   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
11838       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
11839     return SDValue();
11840 
11841   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11842   Res = DAG.getBitcast(MVT::v16i8, Res);
11843 
11844   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
11845   // inner sequential set of elements, possibly offset:
11846   // 01234567 --> zzzzzz01 --> 1zzzzzzz
11847   // 01234567 --> 4567zzzz --> zzzzz456
11848   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
11849   if (ZeroLo == 0) {
11850     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11851     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11852                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11853     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11854                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
11855   } else if (ZeroHi == 0) {
11856     unsigned Shift = Mask[ZeroLo] % NumElts;
11857     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11858                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11859     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11860                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11861   } else if (!Subtarget.hasSSSE3()) {
11862     // If we don't have PSHUFB then its worth avoiding an AND constant mask
11863     // by performing 3 byte shifts. Shuffle combining can kick in above that.
11864     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
11865     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11866     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11867                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11868     Shift += Mask[ZeroLo] % NumElts;
11869     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11870                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11871     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11872                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11873   } else
11874     return SDValue();
11875 
11876   return DAG.getBitcast(VT, Res);
11877 }
11878 
11879 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
11880 ///
11881 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
11882 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
11883 /// matches elements from one of the input vectors shuffled to the left or
11884 /// right with zeroable elements 'shifted in'. It handles both the strictly
11885 /// bit-wise element shifts and the byte shift across an entire 128-bit double
11886 /// quad word lane.
11887 ///
11888 /// PSHL : (little-endian) left bit shift.
11889 /// [ zz, 0, zz,  2 ]
11890 /// [ -1, 4, zz, -1 ]
11891 /// PSRL : (little-endian) right bit shift.
11892 /// [  1, zz,  3, zz]
11893 /// [ -1, -1,  7, zz]
11894 /// PSLLDQ : (little-endian) left byte shift
11895 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
11896 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
11897 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
11898 /// PSRLDQ : (little-endian) right byte shift
11899 /// [  5, 6,  7, zz, zz, zz, zz, zz]
11900 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
11901 /// [  1, 2, -1, -1, -1, -1, zz, zz]
matchShuffleAsShift(MVT & ShiftVT,unsigned & Opcode,unsigned ScalarSizeInBits,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable,const X86Subtarget & Subtarget)11902 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
11903                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
11904                                int MaskOffset, const APInt &Zeroable,
11905                                const X86Subtarget &Subtarget) {
11906   int Size = Mask.size();
11907   unsigned SizeInBits = Size * ScalarSizeInBits;
11908 
11909   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
11910     for (int i = 0; i < Size; i += Scale)
11911       for (int j = 0; j < Shift; ++j)
11912         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
11913           return false;
11914 
11915     return true;
11916   };
11917 
11918   auto MatchShift = [&](int Shift, int Scale, bool Left) {
11919     for (int i = 0; i != Size; i += Scale) {
11920       unsigned Pos = Left ? i + Shift : i;
11921       unsigned Low = Left ? i : i + Shift;
11922       unsigned Len = Scale - Shift;
11923       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
11924         return -1;
11925     }
11926 
11927     int ShiftEltBits = ScalarSizeInBits * Scale;
11928     bool ByteShift = ShiftEltBits > 64;
11929     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
11930                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
11931     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
11932 
11933     // Normalize the scale for byte shifts to still produce an i64 element
11934     // type.
11935     Scale = ByteShift ? Scale / 2 : Scale;
11936 
11937     // We need to round trip through the appropriate type for the shift.
11938     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
11939     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
11940                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
11941     return (int)ShiftAmt;
11942   };
11943 
11944   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
11945   // keep doubling the size of the integer elements up to that. We can
11946   // then shift the elements of the integer vector by whole multiples of
11947   // their width within the elements of the larger integer vector. Test each
11948   // multiple to see if we can find a match with the moved element indices
11949   // and that the shifted in elements are all zeroable.
11950   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
11951   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
11952     for (int Shift = 1; Shift != Scale; ++Shift)
11953       for (bool Left : {true, false})
11954         if (CheckZeros(Shift, Scale, Left)) {
11955           int ShiftAmt = MatchShift(Shift, Scale, Left);
11956           if (0 < ShiftAmt)
11957             return ShiftAmt;
11958         }
11959 
11960   // no match
11961   return -1;
11962 }
11963 
lowerShuffleAsShift(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11964 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
11965                                    SDValue V2, ArrayRef<int> Mask,
11966                                    const APInt &Zeroable,
11967                                    const X86Subtarget &Subtarget,
11968                                    SelectionDAG &DAG) {
11969   int Size = Mask.size();
11970   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11971 
11972   MVT ShiftVT;
11973   SDValue V = V1;
11974   unsigned Opcode;
11975 
11976   // Try to match shuffle against V1 shift.
11977   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11978                                      Mask, 0, Zeroable, Subtarget);
11979 
11980   // If V1 failed, try to match shuffle against V2 shift.
11981   if (ShiftAmt < 0) {
11982     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11983                                    Mask, Size, Zeroable, Subtarget);
11984     V = V2;
11985   }
11986 
11987   if (ShiftAmt < 0)
11988     return SDValue();
11989 
11990   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
11991          "Illegal integer vector type");
11992   V = DAG.getBitcast(ShiftVT, V);
11993   V = DAG.getNode(Opcode, DL, ShiftVT, V,
11994                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
11995   return DAG.getBitcast(VT, V);
11996 }
11997 
11998 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
11999 // Remainder of lower half result is zero and upper half is all undef.
matchShuffleAsEXTRQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx,const APInt & Zeroable)12000 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
12001                                 ArrayRef<int> Mask, uint64_t &BitLen,
12002                                 uint64_t &BitIdx, const APInt &Zeroable) {
12003   int Size = Mask.size();
12004   int HalfSize = Size / 2;
12005   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12006   assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask");
12007 
12008   // Upper half must be undefined.
12009   if (!isUndefUpperHalf(Mask))
12010     return false;
12011 
12012   // Determine the extraction length from the part of the
12013   // lower half that isn't zeroable.
12014   int Len = HalfSize;
12015   for (; Len > 0; --Len)
12016     if (!Zeroable[Len - 1])
12017       break;
12018   assert(Len > 0 && "Zeroable shuffle mask");
12019 
12020   // Attempt to match first Len sequential elements from the lower half.
12021   SDValue Src;
12022   int Idx = -1;
12023   for (int i = 0; i != Len; ++i) {
12024     int M = Mask[i];
12025     if (M == SM_SentinelUndef)
12026       continue;
12027     SDValue &V = (M < Size ? V1 : V2);
12028     M = M % Size;
12029 
12030     // The extracted elements must start at a valid index and all mask
12031     // elements must be in the lower half.
12032     if (i > M || M >= HalfSize)
12033       return false;
12034 
12035     if (Idx < 0 || (Src == V && Idx == (M - i))) {
12036       Src = V;
12037       Idx = M - i;
12038       continue;
12039     }
12040     return false;
12041   }
12042 
12043   if (!Src || Idx < 0)
12044     return false;
12045 
12046   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12047   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12048   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12049   V1 = Src;
12050   return true;
12051 }
12052 
12053 // INSERTQ: Extract lowest Len elements from lower half of second source and
12054 // insert over first source, starting at Idx.
12055 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
matchShuffleAsINSERTQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx)12056 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
12057                                   ArrayRef<int> Mask, uint64_t &BitLen,
12058                                   uint64_t &BitIdx) {
12059   int Size = Mask.size();
12060   int HalfSize = Size / 2;
12061   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12062 
12063   // Upper half must be undefined.
12064   if (!isUndefUpperHalf(Mask))
12065     return false;
12066 
12067   for (int Idx = 0; Idx != HalfSize; ++Idx) {
12068     SDValue Base;
12069 
12070     // Attempt to match first source from mask before insertion point.
12071     if (isUndefInRange(Mask, 0, Idx)) {
12072       /* EMPTY */
12073     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12074       Base = V1;
12075     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12076       Base = V2;
12077     } else {
12078       continue;
12079     }
12080 
12081     // Extend the extraction length looking to match both the insertion of
12082     // the second source and the remaining elements of the first.
12083     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12084       SDValue Insert;
12085       int Len = Hi - Idx;
12086 
12087       // Match insertion.
12088       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12089         Insert = V1;
12090       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12091         Insert = V2;
12092       } else {
12093         continue;
12094       }
12095 
12096       // Match the remaining elements of the lower half.
12097       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12098         /* EMPTY */
12099       } else if ((!Base || (Base == V1)) &&
12100                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12101         Base = V1;
12102       } else if ((!Base || (Base == V2)) &&
12103                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12104                                             Size + Hi)) {
12105         Base = V2;
12106       } else {
12107         continue;
12108       }
12109 
12110       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12111       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12112       V1 = Base;
12113       V2 = Insert;
12114       return true;
12115     }
12116   }
12117 
12118   return false;
12119 }
12120 
12121 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
lowerShuffleWithSSE4A(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)12122 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
12123                                      SDValue V2, ArrayRef<int> Mask,
12124                                      const APInt &Zeroable, SelectionDAG &DAG) {
12125   uint64_t BitLen, BitIdx;
12126   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12127     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12128                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12129                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12130 
12131   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12132     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12133                        V2 ? V2 : DAG.getUNDEF(VT),
12134                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12135                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12136 
12137   return SDValue();
12138 }
12139 
12140 /// Lower a vector shuffle as a zero or any extension.
12141 ///
12142 /// Given a specific number of elements, element bit width, and extension
12143 /// stride, produce either a zero or any extension based on the available
12144 /// features of the subtarget. The extended elements are consecutive and
12145 /// begin and can start from an offsetted element index in the input; to
12146 /// avoid excess shuffling the offset must either being in the bottom lane
12147 /// or at the start of a higher lane. All extended elements must be from
12148 /// the same lane.
lowerShuffleAsSpecificZeroOrAnyExtend(const SDLoc & DL,MVT VT,int Scale,int Offset,bool AnyExt,SDValue InputV,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12149 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
12150     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
12151     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12152   assert(Scale > 1 && "Need a scale to extend.");
12153   int EltBits = VT.getScalarSizeInBits();
12154   int NumElements = VT.getVectorNumElements();
12155   int NumEltsPerLane = 128 / EltBits;
12156   int OffsetLane = Offset / NumEltsPerLane;
12157   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12158          "Only 8, 16, and 32 bit elements can be extended.");
12159   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12160   assert(0 <= Offset && "Extension offset must be positive.");
12161   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12162          "Extension offset must be in the first lane or start an upper lane.");
12163 
12164   // Check that an index is in same lane as the base offset.
12165   auto SafeOffset = [&](int Idx) {
12166     return OffsetLane == (Idx / NumEltsPerLane);
12167   };
12168 
12169   // Shift along an input so that the offset base moves to the first element.
12170   auto ShuffleOffset = [&](SDValue V) {
12171     if (!Offset)
12172       return V;
12173 
12174     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12175     for (int i = 0; i * Scale < NumElements; ++i) {
12176       int SrcIdx = i + Offset;
12177       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12178     }
12179     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12180   };
12181 
12182   // Found a valid a/zext mask! Try various lowering strategies based on the
12183   // input type and available ISA extensions.
12184   if (Subtarget.hasSSE41()) {
12185     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12186     // PUNPCK will catch this in a later shuffle match.
12187     if (Offset && Scale == 2 && VT.is128BitVector())
12188       return SDValue();
12189     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12190                                  NumElements / Scale);
12191     InputV = ShuffleOffset(InputV);
12192     InputV = getExtendInVec(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND, DL,
12193                             ExtVT, InputV, DAG);
12194     return DAG.getBitcast(VT, InputV);
12195   }
12196 
12197   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12198 
12199   // For any extends we can cheat for larger element sizes and use shuffle
12200   // instructions that can fold with a load and/or copy.
12201   if (AnyExt && EltBits == 32) {
12202     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12203                          -1};
12204     return DAG.getBitcast(
12205         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12206                         DAG.getBitcast(MVT::v4i32, InputV),
12207                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12208   }
12209   if (AnyExt && EltBits == 16 && Scale > 2) {
12210     int PSHUFDMask[4] = {Offset / 2, -1,
12211                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12212     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12213                          DAG.getBitcast(MVT::v4i32, InputV),
12214                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12215     int PSHUFWMask[4] = {1, -1, -1, -1};
12216     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12217     return DAG.getBitcast(
12218         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12219                         DAG.getBitcast(MVT::v8i16, InputV),
12220                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12221   }
12222 
12223   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12224   // to 64-bits.
12225   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12226     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12227     assert(VT.is128BitVector() && "Unexpected vector width!");
12228 
12229     int LoIdx = Offset * EltBits;
12230     SDValue Lo = DAG.getBitcast(
12231         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12232                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12233                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12234 
12235     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12236       return DAG.getBitcast(VT, Lo);
12237 
12238     int HiIdx = (Offset + 1) * EltBits;
12239     SDValue Hi = DAG.getBitcast(
12240         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12241                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12242                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12243     return DAG.getBitcast(VT,
12244                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12245   }
12246 
12247   // If this would require more than 2 unpack instructions to expand, use
12248   // pshufb when available. We can only use more than 2 unpack instructions
12249   // when zero extending i8 elements which also makes it easier to use pshufb.
12250   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12251     assert(NumElements == 16 && "Unexpected byte vector width!");
12252     SDValue PSHUFBMask[16];
12253     for (int i = 0; i < 16; ++i) {
12254       int Idx = Offset + (i / Scale);
12255       if ((i % Scale == 0 && SafeOffset(Idx))) {
12256         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12257         continue;
12258       }
12259       PSHUFBMask[i] =
12260           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12261     }
12262     InputV = DAG.getBitcast(MVT::v16i8, InputV);
12263     return DAG.getBitcast(
12264         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12265                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12266   }
12267 
12268   // If we are extending from an offset, ensure we start on a boundary that
12269   // we can unpack from.
12270   int AlignToUnpack = Offset % (NumElements / Scale);
12271   if (AlignToUnpack) {
12272     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12273     for (int i = AlignToUnpack; i < NumElements; ++i)
12274       ShMask[i - AlignToUnpack] = i;
12275     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12276     Offset -= AlignToUnpack;
12277   }
12278 
12279   // Otherwise emit a sequence of unpacks.
12280   do {
12281     unsigned UnpackLoHi = X86ISD::UNPCKL;
12282     if (Offset >= (NumElements / 2)) {
12283       UnpackLoHi = X86ISD::UNPCKH;
12284       Offset -= (NumElements / 2);
12285     }
12286 
12287     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12288     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12289                          : getZeroVector(InputVT, Subtarget, DAG, DL);
12290     InputV = DAG.getBitcast(InputVT, InputV);
12291     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12292     Scale /= 2;
12293     EltBits *= 2;
12294     NumElements /= 2;
12295   } while (Scale > 1);
12296   return DAG.getBitcast(VT, InputV);
12297 }
12298 
12299 /// Try to lower a vector shuffle as a zero extension on any microarch.
12300 ///
12301 /// This routine will try to do everything in its power to cleverly lower
12302 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
12303 /// check for the profitability of this lowering,  it tries to aggressively
12304 /// match this pattern. It will use all of the micro-architectural details it
12305 /// can to emit an efficient lowering. It handles both blends with all-zero
12306 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12307 /// masking out later).
12308 ///
12309 /// The reason we have dedicated lowering for zext-style shuffles is that they
12310 /// are both incredibly common and often quite performance sensitive.
lowerShuffleAsZeroOrAnyExtend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)12311 static SDValue lowerShuffleAsZeroOrAnyExtend(
12312     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12313     const APInt &Zeroable, const X86Subtarget &Subtarget,
12314     SelectionDAG &DAG) {
12315   int Bits = VT.getSizeInBits();
12316   int NumLanes = Bits / 128;
12317   int NumElements = VT.getVectorNumElements();
12318   int NumEltsPerLane = NumElements / NumLanes;
12319   assert(VT.getScalarSizeInBits() <= 32 &&
12320          "Exceeds 32-bit integer zero extension limit");
12321   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12322 
12323   // Define a helper function to check a particular ext-scale and lower to it if
12324   // valid.
12325   auto Lower = [&](int Scale) -> SDValue {
12326     SDValue InputV;
12327     bool AnyExt = true;
12328     int Offset = 0;
12329     int Matches = 0;
12330     for (int i = 0; i < NumElements; ++i) {
12331       int M = Mask[i];
12332       if (M < 0)
12333         continue; // Valid anywhere but doesn't tell us anything.
12334       if (i % Scale != 0) {
12335         // Each of the extended elements need to be zeroable.
12336         if (!Zeroable[i])
12337           return SDValue();
12338 
12339         // We no longer are in the anyext case.
12340         AnyExt = false;
12341         continue;
12342       }
12343 
12344       // Each of the base elements needs to be consecutive indices into the
12345       // same input vector.
12346       SDValue V = M < NumElements ? V1 : V2;
12347       M = M % NumElements;
12348       if (!InputV) {
12349         InputV = V;
12350         Offset = M - (i / Scale);
12351       } else if (InputV != V)
12352         return SDValue(); // Flip-flopping inputs.
12353 
12354       // Offset must start in the lowest 128-bit lane or at the start of an
12355       // upper lane.
12356       // FIXME: Is it ever worth allowing a negative base offset?
12357       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12358             (Offset % NumEltsPerLane) == 0))
12359         return SDValue();
12360 
12361       // If we are offsetting, all referenced entries must come from the same
12362       // lane.
12363       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12364         return SDValue();
12365 
12366       if ((M % NumElements) != (Offset + (i / Scale)))
12367         return SDValue(); // Non-consecutive strided elements.
12368       Matches++;
12369     }
12370 
12371     // If we fail to find an input, we have a zero-shuffle which should always
12372     // have already been handled.
12373     // FIXME: Maybe handle this here in case during blending we end up with one?
12374     if (!InputV)
12375       return SDValue();
12376 
12377     // If we are offsetting, don't extend if we only match a single input, we
12378     // can always do better by using a basic PSHUF or PUNPCK.
12379     if (Offset != 0 && Matches < 2)
12380       return SDValue();
12381 
12382     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
12383                                                  InputV, Mask, Subtarget, DAG);
12384   };
12385 
12386   // The widest scale possible for extending is to a 64-bit integer.
12387   assert(Bits % 64 == 0 &&
12388          "The number of bits in a vector must be divisible by 64 on x86!");
12389   int NumExtElements = Bits / 64;
12390 
12391   // Each iteration, try extending the elements half as much, but into twice as
12392   // many elements.
12393   for (; NumExtElements < NumElements; NumExtElements *= 2) {
12394     assert(NumElements % NumExtElements == 0 &&
12395            "The input vector size must be divisible by the extended size.");
12396     if (SDValue V = Lower(NumElements / NumExtElements))
12397       return V;
12398   }
12399 
12400   // General extends failed, but 128-bit vectors may be able to use MOVQ.
12401   if (Bits != 128)
12402     return SDValue();
12403 
12404   // Returns one of the source operands if the shuffle can be reduced to a
12405   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
12406   auto CanZExtLowHalf = [&]() {
12407     for (int i = NumElements / 2; i != NumElements; ++i)
12408       if (!Zeroable[i])
12409         return SDValue();
12410     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
12411       return V1;
12412     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
12413       return V2;
12414     return SDValue();
12415   };
12416 
12417   if (SDValue V = CanZExtLowHalf()) {
12418     V = DAG.getBitcast(MVT::v2i64, V);
12419     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
12420     return DAG.getBitcast(VT, V);
12421   }
12422 
12423   // No viable ext lowering found.
12424   return SDValue();
12425 }
12426 
12427 /// Try to get a scalar value for a specific element of a vector.
12428 ///
12429 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
getScalarValueForVectorElement(SDValue V,int Idx,SelectionDAG & DAG)12430 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
12431                                               SelectionDAG &DAG) {
12432   MVT VT = V.getSimpleValueType();
12433   MVT EltVT = VT.getVectorElementType();
12434   V = peekThroughBitcasts(V);
12435 
12436   // If the bitcasts shift the element size, we can't extract an equivalent
12437   // element from it.
12438   MVT NewVT = V.getSimpleValueType();
12439   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
12440     return SDValue();
12441 
12442   if (V.getOpcode() == ISD::BUILD_VECTOR ||
12443       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
12444     // Ensure the scalar operand is the same size as the destination.
12445     // FIXME: Add support for scalar truncation where possible.
12446     SDValue S = V.getOperand(Idx);
12447     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
12448       return DAG.getBitcast(EltVT, S);
12449   }
12450 
12451   return SDValue();
12452 }
12453 
12454 /// Helper to test for a load that can be folded with x86 shuffles.
12455 ///
12456 /// This is particularly important because the set of instructions varies
12457 /// significantly based on whether the operand is a load or not.
isShuffleFoldableLoad(SDValue V)12458 static bool isShuffleFoldableLoad(SDValue V) {
12459   V = peekThroughBitcasts(V);
12460   return ISD::isNON_EXTLoad(V.getNode());
12461 }
12462 
12463 /// Try to lower insertion of a single element into a zero vector.
12464 ///
12465 /// This is a common pattern that we have especially efficient patterns to lower
12466 /// across all subtarget feature sets.
lowerShuffleAsElementInsertion(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)12467 static SDValue lowerShuffleAsElementInsertion(
12468     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12469     const APInt &Zeroable, const X86Subtarget &Subtarget,
12470     SelectionDAG &DAG) {
12471   MVT ExtVT = VT;
12472   MVT EltVT = VT.getVectorElementType();
12473 
12474   int V2Index =
12475       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
12476       Mask.begin();
12477   bool IsV1Zeroable = true;
12478   for (int i = 0, Size = Mask.size(); i < Size; ++i)
12479     if (i != V2Index && !Zeroable[i]) {
12480       IsV1Zeroable = false;
12481       break;
12482     }
12483 
12484   // Check for a single input from a SCALAR_TO_VECTOR node.
12485   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
12486   // all the smarts here sunk into that routine. However, the current
12487   // lowering of BUILD_VECTOR makes that nearly impossible until the old
12488   // vector shuffle lowering is dead.
12489   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
12490                                                DAG);
12491   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
12492     // We need to zext the scalar if it is smaller than an i32.
12493     V2S = DAG.getBitcast(EltVT, V2S);
12494     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
12495       // Using zext to expand a narrow element won't work for non-zero
12496       // insertions.
12497       if (!IsV1Zeroable)
12498         return SDValue();
12499 
12500       // Zero-extend directly to i32.
12501       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
12502       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
12503     }
12504     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
12505   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
12506              EltVT == MVT::i16) {
12507     // Either not inserting from the low element of the input or the input
12508     // element size is too small to use VZEXT_MOVL to clear the high bits.
12509     return SDValue();
12510   }
12511 
12512   if (!IsV1Zeroable) {
12513     // If V1 can't be treated as a zero vector we have fewer options to lower
12514     // this. We can't support integer vectors or non-zero targets cheaply, and
12515     // the V1 elements can't be permuted in any way.
12516     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
12517     if (!VT.isFloatingPoint() || V2Index != 0)
12518       return SDValue();
12519     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
12520     V1Mask[V2Index] = -1;
12521     if (!isNoopShuffleMask(V1Mask))
12522       return SDValue();
12523     if (!VT.is128BitVector())
12524       return SDValue();
12525 
12526     // Otherwise, use MOVSD or MOVSS.
12527     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
12528            "Only two types of floating point element types to handle!");
12529     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
12530                        ExtVT, V1, V2);
12531   }
12532 
12533   // This lowering only works for the low element with floating point vectors.
12534   if (VT.isFloatingPoint() && V2Index != 0)
12535     return SDValue();
12536 
12537   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
12538   if (ExtVT != VT)
12539     V2 = DAG.getBitcast(VT, V2);
12540 
12541   if (V2Index != 0) {
12542     // If we have 4 or fewer lanes we can cheaply shuffle the element into
12543     // the desired position. Otherwise it is more efficient to do a vector
12544     // shift left. We know that we can do a vector shift left because all
12545     // the inputs are zero.
12546     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
12547       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
12548       V2Shuffle[V2Index] = 0;
12549       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
12550     } else {
12551       V2 = DAG.getBitcast(MVT::v16i8, V2);
12552       V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
12553                        DAG.getTargetConstant(
12554                            V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
12555       V2 = DAG.getBitcast(VT, V2);
12556     }
12557   }
12558   return V2;
12559 }
12560 
12561 /// Try to lower broadcast of a single - truncated - integer element,
12562 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
12563 ///
12564 /// This assumes we have AVX2.
lowerShuffleAsTruncBroadcast(const SDLoc & DL,MVT VT,SDValue V0,int BroadcastIdx,const X86Subtarget & Subtarget,SelectionDAG & DAG)12565 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
12566                                             int BroadcastIdx,
12567                                             const X86Subtarget &Subtarget,
12568                                             SelectionDAG &DAG) {
12569   assert(Subtarget.hasAVX2() &&
12570          "We can only lower integer broadcasts with AVX2!");
12571 
12572   EVT EltVT = VT.getVectorElementType();
12573   EVT V0VT = V0.getValueType();
12574 
12575   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
12576   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
12577 
12578   EVT V0EltVT = V0VT.getVectorElementType();
12579   if (!V0EltVT.isInteger())
12580     return SDValue();
12581 
12582   const unsigned EltSize = EltVT.getSizeInBits();
12583   const unsigned V0EltSize = V0EltVT.getSizeInBits();
12584 
12585   // This is only a truncation if the original element type is larger.
12586   if (V0EltSize <= EltSize)
12587     return SDValue();
12588 
12589   assert(((V0EltSize % EltSize) == 0) &&
12590          "Scalar type sizes must all be powers of 2 on x86!");
12591 
12592   const unsigned V0Opc = V0.getOpcode();
12593   const unsigned Scale = V0EltSize / EltSize;
12594   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
12595 
12596   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
12597       V0Opc != ISD::BUILD_VECTOR)
12598     return SDValue();
12599 
12600   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
12601 
12602   // If we're extracting non-least-significant bits, shift so we can truncate.
12603   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
12604   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
12605   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
12606   if (const int OffsetIdx = BroadcastIdx % Scale)
12607     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
12608                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
12609 
12610   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
12611                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
12612 }
12613 
12614 /// Test whether this can be lowered with a single SHUFPS instruction.
12615 ///
12616 /// This is used to disable more specialized lowerings when the shufps lowering
12617 /// will happen to be efficient.
isSingleSHUFPSMask(ArrayRef<int> Mask)12618 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
12619   // This routine only handles 128-bit shufps.
12620   assert(Mask.size() == 4 && "Unsupported mask size!");
12621   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
12622   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
12623   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
12624   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
12625 
12626   // To lower with a single SHUFPS we need to have the low half and high half
12627   // each requiring a single input.
12628   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
12629     return false;
12630   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
12631     return false;
12632 
12633   return true;
12634 }
12635 
12636 /// If we are extracting two 128-bit halves of a vector and shuffling the
12637 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
12638 /// multi-shuffle lowering.
lowerShuffleOfExtractsAsVperm(const SDLoc & DL,SDValue N0,SDValue N1,ArrayRef<int> Mask,SelectionDAG & DAG)12639 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
12640                                              SDValue N1, ArrayRef<int> Mask,
12641                                              SelectionDAG &DAG) {
12642   EVT VT = N0.getValueType();
12643   assert((VT.is128BitVector() &&
12644           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
12645          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
12646 
12647   // Check that both sources are extracts of the same source vector.
12648   if (!N0.hasOneUse() || !N1.hasOneUse() ||
12649       N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12650       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12651       N0.getOperand(0) != N1.getOperand(0))
12652     return SDValue();
12653 
12654   SDValue WideVec = N0.getOperand(0);
12655   EVT WideVT = WideVec.getValueType();
12656   if (!WideVT.is256BitVector() || !isa<ConstantSDNode>(N0.getOperand(1)) ||
12657       !isa<ConstantSDNode>(N1.getOperand(1)))
12658     return SDValue();
12659 
12660   // Match extracts of each half of the wide source vector. Commute the shuffle
12661   // if the extract of the low half is N1.
12662   unsigned NumElts = VT.getVectorNumElements();
12663   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
12664   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
12665   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
12666   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
12667     ShuffleVectorSDNode::commuteMask(NewMask);
12668   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
12669     return SDValue();
12670 
12671   // Final bailout: if the mask is simple, we are better off using an extract
12672   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
12673   // because that avoids a constant load from memory.
12674   if (NumElts == 4 &&
12675       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
12676     return SDValue();
12677 
12678   // Extend the shuffle mask with undef elements.
12679   NewMask.append(NumElts, -1);
12680 
12681   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
12682   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
12683                                       NewMask);
12684   // This is free: ymm -> xmm.
12685   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
12686                      DAG.getIntPtrConstant(0, DL));
12687 }
12688 
12689 /// Try to lower broadcast of a single element.
12690 ///
12691 /// For convenience, this code also bundles all of the subtarget feature set
12692 /// filtering. While a little annoying to re-dispatch on type here, there isn't
12693 /// a convenient way to factor it out.
lowerShuffleAsBroadcast(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12694 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
12695                                        SDValue V2, ArrayRef<int> Mask,
12696                                        const X86Subtarget &Subtarget,
12697                                        SelectionDAG &DAG) {
12698   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
12699         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
12700         (Subtarget.hasAVX2() && VT.isInteger())))
12701     return SDValue();
12702 
12703   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
12704   // we can only broadcast from a register with AVX2.
12705   unsigned NumElts = Mask.size();
12706   unsigned NumEltBits = VT.getScalarSizeInBits();
12707   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
12708                         ? X86ISD::MOVDDUP
12709                         : X86ISD::VBROADCAST;
12710   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
12711 
12712   // Check that the mask is a broadcast.
12713   int BroadcastIdx = -1;
12714   for (int i = 0; i != (int)NumElts; ++i) {
12715     SmallVector<int, 8> BroadcastMask(NumElts, i);
12716     if (isShuffleEquivalent(V1, V2, Mask, BroadcastMask)) {
12717       BroadcastIdx = i;
12718       break;
12719     }
12720   }
12721 
12722   if (BroadcastIdx < 0)
12723     return SDValue();
12724   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
12725                                             "a sorted mask where the broadcast "
12726                                             "comes from V1.");
12727 
12728   // Go up the chain of (vector) values to find a scalar load that we can
12729   // combine with the broadcast.
12730   int BitOffset = BroadcastIdx * NumEltBits;
12731   SDValue V = V1;
12732   for (;;) {
12733     switch (V.getOpcode()) {
12734     case ISD::BITCAST: {
12735       V = V.getOperand(0);
12736       continue;
12737     }
12738     case ISD::CONCAT_VECTORS: {
12739       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
12740       int OpIdx = BitOffset / OpBitWidth;
12741       V = V.getOperand(OpIdx);
12742       BitOffset %= OpBitWidth;
12743       continue;
12744     }
12745     case ISD::INSERT_SUBVECTOR: {
12746       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
12747       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
12748       if (!ConstantIdx)
12749         break;
12750 
12751       int EltBitWidth = VOuter.getScalarValueSizeInBits();
12752       int Idx = (int)ConstantIdx->getZExtValue();
12753       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
12754       int BeginOffset = Idx * EltBitWidth;
12755       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
12756       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
12757         BitOffset -= BeginOffset;
12758         V = VInner;
12759       } else {
12760         V = VOuter;
12761       }
12762       continue;
12763     }
12764     }
12765     break;
12766   }
12767   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
12768   BroadcastIdx = BitOffset / NumEltBits;
12769 
12770   // Do we need to bitcast the source to retrieve the original broadcast index?
12771   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
12772 
12773   // Check if this is a broadcast of a scalar. We special case lowering
12774   // for scalars so that we can more effectively fold with loads.
12775   // If the original value has a larger element type than the shuffle, the
12776   // broadcast element is in essence truncated. Make that explicit to ease
12777   // folding.
12778   if (BitCastSrc && VT.isInteger())
12779     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
12780             DL, VT, V, BroadcastIdx, Subtarget, DAG))
12781       return TruncBroadcast;
12782 
12783   MVT BroadcastVT = VT;
12784 
12785   // Also check the simpler case, where we can directly reuse the scalar.
12786   if (!BitCastSrc &&
12787       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
12788        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
12789     V = V.getOperand(BroadcastIdx);
12790 
12791     // If we can't broadcast from a register, check that the input is a load.
12792     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
12793       return SDValue();
12794   } else if (MayFoldLoad(V) && cast<LoadSDNode>(V)->isSimple()) {
12795     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
12796     if (!Subtarget.is64Bit() && VT.getScalarType() == MVT::i64) {
12797       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
12798       Opcode = (BroadcastVT.is128BitVector() && !Subtarget.hasAVX2())
12799                    ? X86ISD::MOVDDUP
12800                    : Opcode;
12801     }
12802 
12803     // If we are broadcasting a load that is only used by the shuffle
12804     // then we can reduce the vector load to the broadcasted scalar load.
12805     LoadSDNode *Ld = cast<LoadSDNode>(V);
12806     SDValue BaseAddr = Ld->getOperand(1);
12807     EVT SVT = BroadcastVT.getScalarType();
12808     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
12809     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
12810     SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
12811     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
12812                     DAG.getMachineFunction().getMachineMemOperand(
12813                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12814     DAG.makeEquivalentMemoryOrdering(Ld, V);
12815   } else if (!BroadcastFromReg) {
12816     // We can't broadcast from a vector register.
12817     return SDValue();
12818   } else if (BitOffset != 0) {
12819     // We can only broadcast from the zero-element of a vector register,
12820     // but it can be advantageous to broadcast from the zero-element of a
12821     // subvector.
12822     if (!VT.is256BitVector() && !VT.is512BitVector())
12823       return SDValue();
12824 
12825     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
12826     if (VT == MVT::v4f64 || VT == MVT::v4i64)
12827       return SDValue();
12828 
12829     // Only broadcast the zero-element of a 128-bit subvector.
12830     if ((BitOffset % 128) != 0)
12831       return SDValue();
12832 
12833     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
12834            "Unexpected bit-offset");
12835     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
12836            "Unexpected vector size");
12837     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
12838     V = extract128BitVector(V, ExtractIdx, DAG, DL);
12839   }
12840 
12841   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
12842     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
12843                     DAG.getBitcast(MVT::f64, V));
12844 
12845   // Bitcast back to the same scalar type as BroadcastVT.
12846   if (V.getValueType().getScalarType() != BroadcastVT.getScalarType()) {
12847     assert(NumEltBits == BroadcastVT.getScalarSizeInBits() &&
12848            "Unexpected vector element size");
12849     MVT ExtVT;
12850     if (V.getValueType().isVector()) {
12851       unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
12852       ExtVT = MVT::getVectorVT(BroadcastVT.getScalarType(), NumSrcElts);
12853     } else {
12854       ExtVT = BroadcastVT.getScalarType();
12855     }
12856     V = DAG.getBitcast(ExtVT, V);
12857   }
12858 
12859   // 32-bit targets need to load i64 as a f64 and then bitcast the result.
12860   if (!Subtarget.is64Bit() && V.getValueType() == MVT::i64) {
12861     V = DAG.getBitcast(MVT::f64, V);
12862     unsigned NumBroadcastElts = BroadcastVT.getVectorNumElements();
12863     BroadcastVT = MVT::getVectorVT(MVT::f64, NumBroadcastElts);
12864   }
12865 
12866   // We only support broadcasting from 128-bit vectors to minimize the
12867   // number of patterns we need to deal with in isel. So extract down to
12868   // 128-bits, removing as many bitcasts as possible.
12869   if (V.getValueSizeInBits() > 128) {
12870     MVT ExtVT = V.getSimpleValueType().getScalarType();
12871     ExtVT = MVT::getVectorVT(ExtVT, 128 / ExtVT.getScalarSizeInBits());
12872     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
12873     V = DAG.getBitcast(ExtVT, V);
12874   }
12875 
12876   return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
12877 }
12878 
12879 // Check for whether we can use INSERTPS to perform the shuffle. We only use
12880 // INSERTPS when the V1 elements are already in the correct locations
12881 // because otherwise we can just always use two SHUFPS instructions which
12882 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
12883 // perform INSERTPS if a single V1 element is out of place and all V2
12884 // elements are zeroable.
matchShuffleAsInsertPS(SDValue & V1,SDValue & V2,unsigned & InsertPSMask,const APInt & Zeroable,ArrayRef<int> Mask,SelectionDAG & DAG)12885 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
12886                                    unsigned &InsertPSMask,
12887                                    const APInt &Zeroable,
12888                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
12889   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
12890   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
12891   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12892 
12893   // Attempt to match INSERTPS with one element from VA or VB being
12894   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
12895   // are updated.
12896   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
12897                              ArrayRef<int> CandidateMask) {
12898     unsigned ZMask = 0;
12899     int VADstIndex = -1;
12900     int VBDstIndex = -1;
12901     bool VAUsedInPlace = false;
12902 
12903     for (int i = 0; i < 4; ++i) {
12904       // Synthesize a zero mask from the zeroable elements (includes undefs).
12905       if (Zeroable[i]) {
12906         ZMask |= 1 << i;
12907         continue;
12908       }
12909 
12910       // Flag if we use any VA inputs in place.
12911       if (i == CandidateMask[i]) {
12912         VAUsedInPlace = true;
12913         continue;
12914       }
12915 
12916       // We can only insert a single non-zeroable element.
12917       if (VADstIndex >= 0 || VBDstIndex >= 0)
12918         return false;
12919 
12920       if (CandidateMask[i] < 4) {
12921         // VA input out of place for insertion.
12922         VADstIndex = i;
12923       } else {
12924         // VB input for insertion.
12925         VBDstIndex = i;
12926       }
12927     }
12928 
12929     // Don't bother if we have no (non-zeroable) element for insertion.
12930     if (VADstIndex < 0 && VBDstIndex < 0)
12931       return false;
12932 
12933     // Determine element insertion src/dst indices. The src index is from the
12934     // start of the inserted vector, not the start of the concatenated vector.
12935     unsigned VBSrcIndex = 0;
12936     if (VADstIndex >= 0) {
12937       // If we have a VA input out of place, we use VA as the V2 element
12938       // insertion and don't use the original V2 at all.
12939       VBSrcIndex = CandidateMask[VADstIndex];
12940       VBDstIndex = VADstIndex;
12941       VB = VA;
12942     } else {
12943       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
12944     }
12945 
12946     // If no V1 inputs are used in place, then the result is created only from
12947     // the zero mask and the V2 insertion - so remove V1 dependency.
12948     if (!VAUsedInPlace)
12949       VA = DAG.getUNDEF(MVT::v4f32);
12950 
12951     // Update V1, V2 and InsertPSMask accordingly.
12952     V1 = VA;
12953     V2 = VB;
12954 
12955     // Insert the V2 element into the desired position.
12956     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
12957     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
12958     return true;
12959   };
12960 
12961   if (matchAsInsertPS(V1, V2, Mask))
12962     return true;
12963 
12964   // Commute and try again.
12965   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
12966   ShuffleVectorSDNode::commuteMask(CommutedMask);
12967   if (matchAsInsertPS(V2, V1, CommutedMask))
12968     return true;
12969 
12970   return false;
12971 }
12972 
lowerShuffleAsInsertPS(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)12973 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
12974                                       ArrayRef<int> Mask, const APInt &Zeroable,
12975                                       SelectionDAG &DAG) {
12976   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12977   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12978 
12979   // Attempt to match the insertps pattern.
12980   unsigned InsertPSMask;
12981   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
12982     return SDValue();
12983 
12984   // Insert the V2 element into the desired position.
12985   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
12986                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
12987 }
12988 
12989 /// Try to lower a shuffle as a permute of the inputs followed by an
12990 /// UNPCK instruction.
12991 ///
12992 /// This specifically targets cases where we end up with alternating between
12993 /// the two inputs, and so can permute them into something that feeds a single
12994 /// UNPCK instruction. Note that this routine only targets integer vectors
12995 /// because for floating point vectors we have a generalized SHUFPS lowering
12996 /// strategy that handles everything that doesn't *exactly* match an unpack,
12997 /// making this clever lowering unnecessary.
lowerShuffleAsPermuteAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12998 static SDValue lowerShuffleAsPermuteAndUnpack(
12999     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13000     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13001   assert(!VT.isFloatingPoint() &&
13002          "This routine only supports integer vectors.");
13003   assert(VT.is128BitVector() &&
13004          "This routine only works on 128-bit vectors.");
13005   assert(!V2.isUndef() &&
13006          "This routine should only be used when blending two inputs.");
13007   assert(Mask.size() >= 2 && "Single element masks are invalid.");
13008 
13009   int Size = Mask.size();
13010 
13011   int NumLoInputs =
13012       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
13013   int NumHiInputs =
13014       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
13015 
13016   bool UnpackLo = NumLoInputs >= NumHiInputs;
13017 
13018   auto TryUnpack = [&](int ScalarSize, int Scale) {
13019     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
13020     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
13021 
13022     for (int i = 0; i < Size; ++i) {
13023       if (Mask[i] < 0)
13024         continue;
13025 
13026       // Each element of the unpack contains Scale elements from this mask.
13027       int UnpackIdx = i / Scale;
13028 
13029       // We only handle the case where V1 feeds the first slots of the unpack.
13030       // We rely on canonicalization to ensure this is the case.
13031       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
13032         return SDValue();
13033 
13034       // Setup the mask for this input. The indexing is tricky as we have to
13035       // handle the unpack stride.
13036       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
13037       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
13038           Mask[i] % Size;
13039     }
13040 
13041     // If we will have to shuffle both inputs to use the unpack, check whether
13042     // we can just unpack first and shuffle the result. If so, skip this unpack.
13043     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
13044         !isNoopShuffleMask(V2Mask))
13045       return SDValue();
13046 
13047     // Shuffle the inputs into place.
13048     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13049     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13050 
13051     // Cast the inputs to the type we will use to unpack them.
13052     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
13053     V1 = DAG.getBitcast(UnpackVT, V1);
13054     V2 = DAG.getBitcast(UnpackVT, V2);
13055 
13056     // Unpack the inputs and cast the result back to the desired type.
13057     return DAG.getBitcast(
13058         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13059                         UnpackVT, V1, V2));
13060   };
13061 
13062   // We try each unpack from the largest to the smallest to try and find one
13063   // that fits this mask.
13064   int OrigScalarSize = VT.getScalarSizeInBits();
13065   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
13066     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
13067       return Unpack;
13068 
13069   // If we're shuffling with a zero vector then we're better off not doing
13070   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
13071   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
13072       ISD::isBuildVectorAllZeros(V2.getNode()))
13073     return SDValue();
13074 
13075   // If none of the unpack-rooted lowerings worked (or were profitable) try an
13076   // initial unpack.
13077   if (NumLoInputs == 0 || NumHiInputs == 0) {
13078     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
13079            "We have to have *some* inputs!");
13080     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
13081 
13082     // FIXME: We could consider the total complexity of the permute of each
13083     // possible unpacking. Or at the least we should consider how many
13084     // half-crossings are created.
13085     // FIXME: We could consider commuting the unpacks.
13086 
13087     SmallVector<int, 32> PermMask((unsigned)Size, -1);
13088     for (int i = 0; i < Size; ++i) {
13089       if (Mask[i] < 0)
13090         continue;
13091 
13092       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
13093 
13094       PermMask[i] =
13095           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
13096     }
13097     return DAG.getVectorShuffle(
13098         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
13099                             DL, VT, V1, V2),
13100         DAG.getUNDEF(VT), PermMask);
13101   }
13102 
13103   return SDValue();
13104 }
13105 
13106 /// Handle lowering of 2-lane 64-bit floating point shuffles.
13107 ///
13108 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
13109 /// support for floating point shuffles but not integer shuffles. These
13110 /// instructions will incur a domain crossing penalty on some chips though so
13111 /// it is better to avoid lowering through this for integer vectors where
13112 /// possible.
lowerV2F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13113 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13114                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13115                                  const X86Subtarget &Subtarget,
13116                                  SelectionDAG &DAG) {
13117   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13118   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13119   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13120 
13121   if (V2.isUndef()) {
13122     // Check for being able to broadcast a single element.
13123     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13124                                                     Mask, Subtarget, DAG))
13125       return Broadcast;
13126 
13127     // Straight shuffle of a single input vector. Simulate this by using the
13128     // single input as both of the "inputs" to this instruction..
13129     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13130 
13131     if (Subtarget.hasAVX()) {
13132       // If we have AVX, we can use VPERMILPS which will allow folding a load
13133       // into the shuffle.
13134       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13135                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13136     }
13137 
13138     return DAG.getNode(
13139         X86ISD::SHUFP, DL, MVT::v2f64,
13140         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13141         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13142         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13143   }
13144   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13145   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13146   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13147   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13148 
13149   if (Subtarget.hasAVX2())
13150     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13151       return Extract;
13152 
13153   // When loading a scalar and then shuffling it into a vector we can often do
13154   // the insertion cheaply.
13155   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13156           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13157     return Insertion;
13158   // Try inverting the insertion since for v2 masks it is easy to do and we
13159   // can't reliably sort the mask one way or the other.
13160   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13161                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13162   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13163           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13164     return Insertion;
13165 
13166   // Try to use one of the special instruction patterns to handle two common
13167   // blend patterns if a zero-blend above didn't work.
13168   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
13169       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
13170     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13171       // We can either use a special instruction to load over the low double or
13172       // to move just the low double.
13173       return DAG.getNode(
13174           X86ISD::MOVSD, DL, MVT::v2f64, V2,
13175           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13176 
13177   if (Subtarget.hasSSE41())
13178     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13179                                             Zeroable, Subtarget, DAG))
13180       return Blend;
13181 
13182   // Use dedicated unpack instructions for masks that match their pattern.
13183   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
13184     return V;
13185 
13186   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13187   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13188                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13189 }
13190 
13191 /// Handle lowering of 2-lane 64-bit integer shuffles.
13192 ///
13193 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13194 /// the integer unit to minimize domain crossing penalties. However, for blends
13195 /// it falls back to the floating point shuffle operation with appropriate bit
13196 /// casting.
lowerV2I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13197 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13198                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13199                                  const X86Subtarget &Subtarget,
13200                                  SelectionDAG &DAG) {
13201   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13202   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13203   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13204 
13205   if (V2.isUndef()) {
13206     // Check for being able to broadcast a single element.
13207     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13208                                                     Mask, Subtarget, DAG))
13209       return Broadcast;
13210 
13211     // Straight shuffle of a single input vector. For everything from SSE2
13212     // onward this has a single fast instruction with no scary immediates.
13213     // We have to map the mask as it is actually a v4i32 shuffle instruction.
13214     V1 = DAG.getBitcast(MVT::v4i32, V1);
13215     int WidenedMask[4] = {
13216         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
13217         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
13218     return DAG.getBitcast(
13219         MVT::v2i64,
13220         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13221                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13222   }
13223   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13224   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13225   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13226   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13227 
13228   if (Subtarget.hasAVX2())
13229     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13230       return Extract;
13231 
13232   // Try to use shift instructions.
13233   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
13234                                           Zeroable, Subtarget, DAG))
13235     return Shift;
13236 
13237   // When loading a scalar and then shuffling it into a vector we can often do
13238   // the insertion cheaply.
13239   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13240           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13241     return Insertion;
13242   // Try inverting the insertion since for v2 masks it is easy to do and we
13243   // can't reliably sort the mask one way or the other.
13244   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13245   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13246           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13247     return Insertion;
13248 
13249   // We have different paths for blend lowering, but they all must use the
13250   // *exact* same predicate.
13251   bool IsBlendSupported = Subtarget.hasSSE41();
13252   if (IsBlendSupported)
13253     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13254                                             Zeroable, Subtarget, DAG))
13255       return Blend;
13256 
13257   // Use dedicated unpack instructions for masks that match their pattern.
13258   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
13259     return V;
13260 
13261   // Try to use byte rotation instructions.
13262   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13263   if (Subtarget.hasSSSE3()) {
13264     if (Subtarget.hasVLX())
13265       if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v2i64, V1, V2, Mask,
13266                                                 Subtarget, DAG))
13267         return Rotate;
13268 
13269     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13270                                                   Subtarget, DAG))
13271       return Rotate;
13272   }
13273 
13274   // If we have direct support for blends, we should lower by decomposing into
13275   // a permute. That will be faster than the domain cross.
13276   if (IsBlendSupported)
13277     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2, Mask,
13278                                                 Subtarget, DAG);
13279 
13280   // We implement this with SHUFPD which is pretty lame because it will likely
13281   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13282   // However, all the alternatives are still more cycles and newer chips don't
13283   // have this problem. It would be really nice if x86 had better shuffles here.
13284   V1 = DAG.getBitcast(MVT::v2f64, V1);
13285   V2 = DAG.getBitcast(MVT::v2f64, V2);
13286   return DAG.getBitcast(MVT::v2i64,
13287                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13288 }
13289 
13290 /// Lower a vector shuffle using the SHUFPS instruction.
13291 ///
13292 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13293 /// It makes no assumptions about whether this is the *best* lowering, it simply
13294 /// uses it.
lowerShuffleWithSHUFPS(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)13295 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
13296                                       ArrayRef<int> Mask, SDValue V1,
13297                                       SDValue V2, SelectionDAG &DAG) {
13298   SDValue LowV = V1, HighV = V2;
13299   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
13300 
13301   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13302 
13303   if (NumV2Elements == 1) {
13304     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13305 
13306     // Compute the index adjacent to V2Index and in the same half by toggling
13307     // the low bit.
13308     int V2AdjIndex = V2Index ^ 1;
13309 
13310     if (Mask[V2AdjIndex] < 0) {
13311       // Handles all the cases where we have a single V2 element and an undef.
13312       // This will only ever happen in the high lanes because we commute the
13313       // vector otherwise.
13314       if (V2Index < 2)
13315         std::swap(LowV, HighV);
13316       NewMask[V2Index] -= 4;
13317     } else {
13318       // Handle the case where the V2 element ends up adjacent to a V1 element.
13319       // To make this work, blend them together as the first step.
13320       int V1Index = V2AdjIndex;
13321       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13322       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13323                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13324 
13325       // Now proceed to reconstruct the final blend as we have the necessary
13326       // high or low half formed.
13327       if (V2Index < 2) {
13328         LowV = V2;
13329         HighV = V1;
13330       } else {
13331         HighV = V2;
13332       }
13333       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13334       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13335     }
13336   } else if (NumV2Elements == 2) {
13337     if (Mask[0] < 4 && Mask[1] < 4) {
13338       // Handle the easy case where we have V1 in the low lanes and V2 in the
13339       // high lanes.
13340       NewMask[2] -= 4;
13341       NewMask[3] -= 4;
13342     } else if (Mask[2] < 4 && Mask[3] < 4) {
13343       // We also handle the reversed case because this utility may get called
13344       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13345       // arrange things in the right direction.
13346       NewMask[0] -= 4;
13347       NewMask[1] -= 4;
13348       HighV = V1;
13349       LowV = V2;
13350     } else {
13351       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13352       // trying to place elements directly, just blend them and set up the final
13353       // shuffle to place them.
13354 
13355       // The first two blend mask elements are for V1, the second two are for
13356       // V2.
13357       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13358                           Mask[2] < 4 ? Mask[2] : Mask[3],
13359                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13360                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13361       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13362                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13363 
13364       // Now we do a normal shuffle of V1 by giving V1 as both operands to
13365       // a blend.
13366       LowV = HighV = V1;
13367       NewMask[0] = Mask[0] < 4 ? 0 : 2;
13368       NewMask[1] = Mask[0] < 4 ? 2 : 0;
13369       NewMask[2] = Mask[2] < 4 ? 1 : 3;
13370       NewMask[3] = Mask[2] < 4 ? 3 : 1;
13371     }
13372   }
13373   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13374                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13375 }
13376 
13377 /// Lower 4-lane 32-bit floating point shuffles.
13378 ///
13379 /// Uses instructions exclusively from the floating point unit to minimize
13380 /// domain crossing penalties, as these are sufficient to implement all v4f32
13381 /// shuffles.
lowerV4F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13382 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13383                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13384                                  const X86Subtarget &Subtarget,
13385                                  SelectionDAG &DAG) {
13386   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13387   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13388   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13389 
13390   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13391 
13392   if (NumV2Elements == 0) {
13393     // Check for being able to broadcast a single element.
13394     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
13395                                                     Mask, Subtarget, DAG))
13396       return Broadcast;
13397 
13398     // Use even/odd duplicate instructions for masks that match their pattern.
13399     if (Subtarget.hasSSE3()) {
13400       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
13401         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
13402       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
13403         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
13404     }
13405 
13406     if (Subtarget.hasAVX()) {
13407       // If we have AVX, we can use VPERMILPS which will allow folding a load
13408       // into the shuffle.
13409       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
13410                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13411     }
13412 
13413     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
13414     // in SSE1 because otherwise they are widened to v2f64 and never get here.
13415     if (!Subtarget.hasSSE2()) {
13416       if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}))
13417         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
13418       if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 2, 3}))
13419         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
13420     }
13421 
13422     // Otherwise, use a straight shuffle of a single input vector. We pass the
13423     // input vector to both operands to simulate this with a SHUFPS.
13424     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
13425                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13426   }
13427 
13428   if (Subtarget.hasAVX2())
13429     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13430       return Extract;
13431 
13432   // There are special ways we can lower some single-element blends. However, we
13433   // have custom ways we can lower more complex single-element blends below that
13434   // we defer to if both this and BLENDPS fail to match, so restrict this to
13435   // when the V2 input is targeting element 0 of the mask -- that is the fast
13436   // case here.
13437   if (NumV2Elements == 1 && Mask[0] >= 4)
13438     if (SDValue V = lowerShuffleAsElementInsertion(
13439             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13440       return V;
13441 
13442   if (Subtarget.hasSSE41()) {
13443     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13444                                             Zeroable, Subtarget, DAG))
13445       return Blend;
13446 
13447     // Use INSERTPS if we can complete the shuffle efficiently.
13448     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
13449       return V;
13450 
13451     if (!isSingleSHUFPSMask(Mask))
13452       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
13453                                                             V2, Mask, DAG))
13454         return BlendPerm;
13455   }
13456 
13457   // Use low/high mov instructions. These are only valid in SSE1 because
13458   // otherwise they are widened to v2f64 and never get here.
13459   if (!Subtarget.hasSSE2()) {
13460     if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5}))
13461       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
13462     if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 6, 7}))
13463       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
13464   }
13465 
13466   // Use dedicated unpack instructions for masks that match their pattern.
13467   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
13468     return V;
13469 
13470   // Otherwise fall back to a SHUFPS lowering strategy.
13471   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
13472 }
13473 
13474 /// Lower 4-lane i32 vector shuffles.
13475 ///
13476 /// We try to handle these with integer-domain shuffles where we can, but for
13477 /// blends we use the floating point domain blend instructions.
lowerV4I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13478 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13479                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13480                                  const X86Subtarget &Subtarget,
13481                                  SelectionDAG &DAG) {
13482   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13483   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13484   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13485 
13486   // Whenever we can lower this as a zext, that instruction is strictly faster
13487   // than any alternative. It also allows us to fold memory operands into the
13488   // shuffle in many cases.
13489   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
13490                                                    Zeroable, Subtarget, DAG))
13491     return ZExt;
13492 
13493   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13494 
13495   if (NumV2Elements == 0) {
13496     // Try to use broadcast unless the mask only has one non-undef element.
13497     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
13498       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
13499                                                       Mask, Subtarget, DAG))
13500         return Broadcast;
13501     }
13502 
13503     // Straight shuffle of a single input vector. For everything from SSE2
13504     // onward this has a single fast instruction with no scary immediates.
13505     // We coerce the shuffle pattern to be compatible with UNPCK instructions
13506     // but we aren't actually going to use the UNPCK instruction because doing
13507     // so prevents folding a load into this instruction or making a copy.
13508     const int UnpackLoMask[] = {0, 0, 1, 1};
13509     const int UnpackHiMask[] = {2, 2, 3, 3};
13510     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
13511       Mask = UnpackLoMask;
13512     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
13513       Mask = UnpackHiMask;
13514 
13515     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13516                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13517   }
13518 
13519   if (Subtarget.hasAVX2())
13520     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13521       return Extract;
13522 
13523   // Try to use shift instructions.
13524   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
13525                                           Zeroable, Subtarget, DAG))
13526     return Shift;
13527 
13528   // There are special ways we can lower some single-element blends.
13529   if (NumV2Elements == 1)
13530     if (SDValue V = lowerShuffleAsElementInsertion(
13531             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13532       return V;
13533 
13534   // We have different paths for blend lowering, but they all must use the
13535   // *exact* same predicate.
13536   bool IsBlendSupported = Subtarget.hasSSE41();
13537   if (IsBlendSupported)
13538     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
13539                                             Zeroable, Subtarget, DAG))
13540       return Blend;
13541 
13542   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
13543                                              Zeroable, Subtarget, DAG))
13544     return Masked;
13545 
13546   // Use dedicated unpack instructions for masks that match their pattern.
13547   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
13548     return V;
13549 
13550   // Try to use byte rotation instructions.
13551   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13552   if (Subtarget.hasSSSE3()) {
13553     if (Subtarget.hasVLX())
13554       if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v4i32, V1, V2, Mask,
13555                                                 Subtarget, DAG))
13556         return Rotate;
13557 
13558     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
13559                                                   Subtarget, DAG))
13560       return Rotate;
13561   }
13562 
13563   // Assume that a single SHUFPS is faster than an alternative sequence of
13564   // multiple instructions (even if the CPU has a domain penalty).
13565   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
13566   if (!isSingleSHUFPSMask(Mask)) {
13567     // If we have direct support for blends, we should lower by decomposing into
13568     // a permute. That will be faster than the domain cross.
13569     if (IsBlendSupported)
13570       return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2, Mask,
13571                                                   Subtarget, DAG);
13572 
13573     // Try to lower by permuting the inputs into an unpack instruction.
13574     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
13575                                                         Mask, Subtarget, DAG))
13576       return Unpack;
13577   }
13578 
13579   // We implement this with SHUFPS because it can blend from two vectors.
13580   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
13581   // up the inputs, bypassing domain shift penalties that we would incur if we
13582   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
13583   // relevant.
13584   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
13585   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
13586   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
13587   return DAG.getBitcast(MVT::v4i32, ShufPS);
13588 }
13589 
13590 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
13591 /// shuffle lowering, and the most complex part.
13592 ///
13593 /// The lowering strategy is to try to form pairs of input lanes which are
13594 /// targeted at the same half of the final vector, and then use a dword shuffle
13595 /// to place them onto the right half, and finally unpack the paired lanes into
13596 /// their final position.
13597 ///
13598 /// The exact breakdown of how to form these dword pairs and align them on the
13599 /// correct sides is really tricky. See the comments within the function for
13600 /// more of the details.
13601 ///
13602 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
13603 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
13604 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
13605 /// vector, form the analogous 128-bit 8-element Mask.
lowerV8I16GeneralSingleInputShuffle(const SDLoc & DL,MVT VT,SDValue V,MutableArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)13606 static SDValue lowerV8I16GeneralSingleInputShuffle(
13607     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
13608     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13609   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
13610   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
13611 
13612   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
13613   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
13614   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
13615 
13616   // Attempt to directly match PSHUFLW or PSHUFHW.
13617   if (isUndefOrInRange(LoMask, 0, 4) &&
13618       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
13619     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13620                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13621   }
13622   if (isUndefOrInRange(HiMask, 4, 8) &&
13623       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
13624     for (int i = 0; i != 4; ++i)
13625       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
13626     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13627                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13628   }
13629 
13630   SmallVector<int, 4> LoInputs;
13631   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
13632   array_pod_sort(LoInputs.begin(), LoInputs.end());
13633   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
13634   SmallVector<int, 4> HiInputs;
13635   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
13636   array_pod_sort(HiInputs.begin(), HiInputs.end());
13637   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
13638   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
13639   int NumHToL = LoInputs.size() - NumLToL;
13640   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
13641   int NumHToH = HiInputs.size() - NumLToH;
13642   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
13643   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
13644   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
13645   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
13646 
13647   // If we are shuffling values from one half - check how many different DWORD
13648   // pairs we need to create. If only 1 or 2 then we can perform this as a
13649   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
13650   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
13651                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
13652     V = DAG.getNode(ShufWOp, DL, VT, V,
13653                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13654     V = DAG.getBitcast(PSHUFDVT, V);
13655     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
13656                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13657     return DAG.getBitcast(VT, V);
13658   };
13659 
13660   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
13661     int PSHUFDMask[4] = { -1, -1, -1, -1 };
13662     SmallVector<std::pair<int, int>, 4> DWordPairs;
13663     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
13664 
13665     // Collect the different DWORD pairs.
13666     for (int DWord = 0; DWord != 4; ++DWord) {
13667       int M0 = Mask[2 * DWord + 0];
13668       int M1 = Mask[2 * DWord + 1];
13669       M0 = (M0 >= 0 ? M0 % 4 : M0);
13670       M1 = (M1 >= 0 ? M1 % 4 : M1);
13671       if (M0 < 0 && M1 < 0)
13672         continue;
13673 
13674       bool Match = false;
13675       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
13676         auto &DWordPair = DWordPairs[j];
13677         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
13678             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
13679           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
13680           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
13681           PSHUFDMask[DWord] = DOffset + j;
13682           Match = true;
13683           break;
13684         }
13685       }
13686       if (!Match) {
13687         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
13688         DWordPairs.push_back(std::make_pair(M0, M1));
13689       }
13690     }
13691 
13692     if (DWordPairs.size() <= 2) {
13693       DWordPairs.resize(2, std::make_pair(-1, -1));
13694       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
13695                               DWordPairs[1].first, DWordPairs[1].second};
13696       if ((NumHToL + NumHToH) == 0)
13697         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
13698       if ((NumLToL + NumLToH) == 0)
13699         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
13700     }
13701   }
13702 
13703   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
13704   // such inputs we can swap two of the dwords across the half mark and end up
13705   // with <=2 inputs to each half in each half. Once there, we can fall through
13706   // to the generic code below. For example:
13707   //
13708   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13709   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
13710   //
13711   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
13712   // and an existing 2-into-2 on the other half. In this case we may have to
13713   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
13714   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
13715   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
13716   // because any other situation (including a 3-into-1 or 1-into-3 in the other
13717   // half than the one we target for fixing) will be fixed when we re-enter this
13718   // path. We will also combine away any sequence of PSHUFD instructions that
13719   // result into a single instruction. Here is an example of the tricky case:
13720   //
13721   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13722   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
13723   //
13724   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
13725   //
13726   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
13727   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
13728   //
13729   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
13730   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
13731   //
13732   // The result is fine to be handled by the generic logic.
13733   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
13734                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
13735                           int AOffset, int BOffset) {
13736     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
13737            "Must call this with A having 3 or 1 inputs from the A half.");
13738     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
13739            "Must call this with B having 1 or 3 inputs from the B half.");
13740     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
13741            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
13742 
13743     bool ThreeAInputs = AToAInputs.size() == 3;
13744 
13745     // Compute the index of dword with only one word among the three inputs in
13746     // a half by taking the sum of the half with three inputs and subtracting
13747     // the sum of the actual three inputs. The difference is the remaining
13748     // slot.
13749     int ADWord = 0, BDWord = 0;
13750     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
13751     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
13752     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
13753     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
13754     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
13755     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
13756     int TripleNonInputIdx =
13757         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
13758     TripleDWord = TripleNonInputIdx / 2;
13759 
13760     // We use xor with one to compute the adjacent DWord to whichever one the
13761     // OneInput is in.
13762     OneInputDWord = (OneInput / 2) ^ 1;
13763 
13764     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
13765     // and BToA inputs. If there is also such a problem with the BToB and AToB
13766     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
13767     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
13768     // is essential that we don't *create* a 3<-1 as then we might oscillate.
13769     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
13770       // Compute how many inputs will be flipped by swapping these DWords. We
13771       // need
13772       // to balance this to ensure we don't form a 3-1 shuffle in the other
13773       // half.
13774       int NumFlippedAToBInputs =
13775           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
13776           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
13777       int NumFlippedBToBInputs =
13778           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
13779           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
13780       if ((NumFlippedAToBInputs == 1 &&
13781            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
13782           (NumFlippedBToBInputs == 1 &&
13783            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
13784         // We choose whether to fix the A half or B half based on whether that
13785         // half has zero flipped inputs. At zero, we may not be able to fix it
13786         // with that half. We also bias towards fixing the B half because that
13787         // will more commonly be the high half, and we have to bias one way.
13788         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
13789                                                        ArrayRef<int> Inputs) {
13790           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
13791           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
13792           // Determine whether the free index is in the flipped dword or the
13793           // unflipped dword based on where the pinned index is. We use this bit
13794           // in an xor to conditionally select the adjacent dword.
13795           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
13796           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13797           if (IsFixIdxInput == IsFixFreeIdxInput)
13798             FixFreeIdx += 1;
13799           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13800           assert(IsFixIdxInput != IsFixFreeIdxInput &&
13801                  "We need to be changing the number of flipped inputs!");
13802           int PSHUFHalfMask[] = {0, 1, 2, 3};
13803           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
13804           V = DAG.getNode(
13805               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
13806               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
13807               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13808 
13809           for (int &M : Mask)
13810             if (M >= 0 && M == FixIdx)
13811               M = FixFreeIdx;
13812             else if (M >= 0 && M == FixFreeIdx)
13813               M = FixIdx;
13814         };
13815         if (NumFlippedBToBInputs != 0) {
13816           int BPinnedIdx =
13817               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
13818           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
13819         } else {
13820           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
13821           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
13822           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
13823         }
13824       }
13825     }
13826 
13827     int PSHUFDMask[] = {0, 1, 2, 3};
13828     PSHUFDMask[ADWord] = BDWord;
13829     PSHUFDMask[BDWord] = ADWord;
13830     V = DAG.getBitcast(
13831         VT,
13832         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13833                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13834 
13835     // Adjust the mask to match the new locations of A and B.
13836     for (int &M : Mask)
13837       if (M >= 0 && M/2 == ADWord)
13838         M = 2 * BDWord + M % 2;
13839       else if (M >= 0 && M/2 == BDWord)
13840         M = 2 * ADWord + M % 2;
13841 
13842     // Recurse back into this routine to re-compute state now that this isn't
13843     // a 3 and 1 problem.
13844     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
13845   };
13846   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
13847     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
13848   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
13849     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
13850 
13851   // At this point there are at most two inputs to the low and high halves from
13852   // each half. That means the inputs can always be grouped into dwords and
13853   // those dwords can then be moved to the correct half with a dword shuffle.
13854   // We use at most one low and one high word shuffle to collect these paired
13855   // inputs into dwords, and finally a dword shuffle to place them.
13856   int PSHUFLMask[4] = {-1, -1, -1, -1};
13857   int PSHUFHMask[4] = {-1, -1, -1, -1};
13858   int PSHUFDMask[4] = {-1, -1, -1, -1};
13859 
13860   // First fix the masks for all the inputs that are staying in their
13861   // original halves. This will then dictate the targets of the cross-half
13862   // shuffles.
13863   auto fixInPlaceInputs =
13864       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
13865                     MutableArrayRef<int> SourceHalfMask,
13866                     MutableArrayRef<int> HalfMask, int HalfOffset) {
13867     if (InPlaceInputs.empty())
13868       return;
13869     if (InPlaceInputs.size() == 1) {
13870       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13871           InPlaceInputs[0] - HalfOffset;
13872       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
13873       return;
13874     }
13875     if (IncomingInputs.empty()) {
13876       // Just fix all of the in place inputs.
13877       for (int Input : InPlaceInputs) {
13878         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
13879         PSHUFDMask[Input / 2] = Input / 2;
13880       }
13881       return;
13882     }
13883 
13884     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
13885     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13886         InPlaceInputs[0] - HalfOffset;
13887     // Put the second input next to the first so that they are packed into
13888     // a dword. We find the adjacent index by toggling the low bit.
13889     int AdjIndex = InPlaceInputs[0] ^ 1;
13890     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
13891     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
13892     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
13893   };
13894   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
13895   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
13896 
13897   // Now gather the cross-half inputs and place them into a free dword of
13898   // their target half.
13899   // FIXME: This operation could almost certainly be simplified dramatically to
13900   // look more like the 3-1 fixing operation.
13901   auto moveInputsToRightHalf = [&PSHUFDMask](
13902       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
13903       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
13904       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
13905       int DestOffset) {
13906     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
13907       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
13908     };
13909     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
13910                                                int Word) {
13911       int LowWord = Word & ~1;
13912       int HighWord = Word | 1;
13913       return isWordClobbered(SourceHalfMask, LowWord) ||
13914              isWordClobbered(SourceHalfMask, HighWord);
13915     };
13916 
13917     if (IncomingInputs.empty())
13918       return;
13919 
13920     if (ExistingInputs.empty()) {
13921       // Map any dwords with inputs from them into the right half.
13922       for (int Input : IncomingInputs) {
13923         // If the source half mask maps over the inputs, turn those into
13924         // swaps and use the swapped lane.
13925         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
13926           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
13927             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
13928                 Input - SourceOffset;
13929             // We have to swap the uses in our half mask in one sweep.
13930             for (int &M : HalfMask)
13931               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
13932                 M = Input;
13933               else if (M == Input)
13934                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13935           } else {
13936             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
13937                        Input - SourceOffset &&
13938                    "Previous placement doesn't match!");
13939           }
13940           // Note that this correctly re-maps both when we do a swap and when
13941           // we observe the other side of the swap above. We rely on that to
13942           // avoid swapping the members of the input list directly.
13943           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13944         }
13945 
13946         // Map the input's dword into the correct half.
13947         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
13948           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
13949         else
13950           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
13951                      Input / 2 &&
13952                  "Previous placement doesn't match!");
13953       }
13954 
13955       // And just directly shift any other-half mask elements to be same-half
13956       // as we will have mirrored the dword containing the element into the
13957       // same position within that half.
13958       for (int &M : HalfMask)
13959         if (M >= SourceOffset && M < SourceOffset + 4) {
13960           M = M - SourceOffset + DestOffset;
13961           assert(M >= 0 && "This should never wrap below zero!");
13962         }
13963       return;
13964     }
13965 
13966     // Ensure we have the input in a viable dword of its current half. This
13967     // is particularly tricky because the original position may be clobbered
13968     // by inputs being moved and *staying* in that half.
13969     if (IncomingInputs.size() == 1) {
13970       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13971         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
13972                          SourceOffset;
13973         SourceHalfMask[InputFixed - SourceOffset] =
13974             IncomingInputs[0] - SourceOffset;
13975         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
13976                      InputFixed);
13977         IncomingInputs[0] = InputFixed;
13978       }
13979     } else if (IncomingInputs.size() == 2) {
13980       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
13981           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13982         // We have two non-adjacent or clobbered inputs we need to extract from
13983         // the source half. To do this, we need to map them into some adjacent
13984         // dword slot in the source mask.
13985         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
13986                               IncomingInputs[1] - SourceOffset};
13987 
13988         // If there is a free slot in the source half mask adjacent to one of
13989         // the inputs, place the other input in it. We use (Index XOR 1) to
13990         // compute an adjacent index.
13991         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
13992             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
13993           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
13994           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13995           InputsFixed[1] = InputsFixed[0] ^ 1;
13996         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
13997                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
13998           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
13999           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14000           InputsFixed[0] = InputsFixed[1] ^ 1;
14001         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14002                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14003           // The two inputs are in the same DWord but it is clobbered and the
14004           // adjacent DWord isn't used at all. Move both inputs to the free
14005           // slot.
14006           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14007           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14008           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14009           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14010         } else {
14011           // The only way we hit this point is if there is no clobbering
14012           // (because there are no off-half inputs to this half) and there is no
14013           // free slot adjacent to one of the inputs. In this case, we have to
14014           // swap an input with a non-input.
14015           for (int i = 0; i < 4; ++i)
14016             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14017                    "We can't handle any clobbers here!");
14018           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14019                  "Cannot have adjacent inputs here!");
14020 
14021           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14022           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14023 
14024           // We also have to update the final source mask in this case because
14025           // it may need to undo the above swap.
14026           for (int &M : FinalSourceHalfMask)
14027             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14028               M = InputsFixed[1] + SourceOffset;
14029             else if (M == InputsFixed[1] + SourceOffset)
14030               M = (InputsFixed[0] ^ 1) + SourceOffset;
14031 
14032           InputsFixed[1] = InputsFixed[0] ^ 1;
14033         }
14034 
14035         // Point everything at the fixed inputs.
14036         for (int &M : HalfMask)
14037           if (M == IncomingInputs[0])
14038             M = InputsFixed[0] + SourceOffset;
14039           else if (M == IncomingInputs[1])
14040             M = InputsFixed[1] + SourceOffset;
14041 
14042         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14043         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14044       }
14045     } else {
14046       llvm_unreachable("Unhandled input size!");
14047     }
14048 
14049     // Now hoist the DWord down to the right half.
14050     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14051     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14052     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14053     for (int &M : HalfMask)
14054       for (int Input : IncomingInputs)
14055         if (M == Input)
14056           M = FreeDWord * 2 + Input % 2;
14057   };
14058   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14059                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
14060   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14061                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
14062 
14063   // Now enact all the shuffles we've computed to move the inputs into their
14064   // target half.
14065   if (!isNoopShuffleMask(PSHUFLMask))
14066     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14067                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14068   if (!isNoopShuffleMask(PSHUFHMask))
14069     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14070                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14071   if (!isNoopShuffleMask(PSHUFDMask))
14072     V = DAG.getBitcast(
14073         VT,
14074         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14075                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14076 
14077   // At this point, each half should contain all its inputs, and we can then
14078   // just shuffle them into their final position.
14079   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
14080          "Failed to lift all the high half inputs to the low mask!");
14081   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
14082          "Failed to lift all the low half inputs to the high mask!");
14083 
14084   // Do a half shuffle for the low mask.
14085   if (!isNoopShuffleMask(LoMask))
14086     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14087                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14088 
14089   // Do a half shuffle with the high mask after shifting its values down.
14090   for (int &M : HiMask)
14091     if (M >= 0)
14092       M -= 4;
14093   if (!isNoopShuffleMask(HiMask))
14094     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14095                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14096 
14097   return V;
14098 }
14099 
14100 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14101 /// blend if only one input is used.
lowerShuffleAsBlendOfPSHUFBs(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG,bool & V1InUse,bool & V2InUse)14102 static SDValue lowerShuffleAsBlendOfPSHUFBs(
14103     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14104     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14105   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
14106          "Lane crossing shuffle masks not supported");
14107 
14108   int NumBytes = VT.getSizeInBits() / 8;
14109   int Size = Mask.size();
14110   int Scale = NumBytes / Size;
14111 
14112   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14113   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14114   V1InUse = false;
14115   V2InUse = false;
14116 
14117   for (int i = 0; i < NumBytes; ++i) {
14118     int M = Mask[i / Scale];
14119     if (M < 0)
14120       continue;
14121 
14122     const int ZeroMask = 0x80;
14123     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14124     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14125     if (Zeroable[i / Scale])
14126       V1Idx = V2Idx = ZeroMask;
14127 
14128     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14129     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14130     V1InUse |= (ZeroMask != V1Idx);
14131     V2InUse |= (ZeroMask != V2Idx);
14132   }
14133 
14134   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14135   if (V1InUse)
14136     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14137                      DAG.getBuildVector(ShufVT, DL, V1Mask));
14138   if (V2InUse)
14139     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14140                      DAG.getBuildVector(ShufVT, DL, V2Mask));
14141 
14142   // If we need shuffled inputs from both, blend the two.
14143   SDValue V;
14144   if (V1InUse && V2InUse)
14145     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14146   else
14147     V = V1InUse ? V1 : V2;
14148 
14149   // Cast the result back to the correct type.
14150   return DAG.getBitcast(VT, V);
14151 }
14152 
14153 /// Generic lowering of 8-lane i16 shuffles.
14154 ///
14155 /// This handles both single-input shuffles and combined shuffle/blends with
14156 /// two inputs. The single input shuffles are immediately delegated to
14157 /// a dedicated lowering routine.
14158 ///
14159 /// The blends are lowered in one of three fundamental ways. If there are few
14160 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14161 /// of the input is significantly cheaper when lowered as an interleaving of
14162 /// the two inputs, try to interleave them. Otherwise, blend the low and high
14163 /// halves of the inputs separately (making them have relatively few inputs)
14164 /// and then concatenate them.
lowerV8I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14165 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14166                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14167                                  const X86Subtarget &Subtarget,
14168                                  SelectionDAG &DAG) {
14169   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14170   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14171   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14172 
14173   // Whenever we can lower this as a zext, that instruction is strictly faster
14174   // than any alternative.
14175   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14176                                                    Zeroable, Subtarget, DAG))
14177     return ZExt;
14178 
14179   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14180 
14181   if (NumV2Inputs == 0) {
14182     // Try to use shift instructions.
14183     if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
14184                                             Zeroable, Subtarget, DAG))
14185       return Shift;
14186 
14187     // Check for being able to broadcast a single element.
14188     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14189                                                     Mask, Subtarget, DAG))
14190       return Broadcast;
14191 
14192     // Use dedicated unpack instructions for masks that match their pattern.
14193     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
14194       return V;
14195 
14196     // Use dedicated pack instructions for masks that match their pattern.
14197     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
14198                                          Subtarget))
14199       return V;
14200 
14201     // Try to use byte rotation instructions.
14202     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14203                                                   Subtarget, DAG))
14204       return Rotate;
14205 
14206     // Make a copy of the mask so it can be modified.
14207     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
14208     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14209                                                Subtarget, DAG);
14210   }
14211 
14212   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14213          "All single-input shuffles should be canonicalized to be V1-input "
14214          "shuffles.");
14215 
14216   // Try to use shift instructions.
14217   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
14218                                           Zeroable, Subtarget, DAG))
14219     return Shift;
14220 
14221   // See if we can use SSE4A Extraction / Insertion.
14222   if (Subtarget.hasSSE4A())
14223     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14224                                           Zeroable, DAG))
14225       return V;
14226 
14227   // There are special ways we can lower some single-element blends.
14228   if (NumV2Inputs == 1)
14229     if (SDValue V = lowerShuffleAsElementInsertion(
14230             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14231       return V;
14232 
14233   // We have different paths for blend lowering, but they all must use the
14234   // *exact* same predicate.
14235   bool IsBlendSupported = Subtarget.hasSSE41();
14236   if (IsBlendSupported)
14237     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14238                                             Zeroable, Subtarget, DAG))
14239       return Blend;
14240 
14241   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
14242                                              Zeroable, Subtarget, DAG))
14243     return Masked;
14244 
14245   // Use dedicated unpack instructions for masks that match their pattern.
14246   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
14247     return V;
14248 
14249   // Use dedicated pack instructions for masks that match their pattern.
14250   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
14251                                        Subtarget))
14252     return V;
14253 
14254   // Try to use byte rotation instructions.
14255   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14256                                                 Subtarget, DAG))
14257     return Rotate;
14258 
14259   if (SDValue BitBlend =
14260           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14261     return BitBlend;
14262 
14263   // Try to use byte shift instructions to mask.
14264   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14265                                               Zeroable, Subtarget, DAG))
14266     return V;
14267 
14268   // Try to lower by permuting the inputs into an unpack instruction.
14269   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14270                                                       Mask, Subtarget, DAG))
14271     return Unpack;
14272 
14273   // If we can't directly blend but can use PSHUFB, that will be better as it
14274   // can both shuffle and set up the inefficient blend.
14275   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14276     bool V1InUse, V2InUse;
14277     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14278                                         Zeroable, DAG, V1InUse, V2InUse);
14279   }
14280 
14281   // We can always bit-blend if we have to so the fallback strategy is to
14282   // decompose into single-input permutes and blends.
14283   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
14284                                               Mask, Subtarget, DAG);
14285 }
14286 
14287 /// Check whether a compaction lowering can be done by dropping even
14288 /// elements and compute how many times even elements must be dropped.
14289 ///
14290 /// This handles shuffles which take every Nth element where N is a power of
14291 /// two. Example shuffle masks:
14292 ///
14293 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
14294 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
14295 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
14296 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
14297 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
14298 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
14299 ///
14300 /// Any of these lanes can of course be undef.
14301 ///
14302 /// This routine only supports N <= 3.
14303 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
14304 /// for larger N.
14305 ///
14306 /// \returns N above, or the number of times even elements must be dropped if
14307 /// there is such a number. Otherwise returns zero.
canLowerByDroppingEvenElements(ArrayRef<int> Mask,bool IsSingleInput)14308 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
14309                                           bool IsSingleInput) {
14310   // The modulus for the shuffle vector entries is based on whether this is
14311   // a single input or not.
14312   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
14313   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
14314          "We should only be called with masks with a power-of-2 size!");
14315 
14316   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
14317 
14318   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
14319   // and 2^3 simultaneously. This is because we may have ambiguity with
14320   // partially undef inputs.
14321   bool ViableForN[3] = {true, true, true};
14322 
14323   for (int i = 0, e = Mask.size(); i < e; ++i) {
14324     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
14325     // want.
14326     if (Mask[i] < 0)
14327       continue;
14328 
14329     bool IsAnyViable = false;
14330     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
14331       if (ViableForN[j]) {
14332         uint64_t N = j + 1;
14333 
14334         // The shuffle mask must be equal to (i * 2^N) % M.
14335         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
14336           IsAnyViable = true;
14337         else
14338           ViableForN[j] = false;
14339       }
14340     // Early exit if we exhaust the possible powers of two.
14341     if (!IsAnyViable)
14342       break;
14343   }
14344 
14345   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
14346     if (ViableForN[j])
14347       return j + 1;
14348 
14349   // Return 0 as there is no viable power of two.
14350   return 0;
14351 }
14352 
lowerShuffleWithPERMV(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)14353 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
14354                                      ArrayRef<int> Mask, SDValue V1,
14355                                      SDValue V2, SelectionDAG &DAG) {
14356   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
14357   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
14358 
14359   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
14360   if (V2.isUndef())
14361     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
14362 
14363   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
14364 }
14365 
14366 /// Generic lowering of v16i8 shuffles.
14367 ///
14368 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
14369 /// detect any complexity reducing interleaving. If that doesn't help, it uses
14370 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
14371 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
14372 /// back together.
lowerV16I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14373 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14374                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14375                                  const X86Subtarget &Subtarget,
14376                                  SelectionDAG &DAG) {
14377   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14378   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14379   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
14380 
14381   // Try to use shift instructions.
14382   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
14383                                           Zeroable, Subtarget, DAG))
14384     return Shift;
14385 
14386   // Try to use byte rotation instructions.
14387   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
14388                                                 Subtarget, DAG))
14389     return Rotate;
14390 
14391   // Use dedicated pack instructions for masks that match their pattern.
14392   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
14393                                        Subtarget))
14394     return V;
14395 
14396   // Try to use a zext lowering.
14397   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
14398                                                    Zeroable, Subtarget, DAG))
14399     return ZExt;
14400 
14401   // See if we can use SSE4A Extraction / Insertion.
14402   if (Subtarget.hasSSE4A())
14403     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
14404                                           Zeroable, DAG))
14405       return V;
14406 
14407   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
14408 
14409   // For single-input shuffles, there are some nicer lowering tricks we can use.
14410   if (NumV2Elements == 0) {
14411     // Check for being able to broadcast a single element.
14412     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
14413                                                     Mask, Subtarget, DAG))
14414       return Broadcast;
14415 
14416     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
14417       return V;
14418 
14419     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
14420     // Notably, this handles splat and partial-splat shuffles more efficiently.
14421     // However, it only makes sense if the pre-duplication shuffle simplifies
14422     // things significantly. Currently, this means we need to be able to
14423     // express the pre-duplication shuffle as an i16 shuffle.
14424     //
14425     // FIXME: We should check for other patterns which can be widened into an
14426     // i16 shuffle as well.
14427     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
14428       for (int i = 0; i < 16; i += 2)
14429         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
14430           return false;
14431 
14432       return true;
14433     };
14434     auto tryToWidenViaDuplication = [&]() -> SDValue {
14435       if (!canWidenViaDuplication(Mask))
14436         return SDValue();
14437       SmallVector<int, 4> LoInputs;
14438       copy_if(Mask, std::back_inserter(LoInputs),
14439               [](int M) { return M >= 0 && M < 8; });
14440       array_pod_sort(LoInputs.begin(), LoInputs.end());
14441       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
14442                      LoInputs.end());
14443       SmallVector<int, 4> HiInputs;
14444       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
14445       array_pod_sort(HiInputs.begin(), HiInputs.end());
14446       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
14447                      HiInputs.end());
14448 
14449       bool TargetLo = LoInputs.size() >= HiInputs.size();
14450       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
14451       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
14452 
14453       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
14454       SmallDenseMap<int, int, 8> LaneMap;
14455       for (int I : InPlaceInputs) {
14456         PreDupI16Shuffle[I/2] = I/2;
14457         LaneMap[I] = I;
14458       }
14459       int j = TargetLo ? 0 : 4, je = j + 4;
14460       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
14461         // Check if j is already a shuffle of this input. This happens when
14462         // there are two adjacent bytes after we move the low one.
14463         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
14464           // If we haven't yet mapped the input, search for a slot into which
14465           // we can map it.
14466           while (j < je && PreDupI16Shuffle[j] >= 0)
14467             ++j;
14468 
14469           if (j == je)
14470             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
14471             return SDValue();
14472 
14473           // Map this input with the i16 shuffle.
14474           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
14475         }
14476 
14477         // Update the lane map based on the mapping we ended up with.
14478         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
14479       }
14480       V1 = DAG.getBitcast(
14481           MVT::v16i8,
14482           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14483                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
14484 
14485       // Unpack the bytes to form the i16s that will be shuffled into place.
14486       bool EvenInUse = false, OddInUse = false;
14487       for (int i = 0; i < 16; i += 2) {
14488         EvenInUse |= (Mask[i + 0] >= 0);
14489         OddInUse |= (Mask[i + 1] >= 0);
14490         if (EvenInUse && OddInUse)
14491           break;
14492       }
14493       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14494                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
14495                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
14496 
14497       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
14498       for (int i = 0; i < 16; ++i)
14499         if (Mask[i] >= 0) {
14500           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
14501           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
14502           if (PostDupI16Shuffle[i / 2] < 0)
14503             PostDupI16Shuffle[i / 2] = MappedMask;
14504           else
14505             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
14506                    "Conflicting entries in the original shuffle!");
14507         }
14508       return DAG.getBitcast(
14509           MVT::v16i8,
14510           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14511                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
14512     };
14513     if (SDValue V = tryToWidenViaDuplication())
14514       return V;
14515   }
14516 
14517   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
14518                                              Zeroable, Subtarget, DAG))
14519     return Masked;
14520 
14521   // Use dedicated unpack instructions for masks that match their pattern.
14522   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
14523     return V;
14524 
14525   // Try to use byte shift instructions to mask.
14526   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
14527                                               Zeroable, Subtarget, DAG))
14528     return V;
14529 
14530   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
14531   // with PSHUFB. It is important to do this before we attempt to generate any
14532   // blends but after all of the single-input lowerings. If the single input
14533   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
14534   // want to preserve that and we can DAG combine any longer sequences into
14535   // a PSHUFB in the end. But once we start blending from multiple inputs,
14536   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
14537   // and there are *very* few patterns that would actually be faster than the
14538   // PSHUFB approach because of its ability to zero lanes.
14539   //
14540   // FIXME: The only exceptions to the above are blends which are exact
14541   // interleavings with direct instructions supporting them. We currently don't
14542   // handle those well here.
14543   if (Subtarget.hasSSSE3()) {
14544     bool V1InUse = false;
14545     bool V2InUse = false;
14546 
14547     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
14548         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
14549 
14550     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
14551     // do so. This avoids using them to handle blends-with-zero which is
14552     // important as a single pshufb is significantly faster for that.
14553     if (V1InUse && V2InUse) {
14554       if (Subtarget.hasSSE41())
14555         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
14556                                                 Zeroable, Subtarget, DAG))
14557           return Blend;
14558 
14559       // We can use an unpack to do the blending rather than an or in some
14560       // cases. Even though the or may be (very minorly) more efficient, we
14561       // preference this lowering because there are common cases where part of
14562       // the complexity of the shuffles goes away when we do the final blend as
14563       // an unpack.
14564       // FIXME: It might be worth trying to detect if the unpack-feeding
14565       // shuffles will both be pshufb, in which case we shouldn't bother with
14566       // this.
14567       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
14568               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14569         return Unpack;
14570 
14571       // If we have VBMI we can use one VPERM instead of multiple PSHUFBs.
14572       if (Subtarget.hasVBMI() && Subtarget.hasVLX())
14573         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, DAG);
14574 
14575       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
14576       // PALIGNR will be cheaper than the second PSHUFB+OR.
14577       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
14578               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14579         return V;
14580     }
14581 
14582     return PSHUFB;
14583   }
14584 
14585   // There are special ways we can lower some single-element blends.
14586   if (NumV2Elements == 1)
14587     if (SDValue V = lowerShuffleAsElementInsertion(
14588             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
14589       return V;
14590 
14591   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
14592     return Blend;
14593 
14594   // Check whether a compaction lowering can be done. This handles shuffles
14595   // which take every Nth element for some even N. See the helper function for
14596   // details.
14597   //
14598   // We special case these as they can be particularly efficiently handled with
14599   // the PACKUSB instruction on x86 and they show up in common patterns of
14600   // rearranging bytes to truncate wide elements.
14601   bool IsSingleInput = V2.isUndef();
14602   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput)) {
14603     // NumEvenDrops is the power of two stride of the elements. Another way of
14604     // thinking about it is that we need to drop the even elements this many
14605     // times to get the original input.
14606 
14607     // First we need to zero all the dropped bytes.
14608     assert(NumEvenDrops <= 3 &&
14609            "No support for dropping even elements more than 3 times.");
14610     SmallVector<SDValue, 16> ByteClearOps(16, DAG.getConstant(0, DL, MVT::i8));
14611     for (unsigned i = 0; i != 16; i += 1 << NumEvenDrops)
14612       ByteClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i8);
14613     SDValue ByteClearMask = DAG.getBuildVector(MVT::v16i8, DL, ByteClearOps);
14614     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
14615     if (!IsSingleInput)
14616       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
14617 
14618     // Now pack things back together.
14619     V1 = DAG.getBitcast(MVT::v8i16, V1);
14620     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
14621     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
14622     for (int i = 1; i < NumEvenDrops; ++i) {
14623       Result = DAG.getBitcast(MVT::v8i16, Result);
14624       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
14625     }
14626 
14627     return Result;
14628   }
14629 
14630   // Handle multi-input cases by blending single-input shuffles.
14631   if (NumV2Elements > 0)
14632     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2, Mask,
14633                                                 Subtarget, DAG);
14634 
14635   // The fallback path for single-input shuffles widens this into two v8i16
14636   // vectors with unpacks, shuffles those, and then pulls them back together
14637   // with a pack.
14638   SDValue V = V1;
14639 
14640   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14641   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14642   for (int i = 0; i < 16; ++i)
14643     if (Mask[i] >= 0)
14644       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
14645 
14646   SDValue VLoHalf, VHiHalf;
14647   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
14648   // them out and avoid using UNPCK{L,H} to extract the elements of V as
14649   // i16s.
14650   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
14651       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
14652     // Use a mask to drop the high bytes.
14653     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
14654     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
14655                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
14656 
14657     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
14658     VHiHalf = DAG.getUNDEF(MVT::v8i16);
14659 
14660     // Squash the masks to point directly into VLoHalf.
14661     for (int &M : LoBlendMask)
14662       if (M >= 0)
14663         M /= 2;
14664     for (int &M : HiBlendMask)
14665       if (M >= 0)
14666         M /= 2;
14667   } else {
14668     // Otherwise just unpack the low half of V into VLoHalf and the high half into
14669     // VHiHalf so that we can blend them as i16s.
14670     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
14671 
14672     VLoHalf = DAG.getBitcast(
14673         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
14674     VHiHalf = DAG.getBitcast(
14675         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
14676   }
14677 
14678   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
14679   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
14680 
14681   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
14682 }
14683 
14684 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
14685 ///
14686 /// This routine breaks down the specific type of 128-bit shuffle and
14687 /// dispatches to the lowering routines accordingly.
lower128BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)14688 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14689                                   MVT VT, SDValue V1, SDValue V2,
14690                                   const APInt &Zeroable,
14691                                   const X86Subtarget &Subtarget,
14692                                   SelectionDAG &DAG) {
14693   switch (VT.SimpleTy) {
14694   case MVT::v2i64:
14695     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14696   case MVT::v2f64:
14697     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14698   case MVT::v4i32:
14699     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14700   case MVT::v4f32:
14701     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14702   case MVT::v8i16:
14703     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14704   case MVT::v16i8:
14705     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14706 
14707   default:
14708     llvm_unreachable("Unimplemented!");
14709   }
14710 }
14711 
14712 /// Generic routine to split vector shuffle into half-sized shuffles.
14713 ///
14714 /// This routine just extracts two subvectors, shuffles them independently, and
14715 /// then concatenates them back together. This should work effectively with all
14716 /// AVX vector shuffle types.
splitAndLowerShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)14717 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
14718                                     SDValue V2, ArrayRef<int> Mask,
14719                                     SelectionDAG &DAG) {
14720   assert(VT.getSizeInBits() >= 256 &&
14721          "Only for 256-bit or wider vector shuffles!");
14722   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
14723   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
14724 
14725   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
14726   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
14727 
14728   int NumElements = VT.getVectorNumElements();
14729   int SplitNumElements = NumElements / 2;
14730   MVT ScalarVT = VT.getVectorElementType();
14731   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
14732 
14733   // Rather than splitting build-vectors, just build two narrower build
14734   // vectors. This helps shuffling with splats and zeros.
14735   auto SplitVector = [&](SDValue V) {
14736     V = peekThroughBitcasts(V);
14737 
14738     MVT OrigVT = V.getSimpleValueType();
14739     int OrigNumElements = OrigVT.getVectorNumElements();
14740     int OrigSplitNumElements = OrigNumElements / 2;
14741     MVT OrigScalarVT = OrigVT.getVectorElementType();
14742     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
14743 
14744     SDValue LoV, HiV;
14745 
14746     auto *BV = dyn_cast<BuildVectorSDNode>(V);
14747     if (!BV) {
14748       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
14749                         DAG.getIntPtrConstant(0, DL));
14750       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
14751                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
14752     } else {
14753 
14754       SmallVector<SDValue, 16> LoOps, HiOps;
14755       for (int i = 0; i < OrigSplitNumElements; ++i) {
14756         LoOps.push_back(BV->getOperand(i));
14757         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
14758       }
14759       LoV = DAG.getBuildVector(OrigSplitVT, DL, LoOps);
14760       HiV = DAG.getBuildVector(OrigSplitVT, DL, HiOps);
14761     }
14762     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
14763                           DAG.getBitcast(SplitVT, HiV));
14764   };
14765 
14766   SDValue LoV1, HiV1, LoV2, HiV2;
14767   std::tie(LoV1, HiV1) = SplitVector(V1);
14768   std::tie(LoV2, HiV2) = SplitVector(V2);
14769 
14770   // Now create two 4-way blends of these half-width vectors.
14771   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
14772     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
14773     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
14774     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
14775     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
14776     for (int i = 0; i < SplitNumElements; ++i) {
14777       int M = HalfMask[i];
14778       if (M >= NumElements) {
14779         if (M >= NumElements + SplitNumElements)
14780           UseHiV2 = true;
14781         else
14782           UseLoV2 = true;
14783         V2BlendMask[i] = M - NumElements;
14784         BlendMask[i] = SplitNumElements + i;
14785       } else if (M >= 0) {
14786         if (M >= SplitNumElements)
14787           UseHiV1 = true;
14788         else
14789           UseLoV1 = true;
14790         V1BlendMask[i] = M;
14791         BlendMask[i] = i;
14792       }
14793     }
14794 
14795     // Because the lowering happens after all combining takes place, we need to
14796     // manually combine these blend masks as much as possible so that we create
14797     // a minimal number of high-level vector shuffle nodes.
14798 
14799     // First try just blending the halves of V1 or V2.
14800     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
14801       return DAG.getUNDEF(SplitVT);
14802     if (!UseLoV2 && !UseHiV2)
14803       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14804     if (!UseLoV1 && !UseHiV1)
14805       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14806 
14807     SDValue V1Blend, V2Blend;
14808     if (UseLoV1 && UseHiV1) {
14809       V1Blend =
14810         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14811     } else {
14812       // We only use half of V1 so map the usage down into the final blend mask.
14813       V1Blend = UseLoV1 ? LoV1 : HiV1;
14814       for (int i = 0; i < SplitNumElements; ++i)
14815         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
14816           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
14817     }
14818     if (UseLoV2 && UseHiV2) {
14819       V2Blend =
14820         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14821     } else {
14822       // We only use half of V2 so map the usage down into the final blend mask.
14823       V2Blend = UseLoV2 ? LoV2 : HiV2;
14824       for (int i = 0; i < SplitNumElements; ++i)
14825         if (BlendMask[i] >= SplitNumElements)
14826           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
14827     }
14828     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
14829   };
14830   SDValue Lo = HalfBlend(LoMask);
14831   SDValue Hi = HalfBlend(HiMask);
14832   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
14833 }
14834 
14835 /// Either split a vector in halves or decompose the shuffles and the
14836 /// blend.
14837 ///
14838 /// This is provided as a good fallback for many lowerings of non-single-input
14839 /// shuffles with more than one 128-bit lane. In those cases, we want to select
14840 /// between splitting the shuffle into 128-bit components and stitching those
14841 /// back together vs. extracting the single-input shuffles and blending those
14842 /// results.
lowerShuffleAsSplitOrBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14843 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
14844                                           SDValue V2, ArrayRef<int> Mask,
14845                                           const X86Subtarget &Subtarget,
14846                                           SelectionDAG &DAG) {
14847   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
14848          "shuffles as it could then recurse on itself.");
14849   int Size = Mask.size();
14850 
14851   // If this can be modeled as a broadcast of two elements followed by a blend,
14852   // prefer that lowering. This is especially important because broadcasts can
14853   // often fold with memory operands.
14854   auto DoBothBroadcast = [&] {
14855     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
14856     for (int M : Mask)
14857       if (M >= Size) {
14858         if (V2BroadcastIdx < 0)
14859           V2BroadcastIdx = M - Size;
14860         else if (M - Size != V2BroadcastIdx)
14861           return false;
14862       } else if (M >= 0) {
14863         if (V1BroadcastIdx < 0)
14864           V1BroadcastIdx = M;
14865         else if (M != V1BroadcastIdx)
14866           return false;
14867       }
14868     return true;
14869   };
14870   if (DoBothBroadcast())
14871     return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
14872                                                 Subtarget, DAG);
14873 
14874   // If the inputs all stem from a single 128-bit lane of each input, then we
14875   // split them rather than blending because the split will decompose to
14876   // unusually few instructions.
14877   int LaneCount = VT.getSizeInBits() / 128;
14878   int LaneSize = Size / LaneCount;
14879   SmallBitVector LaneInputs[2];
14880   LaneInputs[0].resize(LaneCount, false);
14881   LaneInputs[1].resize(LaneCount, false);
14882   for (int i = 0; i < Size; ++i)
14883     if (Mask[i] >= 0)
14884       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
14885   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
14886     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
14887 
14888   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
14889   // that the decomposed single-input shuffles don't end up here.
14890   return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, Subtarget,
14891                                               DAG);
14892 }
14893 
14894 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
14895 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
lowerShuffleAsLanePermuteAndSHUFP(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)14896 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
14897                                                  SDValue V1, SDValue V2,
14898                                                  ArrayRef<int> Mask,
14899                                                  SelectionDAG &DAG) {
14900   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
14901 
14902   int LHSMask[4] = {-1, -1, -1, -1};
14903   int RHSMask[4] = {-1, -1, -1, -1};
14904   unsigned SHUFPMask = 0;
14905 
14906   // As SHUFPD uses a single LHS/RHS element per lane, we can always
14907   // perform the shuffle once the lanes have been shuffled in place.
14908   for (int i = 0; i != 4; ++i) {
14909     int M = Mask[i];
14910     if (M < 0)
14911       continue;
14912     int LaneBase = i & ~1;
14913     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
14914     LaneMask[LaneBase + (M & 1)] = M;
14915     SHUFPMask |= (M & 1) << i;
14916   }
14917 
14918   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
14919   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
14920   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
14921                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
14922 }
14923 
14924 /// Lower a vector shuffle crossing multiple 128-bit lanes as
14925 /// a lane permutation followed by a per-lane permutation.
14926 ///
14927 /// This is mainly for cases where we can have non-repeating permutes
14928 /// in each lane.
14929 ///
14930 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
14931 /// we should investigate merging them.
lowerShuffleAsLanePermuteAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)14932 static SDValue lowerShuffleAsLanePermuteAndPermute(
14933     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14934     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14935   int NumElts = VT.getVectorNumElements();
14936   int NumLanes = VT.getSizeInBits() / 128;
14937   int NumEltsPerLane = NumElts / NumLanes;
14938 
14939   SmallVector<int, 4> SrcLaneMask(NumLanes, SM_SentinelUndef);
14940   SmallVector<int, 16> PermMask(NumElts, SM_SentinelUndef);
14941 
14942   for (int i = 0; i != NumElts; ++i) {
14943     int M = Mask[i];
14944     if (M < 0)
14945       continue;
14946 
14947     // Ensure that each lane comes from a single source lane.
14948     int SrcLane = M / NumEltsPerLane;
14949     int DstLane = i / NumEltsPerLane;
14950     if (!isUndefOrEqual(SrcLaneMask[DstLane], SrcLane))
14951       return SDValue();
14952     SrcLaneMask[DstLane] = SrcLane;
14953 
14954     PermMask[i] = (DstLane * NumEltsPerLane) + (M % NumEltsPerLane);
14955   }
14956 
14957   // Make sure we set all elements of the lane mask, to avoid undef propagation.
14958   SmallVector<int, 16> LaneMask(NumElts, SM_SentinelUndef);
14959   for (int DstLane = 0; DstLane != NumLanes; ++DstLane) {
14960     int SrcLane = SrcLaneMask[DstLane];
14961     if (0 <= SrcLane)
14962       for (int j = 0; j != NumEltsPerLane; ++j) {
14963         LaneMask[(DstLane * NumEltsPerLane) + j] =
14964             (SrcLane * NumEltsPerLane) + j;
14965       }
14966   }
14967 
14968   // If we're only shuffling a single lowest lane and the rest are identity
14969   // then don't bother.
14970   // TODO - isShuffleMaskInputInPlace could be extended to something like this.
14971   int NumIdentityLanes = 0;
14972   bool OnlyShuffleLowestLane = true;
14973   for (int i = 0; i != NumLanes; ++i) {
14974     if (isSequentialOrUndefInRange(PermMask, i * NumEltsPerLane, NumEltsPerLane,
14975                                    i * NumEltsPerLane))
14976       NumIdentityLanes++;
14977     else if (SrcLaneMask[i] != 0 && SrcLaneMask[i] != NumLanes)
14978       OnlyShuffleLowestLane = false;
14979   }
14980   if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
14981     return SDValue();
14982 
14983   SDValue LanePermute = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
14984   return DAG.getVectorShuffle(VT, DL, LanePermute, DAG.getUNDEF(VT), PermMask);
14985 }
14986 
14987 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
14988 /// source with a lane permutation.
14989 ///
14990 /// This lowering strategy results in four instructions in the worst case for a
14991 /// single-input cross lane shuffle which is lower than any other fully general
14992 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
14993 /// shuffle pattern should be handled prior to trying this lowering.
lowerShuffleAsLanePermuteAndShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)14994 static SDValue lowerShuffleAsLanePermuteAndShuffle(
14995     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14996     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14997   // FIXME: This should probably be generalized for 512-bit vectors as well.
14998   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
14999   int Size = Mask.size();
15000   int LaneSize = Size / 2;
15001 
15002   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15003   // Only do this if the elements aren't all from the lower lane,
15004   // otherwise we're (probably) better off doing a split.
15005   if (VT == MVT::v4f64 &&
15006       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15007     if (SDValue V =
15008             lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG))
15009       return V;
15010 
15011   // If there are only inputs from one 128-bit lane, splitting will in fact be
15012   // less expensive. The flags track whether the given lane contains an element
15013   // that crosses to another lane.
15014   if (!Subtarget.hasAVX2()) {
15015     bool LaneCrossing[2] = {false, false};
15016     for (int i = 0; i < Size; ++i)
15017       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15018         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15019     if (!LaneCrossing[0] || !LaneCrossing[1])
15020       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15021   } else {
15022     bool LaneUsed[2] = {false, false};
15023     for (int i = 0; i < Size; ++i)
15024       if (Mask[i] >= 0)
15025         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15026     if (!LaneUsed[0] || !LaneUsed[1])
15027       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15028   }
15029 
15030   // TODO - we could support shuffling V2 in the Flipped input.
15031   assert(V2.isUndef() &&
15032          "This last part of this routine only works on single input shuffles");
15033 
15034   SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
15035   for (int i = 0; i < Size; ++i) {
15036     int &M = InLaneMask[i];
15037     if (M < 0)
15038       continue;
15039     if (((M % Size) / LaneSize) != (i / LaneSize))
15040       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15041   }
15042   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15043          "In-lane shuffle mask expected");
15044 
15045   // Flip the lanes, and shuffle the results which should now be in-lane.
15046   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15047   SDValue Flipped = DAG.getBitcast(PVT, V1);
15048   Flipped =
15049       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15050   Flipped = DAG.getBitcast(VT, Flipped);
15051   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15052 }
15053 
15054 /// Handle lowering 2-lane 128-bit shuffles.
lowerV2X128Shuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15055 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
15056                                   SDValue V2, ArrayRef<int> Mask,
15057                                   const APInt &Zeroable,
15058                                   const X86Subtarget &Subtarget,
15059                                   SelectionDAG &DAG) {
15060   // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15061   if (Subtarget.hasAVX2() && V2.isUndef())
15062     return SDValue();
15063 
15064   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15065 
15066   SmallVector<int, 4> WidenedMask;
15067   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15068     return SDValue();
15069 
15070   bool IsLowZero = (Zeroable & 0x3) == 0x3;
15071   bool IsHighZero = (Zeroable & 0xc) == 0xc;
15072 
15073   // Try to use an insert into a zero vector.
15074   if (WidenedMask[0] == 0 && IsHighZero) {
15075     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15076     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15077                               DAG.getIntPtrConstant(0, DL));
15078     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15079                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
15080                        DAG.getIntPtrConstant(0, DL));
15081   }
15082 
15083   // TODO: If minimizing size and one of the inputs is a zero vector and the
15084   // the zero vector has only one use, we could use a VPERM2X128 to save the
15085   // instruction bytes needed to explicitly generate the zero vector.
15086 
15087   // Blends are faster and handle all the non-lane-crossing cases.
15088   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15089                                           Subtarget, DAG))
15090     return Blend;
15091 
15092   // If either input operand is a zero vector, use VPERM2X128 because its mask
15093   // allows us to replace the zero input with an implicit zero.
15094   if (!IsLowZero && !IsHighZero) {
15095     // Check for patterns which can be matched with a single insert of a 128-bit
15096     // subvector.
15097     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
15098     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
15099 
15100       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15101       // this will likely become vinsertf128 which can't fold a 256-bit memop.
15102       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
15103         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15104         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
15105                                      OnlyUsesV1 ? V1 : V2,
15106                                      DAG.getIntPtrConstant(0, DL));
15107         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15108                            DAG.getIntPtrConstant(2, DL));
15109       }
15110     }
15111 
15112     // Try to use SHUF128 if possible.
15113     if (Subtarget.hasVLX()) {
15114       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15115         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15116                             ((WidenedMask[1] % 2) << 1);
15117         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
15118                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
15119       }
15120     }
15121   }
15122 
15123   // Otherwise form a 128-bit permutation. After accounting for undefs,
15124   // convert the 64-bit shuffle mask selection values into 128-bit
15125   // selection bits by dividing the indexes by 2 and shifting into positions
15126   // defined by a vperm2*128 instruction's immediate control byte.
15127 
15128   // The immediate permute control byte looks like this:
15129   //    [1:0] - select 128 bits from sources for low half of destination
15130   //    [2]   - ignore
15131   //    [3]   - zero low half of destination
15132   //    [5:4] - select 128 bits from sources for high half of destination
15133   //    [6]   - ignore
15134   //    [7]   - zero high half of destination
15135 
15136   assert((WidenedMask[0] >= 0 || IsLowZero) &&
15137          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
15138 
15139   unsigned PermMask = 0;
15140   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
15141   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
15142 
15143   // Check the immediate mask and replace unused sources with undef.
15144   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
15145     V1 = DAG.getUNDEF(VT);
15146   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
15147     V2 = DAG.getUNDEF(VT);
15148 
15149   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
15150                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
15151 }
15152 
15153 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
15154 /// shuffling each lane.
15155 ///
15156 /// This attempts to create a repeated lane shuffle where each lane uses one
15157 /// or two of the lanes of the inputs. The lanes of the input vectors are
15158 /// shuffled in one or two independent shuffles to get the lanes into the
15159 /// position needed by the final shuffle.
lowerShuffleAsLanePermuteAndRepeatedMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15160 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
15161     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15162     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15163   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
15164 
15165   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
15166     return SDValue();
15167 
15168   int NumElts = Mask.size();
15169   int NumLanes = VT.getSizeInBits() / 128;
15170   int NumLaneElts = 128 / VT.getScalarSizeInBits();
15171   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
15172   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
15173 
15174   // First pass will try to fill in the RepeatMask from lanes that need two
15175   // sources.
15176   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15177     int Srcs[2] = {-1, -1};
15178     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
15179     for (int i = 0; i != NumLaneElts; ++i) {
15180       int M = Mask[(Lane * NumLaneElts) + i];
15181       if (M < 0)
15182         continue;
15183       // Determine which of the possible input lanes (NumLanes from each source)
15184       // this element comes from. Assign that as one of the sources for this
15185       // lane. We can assign up to 2 sources for this lane. If we run out
15186       // sources we can't do anything.
15187       int LaneSrc = M / NumLaneElts;
15188       int Src;
15189       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
15190         Src = 0;
15191       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
15192         Src = 1;
15193       else
15194         return SDValue();
15195 
15196       Srcs[Src] = LaneSrc;
15197       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
15198     }
15199 
15200     // If this lane has two sources, see if it fits with the repeat mask so far.
15201     if (Srcs[1] < 0)
15202       continue;
15203 
15204     LaneSrcs[Lane][0] = Srcs[0];
15205     LaneSrcs[Lane][1] = Srcs[1];
15206 
15207     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
15208       assert(M1.size() == M2.size() && "Unexpected mask size");
15209       for (int i = 0, e = M1.size(); i != e; ++i)
15210         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
15211           return false;
15212       return true;
15213     };
15214 
15215     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
15216       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
15217       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
15218         int M = Mask[i];
15219         if (M < 0)
15220           continue;
15221         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
15222                "Unexpected mask element");
15223         MergedMask[i] = M;
15224       }
15225     };
15226 
15227     if (MatchMasks(InLaneMask, RepeatMask)) {
15228       // Merge this lane mask into the final repeat mask.
15229       MergeMasks(InLaneMask, RepeatMask);
15230       continue;
15231     }
15232 
15233     // Didn't find a match. Swap the operands and try again.
15234     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
15235     ShuffleVectorSDNode::commuteMask(InLaneMask);
15236 
15237     if (MatchMasks(InLaneMask, RepeatMask)) {
15238       // Merge this lane mask into the final repeat mask.
15239       MergeMasks(InLaneMask, RepeatMask);
15240       continue;
15241     }
15242 
15243     // Couldn't find a match with the operands in either order.
15244     return SDValue();
15245   }
15246 
15247   // Now handle any lanes with only one source.
15248   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15249     // If this lane has already been processed, skip it.
15250     if (LaneSrcs[Lane][0] >= 0)
15251       continue;
15252 
15253     for (int i = 0; i != NumLaneElts; ++i) {
15254       int M = Mask[(Lane * NumLaneElts) + i];
15255       if (M < 0)
15256         continue;
15257 
15258       // If RepeatMask isn't defined yet we can define it ourself.
15259       if (RepeatMask[i] < 0)
15260         RepeatMask[i] = M % NumLaneElts;
15261 
15262       if (RepeatMask[i] < NumElts) {
15263         if (RepeatMask[i] != M % NumLaneElts)
15264           return SDValue();
15265         LaneSrcs[Lane][0] = M / NumLaneElts;
15266       } else {
15267         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
15268           return SDValue();
15269         LaneSrcs[Lane][1] = M / NumLaneElts;
15270       }
15271     }
15272 
15273     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
15274       return SDValue();
15275   }
15276 
15277   SmallVector<int, 16> NewMask(NumElts, -1);
15278   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15279     int Src = LaneSrcs[Lane][0];
15280     for (int i = 0; i != NumLaneElts; ++i) {
15281       int M = -1;
15282       if (Src >= 0)
15283         M = Src * NumLaneElts + i;
15284       NewMask[Lane * NumLaneElts + i] = M;
15285     }
15286   }
15287   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15288   // Ensure we didn't get back the shuffle we started with.
15289   // FIXME: This is a hack to make up for some splat handling code in
15290   // getVectorShuffle.
15291   if (isa<ShuffleVectorSDNode>(NewV1) &&
15292       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
15293     return SDValue();
15294 
15295   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15296     int Src = LaneSrcs[Lane][1];
15297     for (int i = 0; i != NumLaneElts; ++i) {
15298       int M = -1;
15299       if (Src >= 0)
15300         M = Src * NumLaneElts + i;
15301       NewMask[Lane * NumLaneElts + i] = M;
15302     }
15303   }
15304   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15305   // Ensure we didn't get back the shuffle we started with.
15306   // FIXME: This is a hack to make up for some splat handling code in
15307   // getVectorShuffle.
15308   if (isa<ShuffleVectorSDNode>(NewV2) &&
15309       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
15310     return SDValue();
15311 
15312   for (int i = 0; i != NumElts; ++i) {
15313     NewMask[i] = RepeatMask[i % NumLaneElts];
15314     if (NewMask[i] < 0)
15315       continue;
15316 
15317     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
15318   }
15319   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
15320 }
15321 
15322 /// If the input shuffle mask results in a vector that is undefined in all upper
15323 /// or lower half elements and that mask accesses only 2 halves of the
15324 /// shuffle's operands, return true. A mask of half the width with mask indexes
15325 /// adjusted to access the extracted halves of the original shuffle operands is
15326 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
15327 /// lower half of each input operand is accessed.
15328 static bool
getHalfShuffleMask(ArrayRef<int> Mask,MutableArrayRef<int> HalfMask,int & HalfIdx1,int & HalfIdx2)15329 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
15330                    int &HalfIdx1, int &HalfIdx2) {
15331   assert((Mask.size() == HalfMask.size() * 2) &&
15332          "Expected input mask to be twice as long as output");
15333 
15334   // Exactly one half of the result must be undef to allow narrowing.
15335   bool UndefLower = isUndefLowerHalf(Mask);
15336   bool UndefUpper = isUndefUpperHalf(Mask);
15337   if (UndefLower == UndefUpper)
15338     return false;
15339 
15340   unsigned HalfNumElts = HalfMask.size();
15341   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
15342   HalfIdx1 = -1;
15343   HalfIdx2 = -1;
15344   for (unsigned i = 0; i != HalfNumElts; ++i) {
15345     int M = Mask[i + MaskIndexOffset];
15346     if (M < 0) {
15347       HalfMask[i] = M;
15348       continue;
15349     }
15350 
15351     // Determine which of the 4 half vectors this element is from.
15352     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
15353     int HalfIdx = M / HalfNumElts;
15354 
15355     // Determine the element index into its half vector source.
15356     int HalfElt = M % HalfNumElts;
15357 
15358     // We can shuffle with up to 2 half vectors, set the new 'half'
15359     // shuffle mask accordingly.
15360     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
15361       HalfMask[i] = HalfElt;
15362       HalfIdx1 = HalfIdx;
15363       continue;
15364     }
15365     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
15366       HalfMask[i] = HalfElt + HalfNumElts;
15367       HalfIdx2 = HalfIdx;
15368       continue;
15369     }
15370 
15371     // Too many half vectors referenced.
15372     return false;
15373   }
15374 
15375   return true;
15376 }
15377 
15378 /// Given the output values from getHalfShuffleMask(), create a half width
15379 /// shuffle of extracted vectors followed by an insert back to full width.
getShuffleHalfVectors(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> HalfMask,int HalfIdx1,int HalfIdx2,bool UndefLower,SelectionDAG & DAG,bool UseConcat=false)15380 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
15381                                      ArrayRef<int> HalfMask, int HalfIdx1,
15382                                      int HalfIdx2, bool UndefLower,
15383                                      SelectionDAG &DAG, bool UseConcat = false) {
15384   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
15385   assert(V1.getValueType().isSimple() && "Expecting only simple types");
15386 
15387   MVT VT = V1.getSimpleValueType();
15388   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15389   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15390 
15391   auto getHalfVector = [&](int HalfIdx) {
15392     if (HalfIdx < 0)
15393       return DAG.getUNDEF(HalfVT);
15394     SDValue V = (HalfIdx < 2 ? V1 : V2);
15395     HalfIdx = (HalfIdx % 2) * HalfNumElts;
15396     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
15397                        DAG.getIntPtrConstant(HalfIdx, DL));
15398   };
15399 
15400   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
15401   SDValue Half1 = getHalfVector(HalfIdx1);
15402   SDValue Half2 = getHalfVector(HalfIdx2);
15403   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
15404   if (UseConcat) {
15405     SDValue Op0 = V;
15406     SDValue Op1 = DAG.getUNDEF(HalfVT);
15407     if (UndefLower)
15408       std::swap(Op0, Op1);
15409     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
15410   }
15411 
15412   unsigned Offset = UndefLower ? HalfNumElts : 0;
15413   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
15414                      DAG.getIntPtrConstant(Offset, DL));
15415 }
15416 
15417 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
15418 /// This allows for fast cases such as subvector extraction/insertion
15419 /// or shuffling smaller vector types which can lower more efficiently.
lowerShuffleWithUndefHalf(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15420 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
15421                                          SDValue V2, ArrayRef<int> Mask,
15422                                          const X86Subtarget &Subtarget,
15423                                          SelectionDAG &DAG) {
15424   assert((VT.is256BitVector() || VT.is512BitVector()) &&
15425          "Expected 256-bit or 512-bit vector");
15426 
15427   bool UndefLower = isUndefLowerHalf(Mask);
15428   if (!UndefLower && !isUndefUpperHalf(Mask))
15429     return SDValue();
15430 
15431   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
15432          "Completely undef shuffle mask should have been simplified already");
15433 
15434   // Upper half is undef and lower half is whole upper subvector.
15435   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15436   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15437   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15438   if (!UndefLower &&
15439       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
15440     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15441                              DAG.getIntPtrConstant(HalfNumElts, DL));
15442     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15443                        DAG.getIntPtrConstant(0, DL));
15444   }
15445 
15446   // Lower half is undef and upper half is whole lower subvector.
15447   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15448   if (UndefLower &&
15449       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
15450     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15451                              DAG.getIntPtrConstant(0, DL));
15452     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15453                        DAG.getIntPtrConstant(HalfNumElts, DL));
15454   }
15455 
15456   int HalfIdx1, HalfIdx2;
15457   SmallVector<int, 8> HalfMask(HalfNumElts);
15458   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
15459     return SDValue();
15460 
15461   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
15462 
15463   // Only shuffle the halves of the inputs when useful.
15464   unsigned NumLowerHalves =
15465       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
15466   unsigned NumUpperHalves =
15467       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
15468   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
15469 
15470   // Determine the larger pattern of undef/halves, then decide if it's worth
15471   // splitting the shuffle based on subtarget capabilities and types.
15472   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
15473   if (!UndefLower) {
15474     // XXXXuuuu: no insert is needed.
15475     // Always extract lowers when setting lower - these are all free subreg ops.
15476     if (NumUpperHalves == 0)
15477       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15478                                    UndefLower, DAG);
15479 
15480     if (NumUpperHalves == 1) {
15481       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
15482       if (Subtarget.hasAVX2()) {
15483         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
15484         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
15485             !is128BitUnpackShuffleMask(HalfMask) &&
15486             (!isSingleSHUFPSMask(HalfMask) ||
15487              Subtarget.hasFastVariableShuffle()))
15488           return SDValue();
15489         // If this is a unary shuffle (assume that the 2nd operand is
15490         // canonicalized to undef), then we can use vpermpd. Otherwise, we
15491         // are better off extracting the upper half of 1 operand and using a
15492         // narrow shuffle.
15493         if (EltWidth == 64 && V2.isUndef())
15494           return SDValue();
15495       }
15496       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15497       if (Subtarget.hasAVX512() && VT.is512BitVector())
15498         return SDValue();
15499       // Extract + narrow shuffle is better than the wide alternative.
15500       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15501                                    UndefLower, DAG);
15502     }
15503 
15504     // Don't extract both uppers, instead shuffle and then extract.
15505     assert(NumUpperHalves == 2 && "Half vector count went wrong");
15506     return SDValue();
15507   }
15508 
15509   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
15510   if (NumUpperHalves == 0) {
15511     // AVX2 has efficient 64-bit element cross-lane shuffles.
15512     // TODO: Refine to account for unary shuffle, splat, and other masks?
15513     if (Subtarget.hasAVX2() && EltWidth == 64)
15514       return SDValue();
15515     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15516     if (Subtarget.hasAVX512() && VT.is512BitVector())
15517       return SDValue();
15518     // Narrow shuffle + insert is better than the wide alternative.
15519     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15520                                  UndefLower, DAG);
15521   }
15522 
15523   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
15524   return SDValue();
15525 }
15526 
15527 /// Test whether the specified input (0 or 1) is in-place blended by the
15528 /// given mask.
15529 ///
15530 /// This returns true if the elements from a particular input are already in the
15531 /// slot required by the given mask and require no permutation.
isShuffleMaskInputInPlace(int Input,ArrayRef<int> Mask)15532 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
15533   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
15534   int Size = Mask.size();
15535   for (int i = 0; i < Size; ++i)
15536     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
15537       return false;
15538 
15539   return true;
15540 }
15541 
15542 /// Handle case where shuffle sources are coming from the same 128-bit lane and
15543 /// every lane can be represented as the same repeating mask - allowing us to
15544 /// shuffle the sources with the repeating shuffle and then permute the result
15545 /// to the destination lanes.
lowerShuffleAsRepeatedMaskAndLanePermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15546 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
15547     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15548     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15549   int NumElts = VT.getVectorNumElements();
15550   int NumLanes = VT.getSizeInBits() / 128;
15551   int NumLaneElts = NumElts / NumLanes;
15552 
15553   // On AVX2 we may be able to just shuffle the lowest elements and then
15554   // broadcast the result.
15555   if (Subtarget.hasAVX2()) {
15556     for (unsigned BroadcastSize : {16, 32, 64}) {
15557       if (BroadcastSize <= VT.getScalarSizeInBits())
15558         continue;
15559       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
15560 
15561       // Attempt to match a repeating pattern every NumBroadcastElts,
15562       // accounting for UNDEFs but only references the lowest 128-bit
15563       // lane of the inputs.
15564       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
15565         for (int i = 0; i != NumElts; i += NumBroadcastElts)
15566           for (int j = 0; j != NumBroadcastElts; ++j) {
15567             int M = Mask[i + j];
15568             if (M < 0)
15569               continue;
15570             int &R = RepeatMask[j];
15571             if (0 != ((M % NumElts) / NumLaneElts))
15572               return false;
15573             if (0 <= R && R != M)
15574               return false;
15575             R = M;
15576           }
15577         return true;
15578       };
15579 
15580       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
15581       if (!FindRepeatingBroadcastMask(RepeatMask))
15582         continue;
15583 
15584       // Shuffle the (lowest) repeated elements in place for broadcast.
15585       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
15586 
15587       // Shuffle the actual broadcast.
15588       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
15589       for (int i = 0; i != NumElts; i += NumBroadcastElts)
15590         for (int j = 0; j != NumBroadcastElts; ++j)
15591           BroadcastMask[i + j] = j;
15592       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
15593                                   BroadcastMask);
15594     }
15595   }
15596 
15597   // Bail if the shuffle mask doesn't cross 128-bit lanes.
15598   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
15599     return SDValue();
15600 
15601   // Bail if we already have a repeated lane shuffle mask.
15602   SmallVector<int, 8> RepeatedShuffleMask;
15603   if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
15604     return SDValue();
15605 
15606   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
15607   // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
15608   int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
15609   int NumSubLanes = NumLanes * SubLaneScale;
15610   int NumSubLaneElts = NumLaneElts / SubLaneScale;
15611 
15612   // Check that all the sources are coming from the same lane and see if we can
15613   // form a repeating shuffle mask (local to each sub-lane). At the same time,
15614   // determine the source sub-lane for each destination sub-lane.
15615   int TopSrcSubLane = -1;
15616   SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
15617   SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
15618       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
15619       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
15620 
15621   for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
15622     // Extract the sub-lane mask, check that it all comes from the same lane
15623     // and normalize the mask entries to come from the first lane.
15624     int SrcLane = -1;
15625     SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
15626     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15627       int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
15628       if (M < 0)
15629         continue;
15630       int Lane = (M % NumElts) / NumLaneElts;
15631       if ((0 <= SrcLane) && (SrcLane != Lane))
15632         return SDValue();
15633       SrcLane = Lane;
15634       int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
15635       SubLaneMask[Elt] = LocalM;
15636     }
15637 
15638     // Whole sub-lane is UNDEF.
15639     if (SrcLane < 0)
15640       continue;
15641 
15642     // Attempt to match against the candidate repeated sub-lane masks.
15643     for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
15644       auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
15645         for (int i = 0; i != NumSubLaneElts; ++i) {
15646           if (M1[i] < 0 || M2[i] < 0)
15647             continue;
15648           if (M1[i] != M2[i])
15649             return false;
15650         }
15651         return true;
15652       };
15653 
15654       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
15655       if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
15656         continue;
15657 
15658       // Merge the sub-lane mask into the matching repeated sub-lane mask.
15659       for (int i = 0; i != NumSubLaneElts; ++i) {
15660         int M = SubLaneMask[i];
15661         if (M < 0)
15662           continue;
15663         assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
15664                "Unexpected mask element");
15665         RepeatedSubLaneMask[i] = M;
15666       }
15667 
15668       // Track the top most source sub-lane - by setting the remaining to UNDEF
15669       // we can greatly simplify shuffle matching.
15670       int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
15671       TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
15672       Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
15673       break;
15674     }
15675 
15676     // Bail if we failed to find a matching repeated sub-lane mask.
15677     if (Dst2SrcSubLanes[DstSubLane] < 0)
15678       return SDValue();
15679   }
15680   assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
15681          "Unexpected source lane");
15682 
15683   // Create a repeating shuffle mask for the entire vector.
15684   SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
15685   for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
15686     int Lane = SubLane / SubLaneScale;
15687     auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
15688     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15689       int M = RepeatedSubLaneMask[Elt];
15690       if (M < 0)
15691         continue;
15692       int Idx = (SubLane * NumSubLaneElts) + Elt;
15693       RepeatedMask[Idx] = M + (Lane * NumLaneElts);
15694     }
15695   }
15696   SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
15697 
15698   // Shuffle each source sub-lane to its destination.
15699   SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
15700   for (int i = 0; i != NumElts; i += NumSubLaneElts) {
15701     int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
15702     if (SrcSubLane < 0)
15703       continue;
15704     for (int j = 0; j != NumSubLaneElts; ++j)
15705       SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
15706   }
15707 
15708   return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
15709                               SubLaneMask);
15710 }
15711 
matchShuffleWithSHUFPD(MVT VT,SDValue & V1,SDValue & V2,bool & ForceV1Zero,bool & ForceV2Zero,unsigned & ShuffleImm,ArrayRef<int> Mask,const APInt & Zeroable)15712 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
15713                                    bool &ForceV1Zero, bool &ForceV2Zero,
15714                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
15715                                    const APInt &Zeroable) {
15716   int NumElts = VT.getVectorNumElements();
15717   assert(VT.getScalarSizeInBits() == 64 &&
15718          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
15719          "Unexpected data type for VSHUFPD");
15720   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
15721          "Illegal shuffle mask");
15722 
15723   bool ZeroLane[2] = { true, true };
15724   for (int i = 0; i < NumElts; ++i)
15725     ZeroLane[i & 1] &= Zeroable[i];
15726 
15727   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
15728   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
15729   ShuffleImm = 0;
15730   bool ShufpdMask = true;
15731   bool CommutableMask = true;
15732   for (int i = 0; i < NumElts; ++i) {
15733     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
15734       continue;
15735     if (Mask[i] < 0)
15736       return false;
15737     int Val = (i & 6) + NumElts * (i & 1);
15738     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
15739     if (Mask[i] < Val || Mask[i] > Val + 1)
15740       ShufpdMask = false;
15741     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
15742       CommutableMask = false;
15743     ShuffleImm |= (Mask[i] % 2) << i;
15744   }
15745 
15746   if (!ShufpdMask && !CommutableMask)
15747     return false;
15748 
15749   if (!ShufpdMask && CommutableMask)
15750     std::swap(V1, V2);
15751 
15752   ForceV1Zero = ZeroLane[0];
15753   ForceV2Zero = ZeroLane[1];
15754   return true;
15755 }
15756 
lowerShuffleWithSHUFPD(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15757 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
15758                                       SDValue V2, ArrayRef<int> Mask,
15759                                       const APInt &Zeroable,
15760                                       const X86Subtarget &Subtarget,
15761                                       SelectionDAG &DAG) {
15762   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
15763          "Unexpected data type for VSHUFPD");
15764 
15765   unsigned Immediate = 0;
15766   bool ForceV1Zero = false, ForceV2Zero = false;
15767   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
15768                               Mask, Zeroable))
15769     return SDValue();
15770 
15771   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
15772   if (ForceV1Zero)
15773     V1 = getZeroVector(VT, Subtarget, DAG, DL);
15774   if (ForceV2Zero)
15775     V2 = getZeroVector(VT, Subtarget, DAG, DL);
15776 
15777   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15778                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
15779 }
15780 
15781 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
15782 // by zeroable elements in the remaining 24 elements. Turn this into two
15783 // vmovqb instructions shuffled together.
lowerShuffleAsVTRUNCAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)15784 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
15785                                              SDValue V1, SDValue V2,
15786                                              ArrayRef<int> Mask,
15787                                              const APInt &Zeroable,
15788                                              SelectionDAG &DAG) {
15789   assert(VT == MVT::v32i8 && "Unexpected type!");
15790 
15791   // The first 8 indices should be every 8th element.
15792   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
15793     return SDValue();
15794 
15795   // Remaining elements need to be zeroable.
15796   if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
15797     return SDValue();
15798 
15799   V1 = DAG.getBitcast(MVT::v4i64, V1);
15800   V2 = DAG.getBitcast(MVT::v4i64, V2);
15801 
15802   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
15803   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
15804 
15805   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
15806   // the upper bits of the result using an unpckldq.
15807   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
15808                                         { 0, 1, 2, 3, 16, 17, 18, 19,
15809                                           4, 5, 6, 7, 20, 21, 22, 23 });
15810   // Insert the unpckldq into a zero vector to widen to v32i8.
15811   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
15812                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
15813                      DAG.getIntPtrConstant(0, DL));
15814 }
15815 
15816 
15817 /// Handle lowering of 4-lane 64-bit floating point shuffles.
15818 ///
15819 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
15820 /// isn't available.
lowerV4F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15821 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15822                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15823                                  const X86Subtarget &Subtarget,
15824                                  SelectionDAG &DAG) {
15825   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
15826   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
15827   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15828 
15829   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
15830                                      Subtarget, DAG))
15831     return V;
15832 
15833   if (V2.isUndef()) {
15834     // Check for being able to broadcast a single element.
15835     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
15836                                                     Mask, Subtarget, DAG))
15837       return Broadcast;
15838 
15839     // Use low duplicate instructions for masks that match their pattern.
15840     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
15841       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
15842 
15843     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
15844       // Non-half-crossing single input shuffles can be lowered with an
15845       // interleaved permutation.
15846       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
15847                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
15848       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
15849                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
15850     }
15851 
15852     // With AVX2 we have direct support for this permutation.
15853     if (Subtarget.hasAVX2())
15854       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
15855                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15856 
15857     // Try to create an in-lane repeating shuffle mask and then shuffle the
15858     // results into the target lanes.
15859     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15860             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15861       return V;
15862 
15863     // Try to permute the lanes and then use a per-lane permute.
15864     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
15865                                                         Mask, DAG, Subtarget))
15866       return V;
15867 
15868     // Otherwise, fall back.
15869     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
15870                                                DAG, Subtarget);
15871   }
15872 
15873   // Use dedicated unpack instructions for masks that match their pattern.
15874   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
15875     return V;
15876 
15877   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
15878                                           Zeroable, Subtarget, DAG))
15879     return Blend;
15880 
15881   // Check if the blend happens to exactly fit that of SHUFPD.
15882   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
15883                                           Zeroable, Subtarget, DAG))
15884     return Op;
15885 
15886   // If we have lane crossing shuffles AND they don't all come from the lower
15887   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15888   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
15889   // canonicalize to a blend of splat which isn't necessary for this combine.
15890   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
15891       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
15892       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
15893       (V2.getOpcode() != ISD::BUILD_VECTOR))
15894     if (SDValue Op = lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2,
15895                                                        Mask, DAG))
15896       return Op;
15897 
15898   // If we have one input in place, then we can permute the other input and
15899   // blend the result.
15900   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
15901     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
15902                                                 Subtarget, DAG);
15903 
15904   // Try to create an in-lane repeating shuffle mask and then shuffle the
15905   // results into the target lanes.
15906   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15907           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15908     return V;
15909 
15910   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15911   // shuffle. However, if we have AVX2 and either inputs are already in place,
15912   // we will be able to shuffle even across lanes the other input in a single
15913   // instruction so skip this pattern.
15914   if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
15915                                 isShuffleMaskInputInPlace(1, Mask))))
15916     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
15917             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15918       return V;
15919 
15920   // If we have VLX support, we can use VEXPAND.
15921   if (Subtarget.hasVLX())
15922     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
15923                                          DAG, Subtarget))
15924       return V;
15925 
15926   // If we have AVX2 then we always want to lower with a blend because an v4 we
15927   // can fully permute the elements.
15928   if (Subtarget.hasAVX2())
15929     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
15930                                                 Subtarget, DAG);
15931 
15932   // Otherwise fall back on generic lowering.
15933   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
15934                                     Subtarget, DAG);
15935 }
15936 
15937 /// Handle lowering of 4-lane 64-bit integer shuffles.
15938 ///
15939 /// This routine is only called when we have AVX2 and thus a reasonable
15940 /// instruction set for v4i64 shuffling..
lowerV4I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15941 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15942                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15943                                  const X86Subtarget &Subtarget,
15944                                  SelectionDAG &DAG) {
15945   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
15946   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
15947   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15948   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
15949 
15950   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
15951                                      Subtarget, DAG))
15952     return V;
15953 
15954   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
15955                                           Zeroable, Subtarget, DAG))
15956     return Blend;
15957 
15958   // Check for being able to broadcast a single element.
15959   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
15960                                                   Subtarget, DAG))
15961     return Broadcast;
15962 
15963   if (V2.isUndef()) {
15964     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
15965     // can use lower latency instructions that will operate on both lanes.
15966     SmallVector<int, 2> RepeatedMask;
15967     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
15968       SmallVector<int, 4> PSHUFDMask;
15969       scaleShuffleMask<int>(2, RepeatedMask, PSHUFDMask);
15970       return DAG.getBitcast(
15971           MVT::v4i64,
15972           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
15973                       DAG.getBitcast(MVT::v8i32, V1),
15974                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15975     }
15976 
15977     // AVX2 provides a direct instruction for permuting a single input across
15978     // lanes.
15979     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
15980                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15981   }
15982 
15983   // Try to use shift instructions.
15984   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
15985                                           Zeroable, Subtarget, DAG))
15986     return Shift;
15987 
15988   // If we have VLX support, we can use VALIGN or VEXPAND.
15989   if (Subtarget.hasVLX()) {
15990     if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v4i64, V1, V2, Mask,
15991                                               Subtarget, DAG))
15992       return Rotate;
15993 
15994     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
15995                                          DAG, Subtarget))
15996       return V;
15997   }
15998 
15999   // Try to use PALIGNR.
16000   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16001                                                 Subtarget, DAG))
16002     return Rotate;
16003 
16004   // Use dedicated unpack instructions for masks that match their pattern.
16005   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
16006     return V;
16007 
16008   // If we have one input in place, then we can permute the other input and
16009   // blend the result.
16010   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16011     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
16012                                                 Subtarget, DAG);
16013 
16014   // Try to create an in-lane repeating shuffle mask and then shuffle the
16015   // results into the target lanes.
16016   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16017           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16018     return V;
16019 
16020   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16021   // shuffle. However, if we have AVX2 and either inputs are already in place,
16022   // we will be able to shuffle even across lanes the other input in a single
16023   // instruction so skip this pattern.
16024   if (!isShuffleMaskInputInPlace(0, Mask) &&
16025       !isShuffleMaskInputInPlace(1, Mask))
16026     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16027             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16028       return Result;
16029 
16030   // Otherwise fall back on generic blend lowering.
16031   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
16032                                               Subtarget, DAG);
16033 }
16034 
16035 /// Handle lowering of 8-lane 32-bit floating point shuffles.
16036 ///
16037 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
16038 /// isn't available.
lowerV8F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16039 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16040                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16041                                  const X86Subtarget &Subtarget,
16042                                  SelectionDAG &DAG) {
16043   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16044   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16045   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16046 
16047   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
16048                                           Zeroable, Subtarget, DAG))
16049     return Blend;
16050 
16051   // Check for being able to broadcast a single element.
16052   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
16053                                                   Subtarget, DAG))
16054     return Broadcast;
16055 
16056   // If the shuffle mask is repeated in each 128-bit lane, we have many more
16057   // options to efficiently lower the shuffle.
16058   SmallVector<int, 4> RepeatedMask;
16059   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
16060     assert(RepeatedMask.size() == 4 &&
16061            "Repeated masks must be half the mask width!");
16062 
16063     // Use even/odd duplicate instructions for masks that match their pattern.
16064     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
16065       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
16066     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
16067       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
16068 
16069     if (V2.isUndef())
16070       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
16071                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16072 
16073     // Use dedicated unpack instructions for masks that match their pattern.
16074     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
16075       return V;
16076 
16077     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
16078     // have already handled any direct blends.
16079     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
16080   }
16081 
16082   // Try to create an in-lane repeating shuffle mask and then shuffle the
16083   // results into the target lanes.
16084   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16085           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16086     return V;
16087 
16088   // If we have a single input shuffle with different shuffle patterns in the
16089   // two 128-bit lanes use the variable mask to VPERMILPS.
16090   if (V2.isUndef()) {
16091     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16092     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
16093       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
16094 
16095     if (Subtarget.hasAVX2())
16096       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
16097 
16098     // Otherwise, fall back.
16099     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
16100                                                DAG, Subtarget);
16101   }
16102 
16103   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16104   // shuffle.
16105   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16106           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16107     return Result;
16108 
16109   // If we have VLX support, we can use VEXPAND.
16110   if (Subtarget.hasVLX())
16111     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
16112                                          DAG, Subtarget))
16113       return V;
16114 
16115   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16116   // since after split we get a more efficient code using vpunpcklwd and
16117   // vpunpckhwd instrs than vblend.
16118   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
16119     if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
16120                                                Subtarget, DAG))
16121       return V;
16122 
16123   // If we have AVX2 then we always want to lower with a blend because at v8 we
16124   // can fully permute the elements.
16125   if (Subtarget.hasAVX2())
16126     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2, Mask,
16127                                                 Subtarget, DAG);
16128 
16129   // Otherwise fall back on generic lowering.
16130   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
16131                                     Subtarget, DAG);
16132 }
16133 
16134 /// Handle lowering of 8-lane 32-bit integer shuffles.
16135 ///
16136 /// This routine is only called when we have AVX2 and thus a reasonable
16137 /// instruction set for v8i32 shuffling..
lowerV8I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16138 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16139                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16140                                  const X86Subtarget &Subtarget,
16141                                  SelectionDAG &DAG) {
16142   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16143   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16144   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16145   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
16146 
16147   // Whenever we can lower this as a zext, that instruction is strictly faster
16148   // than any alternative. It also allows us to fold memory operands into the
16149   // shuffle in many cases.
16150   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
16151                                                    Zeroable, Subtarget, DAG))
16152     return ZExt;
16153 
16154   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16155   // since after split we get a more efficient code than vblend by using
16156   // vpunpcklwd and vpunpckhwd instrs.
16157   if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
16158       !Subtarget.hasAVX512())
16159     if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask,
16160                                                Subtarget, DAG))
16161       return V;
16162 
16163   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
16164                                           Zeroable, Subtarget, DAG))
16165     return Blend;
16166 
16167   // Check for being able to broadcast a single element.
16168   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
16169                                                   Subtarget, DAG))
16170     return Broadcast;
16171 
16172   // If the shuffle mask is repeated in each 128-bit lane we can use more
16173   // efficient instructions that mirror the shuffles across the two 128-bit
16174   // lanes.
16175   SmallVector<int, 4> RepeatedMask;
16176   bool Is128BitLaneRepeatedShuffle =
16177       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
16178   if (Is128BitLaneRepeatedShuffle) {
16179     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16180     if (V2.isUndef())
16181       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
16182                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16183 
16184     // Use dedicated unpack instructions for masks that match their pattern.
16185     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
16186       return V;
16187   }
16188 
16189   // Try to use shift instructions.
16190   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
16191                                           Zeroable, Subtarget, DAG))
16192     return Shift;
16193 
16194   // If we have VLX support, we can use VALIGN or EXPAND.
16195   if (Subtarget.hasVLX()) {
16196     if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v8i32, V1, V2, Mask,
16197                                               Subtarget, DAG))
16198       return Rotate;
16199 
16200     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
16201                                          DAG, Subtarget))
16202       return V;
16203   }
16204 
16205   // Try to use byte rotation instructions.
16206   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
16207                                                 Subtarget, DAG))
16208     return Rotate;
16209 
16210   // Try to create an in-lane repeating shuffle mask and then shuffle the
16211   // results into the target lanes.
16212   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16213           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16214     return V;
16215 
16216   // If the shuffle patterns aren't repeated but it is a single input, directly
16217   // generate a cross-lane VPERMD instruction.
16218   if (V2.isUndef()) {
16219     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16220     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
16221   }
16222 
16223   // Assume that a single SHUFPS is faster than an alternative sequence of
16224   // multiple instructions (even if the CPU has a domain penalty).
16225   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16226   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16227     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
16228     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
16229     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
16230                                             CastV1, CastV2, DAG);
16231     return DAG.getBitcast(MVT::v8i32, ShufPS);
16232   }
16233 
16234   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16235   // shuffle.
16236   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16237           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16238     return Result;
16239 
16240   // Otherwise fall back on generic blend lowering.
16241   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2, Mask,
16242                                               Subtarget, DAG);
16243 }
16244 
16245 /// Handle lowering of 16-lane 16-bit integer shuffles.
16246 ///
16247 /// This routine is only called when we have AVX2 and thus a reasonable
16248 /// instruction set for v16i16 shuffling..
lowerV16I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16249 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16250                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16251                                   const X86Subtarget &Subtarget,
16252                                   SelectionDAG &DAG) {
16253   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16254   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16255   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16256   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
16257 
16258   // Whenever we can lower this as a zext, that instruction is strictly faster
16259   // than any alternative. It also allows us to fold memory operands into the
16260   // shuffle in many cases.
16261   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16262           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16263     return ZExt;
16264 
16265   // Check for being able to broadcast a single element.
16266   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
16267                                                   Subtarget, DAG))
16268     return Broadcast;
16269 
16270   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
16271                                           Zeroable, Subtarget, DAG))
16272     return Blend;
16273 
16274   // Use dedicated unpack instructions for masks that match their pattern.
16275   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
16276     return V;
16277 
16278   // Use dedicated pack instructions for masks that match their pattern.
16279   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
16280                                        Subtarget))
16281     return V;
16282 
16283   // Try to use shift instructions.
16284   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
16285                                           Zeroable, Subtarget, DAG))
16286     return Shift;
16287 
16288   // Try to use byte rotation instructions.
16289   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
16290                                                 Subtarget, DAG))
16291     return Rotate;
16292 
16293   // Try to create an in-lane repeating shuffle mask and then shuffle the
16294   // results into the target lanes.
16295   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16296           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16297     return V;
16298 
16299   if (V2.isUndef()) {
16300     // There are no generalized cross-lane shuffle operations available on i16
16301     // element types.
16302     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
16303       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16304               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16305         return V;
16306 
16307       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
16308                                                  DAG, Subtarget);
16309     }
16310 
16311     SmallVector<int, 8> RepeatedMask;
16312     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
16313       // As this is a single-input shuffle, the repeated mask should be
16314       // a strictly valid v8i16 mask that we can pass through to the v8i16
16315       // lowering to handle even the v16 case.
16316       return lowerV8I16GeneralSingleInputShuffle(
16317           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
16318     }
16319   }
16320 
16321   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
16322                                               Zeroable, Subtarget, DAG))
16323     return PSHUFB;
16324 
16325   // AVX512BWVL can lower to VPERMW.
16326   if (Subtarget.hasBWI() && Subtarget.hasVLX())
16327     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, DAG);
16328 
16329   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16330   // shuffle.
16331   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16332           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16333     return Result;
16334 
16335   // Try to permute the lanes and then use a per-lane permute.
16336   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16337           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16338     return V;
16339 
16340   // Otherwise fall back on generic lowering.
16341   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
16342                                     Subtarget, DAG);
16343 }
16344 
16345 /// Handle lowering of 32-lane 8-bit integer shuffles.
16346 ///
16347 /// This routine is only called when we have AVX2 and thus a reasonable
16348 /// instruction set for v32i8 shuffling..
lowerV32I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16349 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16350                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16351                                  const X86Subtarget &Subtarget,
16352                                  SelectionDAG &DAG) {
16353   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16354   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16355   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16356   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
16357 
16358   // Whenever we can lower this as a zext, that instruction is strictly faster
16359   // than any alternative. It also allows us to fold memory operands into the
16360   // shuffle in many cases.
16361   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
16362                                                    Zeroable, Subtarget, DAG))
16363     return ZExt;
16364 
16365   // Check for being able to broadcast a single element.
16366   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
16367                                                   Subtarget, DAG))
16368     return Broadcast;
16369 
16370   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
16371                                           Zeroable, Subtarget, DAG))
16372     return Blend;
16373 
16374   // Use dedicated unpack instructions for masks that match their pattern.
16375   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
16376     return V;
16377 
16378   // Use dedicated pack instructions for masks that match their pattern.
16379   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
16380                                        Subtarget))
16381     return V;
16382 
16383   // Try to use shift instructions.
16384   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
16385                                                 Zeroable, Subtarget, DAG))
16386     return Shift;
16387 
16388   // Try to use byte rotation instructions.
16389   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
16390                                                 Subtarget, DAG))
16391     return Rotate;
16392 
16393   // Try to create an in-lane repeating shuffle mask and then shuffle the
16394   // results into the target lanes.
16395   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16396           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16397     return V;
16398 
16399   // There are no generalized cross-lane shuffle operations available on i8
16400   // element types.
16401   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
16402     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16403             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16404       return V;
16405 
16406     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
16407                                                DAG, Subtarget);
16408   }
16409 
16410   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
16411                                               Zeroable, Subtarget, DAG))
16412     return PSHUFB;
16413 
16414   // AVX512VBMIVL can lower to VPERMB.
16415   if (Subtarget.hasVBMI() && Subtarget.hasVLX())
16416     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, DAG);
16417 
16418   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16419   // shuffle.
16420   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16421           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16422     return Result;
16423 
16424   // Try to permute the lanes and then use a per-lane permute.
16425   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16426           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16427     return V;
16428 
16429   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16430   // by zeroable elements in the remaining 24 elements. Turn this into two
16431   // vmovqb instructions shuffled together.
16432   if (Subtarget.hasVLX())
16433     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
16434                                                   Mask, Zeroable, DAG))
16435       return V;
16436 
16437   // Otherwise fall back on generic lowering.
16438   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
16439                                     Subtarget, DAG);
16440 }
16441 
16442 /// High-level routine to lower various 256-bit x86 vector shuffles.
16443 ///
16444 /// This routine either breaks down the specific type of a 256-bit x86 vector
16445 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
16446 /// together based on the available instructions.
lower256BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)16447 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
16448                                   SDValue V1, SDValue V2, const APInt &Zeroable,
16449                                   const X86Subtarget &Subtarget,
16450                                   SelectionDAG &DAG) {
16451   // If we have a single input to the zero element, insert that into V1 if we
16452   // can do so cheaply.
16453   int NumElts = VT.getVectorNumElements();
16454   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16455 
16456   if (NumV2Elements == 1 && Mask[0] >= NumElts)
16457     if (SDValue Insertion = lowerShuffleAsElementInsertion(
16458             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16459       return Insertion;
16460 
16461   // Handle special cases where the lower or upper half is UNDEF.
16462   if (SDValue V =
16463           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16464     return V;
16465 
16466   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
16467   // can check for those subtargets here and avoid much of the subtarget
16468   // querying in the per-vector-type lowering routines. With AVX1 we have
16469   // essentially *zero* ability to manipulate a 256-bit vector with integer
16470   // types. Since we'll use floating point types there eventually, just
16471   // immediately cast everything to a float and operate entirely in that domain.
16472   if (VT.isInteger() && !Subtarget.hasAVX2()) {
16473     int ElementBits = VT.getScalarSizeInBits();
16474     if (ElementBits < 32) {
16475       // No floating point type available, if we can't use the bit operations
16476       // for masking/blending then decompose into 128-bit vectors.
16477       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
16478                                             Subtarget, DAG))
16479         return V;
16480       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
16481         return V;
16482       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16483     }
16484 
16485     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
16486                                 VT.getVectorNumElements());
16487     V1 = DAG.getBitcast(FpVT, V1);
16488     V2 = DAG.getBitcast(FpVT, V2);
16489     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
16490   }
16491 
16492   switch (VT.SimpleTy) {
16493   case MVT::v4f64:
16494     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16495   case MVT::v4i64:
16496     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16497   case MVT::v8f32:
16498     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16499   case MVT::v8i32:
16500     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16501   case MVT::v16i16:
16502     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16503   case MVT::v32i8:
16504     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16505 
16506   default:
16507     llvm_unreachable("Not a valid 256-bit x86 vector type!");
16508   }
16509 }
16510 
16511 /// Try to lower a vector shuffle as a 128-bit shuffles.
lowerV4X128Shuffle(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16512 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
16513                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16514                                   const X86Subtarget &Subtarget,
16515                                   SelectionDAG &DAG) {
16516   assert(VT.getScalarSizeInBits() == 64 &&
16517          "Unexpected element type size for 128bit shuffle.");
16518 
16519   // To handle 256 bit vector requires VLX and most probably
16520   // function lowerV2X128VectorShuffle() is better solution.
16521   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
16522 
16523   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
16524   SmallVector<int, 4> WidenedMask;
16525   if (!canWidenShuffleElements(Mask, WidenedMask))
16526     return SDValue();
16527 
16528   // Try to use an insert into a zero vector.
16529   if (WidenedMask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
16530       (WidenedMask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
16531     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
16532     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
16533     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16534                               DAG.getIntPtrConstant(0, DL));
16535     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16536                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
16537                        DAG.getIntPtrConstant(0, DL));
16538   }
16539 
16540   // Check for patterns which can be matched with a single insert of a 256-bit
16541   // subvector.
16542   bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask,
16543                                         {0, 1, 2, 3, 0, 1, 2, 3});
16544   if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask,
16545                                         {0, 1, 2, 3, 8, 9, 10, 11})) {
16546     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
16547     SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
16548                                  OnlyUsesV1 ? V1 : V2,
16549                               DAG.getIntPtrConstant(0, DL));
16550     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16551                        DAG.getIntPtrConstant(4, DL));
16552   }
16553 
16554   assert(WidenedMask.size() == 4);
16555 
16556   // See if this is an insertion of the lower 128-bits of V2 into V1.
16557   bool IsInsert = true;
16558   int V2Index = -1;
16559   for (int i = 0; i < 4; ++i) {
16560     assert(WidenedMask[i] >= -1);
16561     if (WidenedMask[i] < 0)
16562       continue;
16563 
16564     // Make sure all V1 subvectors are in place.
16565     if (WidenedMask[i] < 4) {
16566       if (WidenedMask[i] != i) {
16567         IsInsert = false;
16568         break;
16569       }
16570     } else {
16571       // Make sure we only have a single V2 index and its the lowest 128-bits.
16572       if (V2Index >= 0 || WidenedMask[i] != 4) {
16573         IsInsert = false;
16574         break;
16575       }
16576       V2Index = i;
16577     }
16578   }
16579   if (IsInsert && V2Index >= 0) {
16580     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16581     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
16582                                  DAG.getIntPtrConstant(0, DL));
16583     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
16584   }
16585 
16586   // Try to lower to vshuf64x2/vshuf32x4.
16587   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
16588   unsigned PermMask = 0;
16589   // Insure elements came from the same Op.
16590   for (int i = 0; i < 4; ++i) {
16591     assert(WidenedMask[i] >= -1);
16592     if (WidenedMask[i] < 0)
16593       continue;
16594 
16595     SDValue Op = WidenedMask[i] >= 4 ? V2 : V1;
16596     unsigned OpIndex = i / 2;
16597     if (Ops[OpIndex].isUndef())
16598       Ops[OpIndex] = Op;
16599     else if (Ops[OpIndex] != Op)
16600       return SDValue();
16601 
16602     // Convert the 128-bit shuffle mask selection values into 128-bit selection
16603     // bits defined by a vshuf64x2 instruction's immediate control byte.
16604     PermMask |= (WidenedMask[i] % 4) << (i * 2);
16605   }
16606 
16607   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
16608                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
16609 }
16610 
16611 /// Handle lowering of 8-lane 64-bit floating point shuffles.
lowerV8F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16612 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16613                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16614                                  const X86Subtarget &Subtarget,
16615                                  SelectionDAG &DAG) {
16616   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16617   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16618   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16619 
16620   if (V2.isUndef()) {
16621     // Use low duplicate instructions for masks that match their pattern.
16622     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
16623       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
16624 
16625     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
16626       // Non-half-crossing single input shuffles can be lowered with an
16627       // interleaved permutation.
16628       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16629                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
16630                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
16631                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
16632       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
16633                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16634     }
16635 
16636     SmallVector<int, 4> RepeatedMask;
16637     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
16638       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
16639                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16640   }
16641 
16642   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
16643                                            V2, Subtarget, DAG))
16644     return Shuf128;
16645 
16646   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
16647     return Unpck;
16648 
16649   // Check if the blend happens to exactly fit that of SHUFPD.
16650   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
16651                                           Zeroable, Subtarget, DAG))
16652     return Op;
16653 
16654   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
16655                                        DAG, Subtarget))
16656     return V;
16657 
16658   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
16659                                           Zeroable, Subtarget, DAG))
16660     return Blend;
16661 
16662   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
16663 }
16664 
16665 /// Handle lowering of 16-lane 32-bit floating point shuffles.
lowerV16F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16666 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16667                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16668                                   const X86Subtarget &Subtarget,
16669                                   SelectionDAG &DAG) {
16670   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
16671   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
16672   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16673 
16674   // If the shuffle mask is repeated in each 128-bit lane, we have many more
16675   // options to efficiently lower the shuffle.
16676   SmallVector<int, 4> RepeatedMask;
16677   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
16678     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16679 
16680     // Use even/odd duplicate instructions for masks that match their pattern.
16681     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
16682       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
16683     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
16684       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
16685 
16686     if (V2.isUndef())
16687       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
16688                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16689 
16690     // Use dedicated unpack instructions for masks that match their pattern.
16691     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
16692       return V;
16693 
16694     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
16695                                             Zeroable, Subtarget, DAG))
16696       return Blend;
16697 
16698     // Otherwise, fall back to a SHUFPS sequence.
16699     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
16700   }
16701 
16702   // If we have a single input shuffle with different shuffle patterns in the
16703   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
16704   if (V2.isUndef() &&
16705       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
16706     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
16707     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
16708   }
16709 
16710   // If we have AVX512F support, we can use VEXPAND.
16711   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
16712                                              V1, V2, DAG, Subtarget))
16713     return V;
16714 
16715   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
16716 }
16717 
16718 /// Handle lowering of 8-lane 64-bit integer shuffles.
lowerV8I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16719 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16720                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16721                                  const X86Subtarget &Subtarget,
16722                                  SelectionDAG &DAG) {
16723   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
16724   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
16725   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16726 
16727   if (V2.isUndef()) {
16728     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16729     // can use lower latency instructions that will operate on all four
16730     // 128-bit lanes.
16731     SmallVector<int, 2> Repeated128Mask;
16732     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
16733       SmallVector<int, 4> PSHUFDMask;
16734       scaleShuffleMask<int>(2, Repeated128Mask, PSHUFDMask);
16735       return DAG.getBitcast(
16736           MVT::v8i64,
16737           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
16738                       DAG.getBitcast(MVT::v16i32, V1),
16739                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16740     }
16741 
16742     SmallVector<int, 4> Repeated256Mask;
16743     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
16744       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
16745                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
16746   }
16747 
16748   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
16749                                            V2, Subtarget, DAG))
16750     return Shuf128;
16751 
16752   // Try to use shift instructions.
16753   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
16754                                           Zeroable, Subtarget, DAG))
16755     return Shift;
16756 
16757   // Try to use VALIGN.
16758   if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v8i64, V1, V2, Mask,
16759                                             Subtarget, DAG))
16760     return Rotate;
16761 
16762   // Try to use PALIGNR.
16763   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
16764                                                 Subtarget, DAG))
16765     return Rotate;
16766 
16767   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
16768     return Unpck;
16769   // If we have AVX512F support, we can use VEXPAND.
16770   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
16771                                        DAG, Subtarget))
16772     return V;
16773 
16774   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
16775                                           Zeroable, Subtarget, DAG))
16776     return Blend;
16777 
16778   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
16779 }
16780 
16781 /// Handle lowering of 16-lane 32-bit integer shuffles.
lowerV16I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16782 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16783                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16784                                   const X86Subtarget &Subtarget,
16785                                   SelectionDAG &DAG) {
16786   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
16787   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
16788   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16789 
16790   // Whenever we can lower this as a zext, that instruction is strictly faster
16791   // than any alternative. It also allows us to fold memory operands into the
16792   // shuffle in many cases.
16793   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16794           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
16795     return ZExt;
16796 
16797   // If the shuffle mask is repeated in each 128-bit lane we can use more
16798   // efficient instructions that mirror the shuffles across the four 128-bit
16799   // lanes.
16800   SmallVector<int, 4> RepeatedMask;
16801   bool Is128BitLaneRepeatedShuffle =
16802       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
16803   if (Is128BitLaneRepeatedShuffle) {
16804     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16805     if (V2.isUndef())
16806       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
16807                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16808 
16809     // Use dedicated unpack instructions for masks that match their pattern.
16810     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
16811       return V;
16812   }
16813 
16814   // Try to use shift instructions.
16815   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
16816                                           Zeroable, Subtarget, DAG))
16817     return Shift;
16818 
16819   // Try to use VALIGN.
16820   if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v16i32, V1, V2, Mask,
16821                                             Subtarget, DAG))
16822     return Rotate;
16823 
16824   // Try to use byte rotation instructions.
16825   if (Subtarget.hasBWI())
16826     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
16827                                                   Subtarget, DAG))
16828       return Rotate;
16829 
16830   // Assume that a single SHUFPS is faster than using a permv shuffle.
16831   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16832   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16833     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
16834     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
16835     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
16836                                             CastV1, CastV2, DAG);
16837     return DAG.getBitcast(MVT::v16i32, ShufPS);
16838   }
16839   // If we have AVX512F support, we can use VEXPAND.
16840   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
16841                                        DAG, Subtarget))
16842     return V;
16843 
16844   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
16845                                           Zeroable, Subtarget, DAG))
16846     return Blend;
16847   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
16848 }
16849 
16850 /// Handle lowering of 32-lane 16-bit integer shuffles.
lowerV32I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16851 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16852                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16853                                   const X86Subtarget &Subtarget,
16854                                   SelectionDAG &DAG) {
16855   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
16856   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
16857   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16858   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
16859 
16860   // Whenever we can lower this as a zext, that instruction is strictly faster
16861   // than any alternative. It also allows us to fold memory operands into the
16862   // shuffle in many cases.
16863   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16864           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16865     return ZExt;
16866 
16867   // Use dedicated unpack instructions for masks that match their pattern.
16868   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
16869     return V;
16870 
16871   // Try to use shift instructions.
16872   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
16873                                           Zeroable, Subtarget, DAG))
16874     return Shift;
16875 
16876   // Try to use byte rotation instructions.
16877   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
16878                                                 Subtarget, DAG))
16879     return Rotate;
16880 
16881   if (V2.isUndef()) {
16882     SmallVector<int, 8> RepeatedMask;
16883     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
16884       // As this is a single-input shuffle, the repeated mask should be
16885       // a strictly valid v8i16 mask that we can pass through to the v8i16
16886       // lowering to handle even the v32 case.
16887       return lowerV8I16GeneralSingleInputShuffle(
16888           DL, MVT::v32i16, V1, RepeatedMask, Subtarget, DAG);
16889     }
16890   }
16891 
16892   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
16893                                                 Zeroable, Subtarget, DAG))
16894     return Blend;
16895 
16896   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
16897                                               Zeroable, Subtarget, DAG))
16898     return PSHUFB;
16899 
16900   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
16901 }
16902 
16903 /// Handle lowering of 64-lane 8-bit integer shuffles.
lowerV64I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16904 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16905                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16906                                  const X86Subtarget &Subtarget,
16907                                  SelectionDAG &DAG) {
16908   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
16909   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
16910   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
16911   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
16912 
16913   // Whenever we can lower this as a zext, that instruction is strictly faster
16914   // than any alternative. It also allows us to fold memory operands into the
16915   // shuffle in many cases.
16916   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16917           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16918     return ZExt;
16919 
16920   // Use dedicated unpack instructions for masks that match their pattern.
16921   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
16922     return V;
16923 
16924   // Use dedicated pack instructions for masks that match their pattern.
16925   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
16926                                        Subtarget))
16927     return V;
16928 
16929   // Try to use shift instructions.
16930   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
16931                                           Zeroable, Subtarget, DAG))
16932     return Shift;
16933 
16934   // Try to use byte rotation instructions.
16935   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
16936                                                 Subtarget, DAG))
16937     return Rotate;
16938 
16939   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
16940                                               Zeroable, Subtarget, DAG))
16941     return PSHUFB;
16942 
16943   // VBMI can use VPERMV/VPERMV3 byte shuffles.
16944   if (Subtarget.hasVBMI())
16945     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, DAG);
16946 
16947   // Try to create an in-lane repeating shuffle mask and then shuffle the
16948   // results into the target lanes.
16949   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16950           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
16951     return V;
16952 
16953   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
16954                                           Zeroable, Subtarget, DAG))
16955     return Blend;
16956 
16957   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16958   // shuffle.
16959   if (!V2.isUndef())
16960     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16961             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
16962       return Result;
16963 
16964   // FIXME: Implement direct support for this type!
16965   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
16966 }
16967 
16968 /// High-level routine to lower various 512-bit x86 vector shuffles.
16969 ///
16970 /// This routine either breaks down the specific type of a 512-bit x86 vector
16971 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
16972 /// together based on the available instructions.
lower512BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)16973 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
16974                                   MVT VT, SDValue V1, SDValue V2,
16975                                   const APInt &Zeroable,
16976                                   const X86Subtarget &Subtarget,
16977                                   SelectionDAG &DAG) {
16978   assert(Subtarget.hasAVX512() &&
16979          "Cannot lower 512-bit vectors w/ basic ISA!");
16980 
16981   // If we have a single input to the zero element, insert that into V1 if we
16982   // can do so cheaply.
16983   int NumElts = Mask.size();
16984   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16985 
16986   if (NumV2Elements == 1 && Mask[0] >= NumElts)
16987     if (SDValue Insertion = lowerShuffleAsElementInsertion(
16988             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16989       return Insertion;
16990 
16991   // Handle special cases where the lower or upper half is UNDEF.
16992   if (SDValue V =
16993           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16994     return V;
16995 
16996   // Check for being able to broadcast a single element.
16997   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
16998                                                   Subtarget, DAG))
16999     return Broadcast;
17000 
17001   // Dispatch to each element type for lowering. If we don't have support for
17002   // specific element type shuffles at 512 bits, immediately split them and
17003   // lower them. Each lowering routine of a given type is allowed to assume that
17004   // the requisite ISA extensions for that element type are available.
17005   switch (VT.SimpleTy) {
17006   case MVT::v8f64:
17007     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17008   case MVT::v16f32:
17009     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17010   case MVT::v8i64:
17011     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17012   case MVT::v16i32:
17013     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17014   case MVT::v32i16:
17015     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17016   case MVT::v64i8:
17017     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17018 
17019   default:
17020     llvm_unreachable("Not a valid 512-bit x86 vector type!");
17021   }
17022 }
17023 
lower1BitShuffleAsKSHIFTR(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)17024 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
17025                                          MVT VT, SDValue V1, SDValue V2,
17026                                          const X86Subtarget &Subtarget,
17027                                          SelectionDAG &DAG) {
17028   // Shuffle should be unary.
17029   if (!V2.isUndef())
17030     return SDValue();
17031 
17032   int ShiftAmt = -1;
17033   int NumElts = Mask.size();
17034   for (int i = 0; i != NumElts; ++i) {
17035     int M = Mask[i];
17036     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
17037            "Unexpected mask index.");
17038     if (M < 0)
17039       continue;
17040 
17041     // The first non-undef element determines our shift amount.
17042     if (ShiftAmt < 0) {
17043       ShiftAmt = M - i;
17044       // Need to be shifting right.
17045       if (ShiftAmt <= 0)
17046         return SDValue();
17047     }
17048     // All non-undef elements must shift by the same amount.
17049     if (ShiftAmt != M - i)
17050       return SDValue();
17051   }
17052   assert(ShiftAmt >= 0 && "All undef?");
17053 
17054   // Great we found a shift right.
17055   MVT WideVT = VT;
17056   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
17057     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17058   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
17059                             DAG.getUNDEF(WideVT), V1,
17060                             DAG.getIntPtrConstant(0, DL));
17061   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
17062                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17063   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17064                      DAG.getIntPtrConstant(0, DL));
17065 }
17066 
17067 // Determine if this shuffle can be implemented with a KSHIFT instruction.
17068 // Returns the shift amount if possible or -1 if not. This is a simplified
17069 // version of matchShuffleAsShift.
match1BitShuffleAsKSHIFT(unsigned & Opcode,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable)17070 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
17071                                     int MaskOffset, const APInt &Zeroable) {
17072   int Size = Mask.size();
17073 
17074   auto CheckZeros = [&](int Shift, bool Left) {
17075     for (int j = 0; j < Shift; ++j)
17076       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
17077         return false;
17078 
17079     return true;
17080   };
17081 
17082   auto MatchShift = [&](int Shift, bool Left) {
17083     unsigned Pos = Left ? Shift : 0;
17084     unsigned Low = Left ? 0 : Shift;
17085     unsigned Len = Size - Shift;
17086     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
17087   };
17088 
17089   for (int Shift = 1; Shift != Size; ++Shift)
17090     for (bool Left : {true, false})
17091       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
17092         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
17093         return Shift;
17094       }
17095 
17096   return -1;
17097 }
17098 
17099 
17100 // Lower vXi1 vector shuffles.
17101 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
17102 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
17103 // vector, shuffle and then truncate it back.
lower1BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)17104 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17105                                 MVT VT, SDValue V1, SDValue V2,
17106                                 const APInt &Zeroable,
17107                                 const X86Subtarget &Subtarget,
17108                                 SelectionDAG &DAG) {
17109   assert(Subtarget.hasAVX512() &&
17110          "Cannot lower 512-bit vectors w/o basic ISA!");
17111 
17112   int NumElts = Mask.size();
17113 
17114   // Try to recognize shuffles that are just padding a subvector with zeros.
17115   int SubvecElts = 0;
17116   int Src = -1;
17117   for (int i = 0; i != NumElts; ++i) {
17118     if (Mask[i] >= 0) {
17119       // Grab the source from the first valid mask. All subsequent elements need
17120       // to use this same source.
17121       if (Src < 0)
17122         Src = Mask[i] / NumElts;
17123       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
17124         break;
17125     }
17126 
17127     ++SubvecElts;
17128   }
17129   assert(SubvecElts != NumElts && "Identity shuffle?");
17130 
17131   // Clip to a power 2.
17132   SubvecElts = PowerOf2Floor(SubvecElts);
17133 
17134   // Make sure the number of zeroable bits in the top at least covers the bits
17135   // not covered by the subvector.
17136   if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
17137     assert(Src >= 0 && "Expected a source!");
17138     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
17139     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
17140                                   Src == 0 ? V1 : V2,
17141                                   DAG.getIntPtrConstant(0, DL));
17142     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17143                        DAG.getConstant(0, DL, VT),
17144                        Extract, DAG.getIntPtrConstant(0, DL));
17145   }
17146 
17147   // Try a simple shift right with undef elements. Later we'll try with zeros.
17148   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
17149                                                 DAG))
17150     return Shift;
17151 
17152   // Try to match KSHIFTs.
17153   unsigned Offset = 0;
17154   for (SDValue V : { V1, V2 }) {
17155     unsigned Opcode;
17156     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
17157     if (ShiftAmt >= 0) {
17158       MVT WideVT = VT;
17159       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
17160         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17161       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
17162                                 DAG.getUNDEF(WideVT), V,
17163                                 DAG.getIntPtrConstant(0, DL));
17164       // Widened right shifts need two shifts to ensure we shift in zeroes.
17165       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
17166         int WideElts = WideVT.getVectorNumElements();
17167         // Shift left to put the original vector in the MSBs of the new size.
17168         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
17169                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
17170         // Increase the shift amount to account for the left shift.
17171         ShiftAmt += WideElts - NumElts;
17172       }
17173 
17174       Res = DAG.getNode(Opcode, DL, WideVT, Res,
17175                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17176       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17177                          DAG.getIntPtrConstant(0, DL));
17178     }
17179     Offset += NumElts; // Increment for next iteration.
17180   }
17181 
17182 
17183 
17184   MVT ExtVT;
17185   switch (VT.SimpleTy) {
17186   default:
17187     llvm_unreachable("Expected a vector of i1 elements");
17188   case MVT::v2i1:
17189     ExtVT = MVT::v2i64;
17190     break;
17191   case MVT::v4i1:
17192     ExtVT = MVT::v4i32;
17193     break;
17194   case MVT::v8i1:
17195     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
17196     // shuffle.
17197     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
17198     break;
17199   case MVT::v16i1:
17200     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17201     // 256-bit operation available.
17202     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
17203     break;
17204   case MVT::v32i1:
17205     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17206     // 256-bit operation available.
17207     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
17208     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
17209     break;
17210   case MVT::v64i1:
17211     // Fall back to scalarization. FIXME: We can do better if the shuffle
17212     // can be partitioned cleanly.
17213     if (!Subtarget.useBWIRegs())
17214       return SDValue();
17215     ExtVT = MVT::v64i8;
17216     break;
17217   }
17218 
17219   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
17220   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
17221 
17222   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
17223   // i1 was sign extended we can use X86ISD::CVT2MASK.
17224   int NumElems = VT.getVectorNumElements();
17225   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
17226       (Subtarget.hasDQI() && (NumElems < 32)))
17227     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
17228                        Shuffle, ISD::SETGT);
17229 
17230   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
17231 }
17232 
17233 /// Helper function that returns true if the shuffle mask should be
17234 /// commuted to improve canonicalization.
canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask)17235 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
17236   int NumElements = Mask.size();
17237 
17238   int NumV1Elements = 0, NumV2Elements = 0;
17239   for (int M : Mask)
17240     if (M < 0)
17241       continue;
17242     else if (M < NumElements)
17243       ++NumV1Elements;
17244     else
17245       ++NumV2Elements;
17246 
17247   // Commute the shuffle as needed such that more elements come from V1 than
17248   // V2. This allows us to match the shuffle pattern strictly on how many
17249   // elements come from V1 without handling the symmetric cases.
17250   if (NumV2Elements > NumV1Elements)
17251     return true;
17252 
17253   assert(NumV1Elements > 0 && "No V1 indices");
17254 
17255   if (NumV2Elements == 0)
17256     return false;
17257 
17258   // When the number of V1 and V2 elements are the same, try to minimize the
17259   // number of uses of V2 in the low half of the vector. When that is tied,
17260   // ensure that the sum of indices for V1 is equal to or lower than the sum
17261   // indices for V2. When those are equal, try to ensure that the number of odd
17262   // indices for V1 is lower than the number of odd indices for V2.
17263   if (NumV1Elements == NumV2Elements) {
17264     int LowV1Elements = 0, LowV2Elements = 0;
17265     for (int M : Mask.slice(0, NumElements / 2))
17266       if (M >= NumElements)
17267         ++LowV2Elements;
17268       else if (M >= 0)
17269         ++LowV1Elements;
17270     if (LowV2Elements > LowV1Elements)
17271       return true;
17272     if (LowV2Elements == LowV1Elements) {
17273       int SumV1Indices = 0, SumV2Indices = 0;
17274       for (int i = 0, Size = Mask.size(); i < Size; ++i)
17275         if (Mask[i] >= NumElements)
17276           SumV2Indices += i;
17277         else if (Mask[i] >= 0)
17278           SumV1Indices += i;
17279       if (SumV2Indices < SumV1Indices)
17280         return true;
17281       if (SumV2Indices == SumV1Indices) {
17282         int NumV1OddIndices = 0, NumV2OddIndices = 0;
17283         for (int i = 0, Size = Mask.size(); i < Size; ++i)
17284           if (Mask[i] >= NumElements)
17285             NumV2OddIndices += i % 2;
17286           else if (Mask[i] >= 0)
17287             NumV1OddIndices += i % 2;
17288         if (NumV2OddIndices < NumV1OddIndices)
17289           return true;
17290       }
17291     }
17292   }
17293 
17294   return false;
17295 }
17296 
17297 /// Top-level lowering for x86 vector shuffles.
17298 ///
17299 /// This handles decomposition, canonicalization, and lowering of all x86
17300 /// vector shuffles. Most of the specific lowering strategies are encapsulated
17301 /// above in helper routines. The canonicalization attempts to widen shuffles
17302 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
17303 /// s.t. only one of the two inputs needs to be tested, etc.
lowerVECTOR_SHUFFLE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17304 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
17305                                    SelectionDAG &DAG) {
17306   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
17307   ArrayRef<int> OrigMask = SVOp->getMask();
17308   SDValue V1 = Op.getOperand(0);
17309   SDValue V2 = Op.getOperand(1);
17310   MVT VT = Op.getSimpleValueType();
17311   int NumElements = VT.getVectorNumElements();
17312   SDLoc DL(Op);
17313   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
17314 
17315   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
17316          "Can't lower MMX shuffles");
17317 
17318   bool V1IsUndef = V1.isUndef();
17319   bool V2IsUndef = V2.isUndef();
17320   if (V1IsUndef && V2IsUndef)
17321     return DAG.getUNDEF(VT);
17322 
17323   // When we create a shuffle node we put the UNDEF node to second operand,
17324   // but in some cases the first operand may be transformed to UNDEF.
17325   // In this case we should just commute the node.
17326   if (V1IsUndef)
17327     return DAG.getCommutedVectorShuffle(*SVOp);
17328 
17329   // Check for non-undef masks pointing at an undef vector and make the masks
17330   // undef as well. This makes it easier to match the shuffle based solely on
17331   // the mask.
17332   if (V2IsUndef &&
17333       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
17334     SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
17335     for (int &M : NewMask)
17336       if (M >= NumElements)
17337         M = -1;
17338     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17339   }
17340 
17341   // Check for illegal shuffle mask element index values.
17342   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
17343   (void)MaskUpperLimit;
17344   assert(llvm::all_of(OrigMask,
17345                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
17346          "Out of bounds shuffle index");
17347 
17348   // We actually see shuffles that are entirely re-arrangements of a set of
17349   // zero inputs. This mostly happens while decomposing complex shuffles into
17350   // simple ones. Directly lower these as a buildvector of zeros.
17351   APInt KnownUndef, KnownZero;
17352   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
17353 
17354   APInt Zeroable = KnownUndef | KnownZero;
17355   if (Zeroable.isAllOnesValue())
17356     return getZeroVector(VT, Subtarget, DAG, DL);
17357 
17358   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
17359 
17360   // Try to collapse shuffles into using a vector type with fewer elements but
17361   // wider element types. We cap this to not form integers or floating point
17362   // elements wider than 64 bits, but it might be interesting to form i128
17363   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
17364   SmallVector<int, 16> WidenedMask;
17365   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
17366       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
17367     // Shuffle mask widening should not interfere with a broadcast opportunity
17368     // by obfuscating the operands with bitcasts.
17369     // TODO: Avoid lowering directly from this top-level function: make this
17370     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
17371     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
17372                                                     Subtarget, DAG))
17373       return Broadcast;
17374 
17375     MVT NewEltVT = VT.isFloatingPoint()
17376                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
17377                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
17378     int NewNumElts = NumElements / 2;
17379     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
17380     // Make sure that the new vector type is legal. For example, v2f64 isn't
17381     // legal on SSE1.
17382     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
17383       if (V2IsZero) {
17384         // Modify the new Mask to take all zeros from the all-zero vector.
17385         // Choose indices that are blend-friendly.
17386         bool UsedZeroVector = false;
17387         assert(find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&
17388                "V2's non-undef elements are used?!");
17389         for (int i = 0; i != NewNumElts; ++i)
17390           if (WidenedMask[i] == SM_SentinelZero) {
17391             WidenedMask[i] = i + NewNumElts;
17392             UsedZeroVector = true;
17393           }
17394         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
17395         // some elements to be undef.
17396         if (UsedZeroVector)
17397           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
17398       }
17399       V1 = DAG.getBitcast(NewVT, V1);
17400       V2 = DAG.getBitcast(NewVT, V2);
17401       return DAG.getBitcast(
17402           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
17403     }
17404   }
17405 
17406   // Commute the shuffle if it will improve canonicalization.
17407   SmallVector<int, 64> Mask(OrigMask.begin(), OrigMask.end());
17408   if (canonicalizeShuffleMaskWithCommute(Mask)) {
17409     ShuffleVectorSDNode::commuteMask(Mask);
17410     std::swap(V1, V2);
17411   }
17412 
17413   if (SDValue V = lowerShuffleWithVPMOV(DL, Mask, VT, V1, V2, DAG, Subtarget))
17414     return V;
17415 
17416   // For each vector width, delegate to a specialized lowering routine.
17417   if (VT.is128BitVector())
17418     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17419 
17420   if (VT.is256BitVector())
17421     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17422 
17423   if (VT.is512BitVector())
17424     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17425 
17426   if (Is1BitVector)
17427     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17428 
17429   llvm_unreachable("Unimplemented!");
17430 }
17431 
17432 /// Try to lower a VSELECT instruction to a vector shuffle.
lowerVSELECTtoVectorShuffle(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17433 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
17434                                            const X86Subtarget &Subtarget,
17435                                            SelectionDAG &DAG) {
17436   SDValue Cond = Op.getOperand(0);
17437   SDValue LHS = Op.getOperand(1);
17438   SDValue RHS = Op.getOperand(2);
17439   MVT VT = Op.getSimpleValueType();
17440 
17441   // Only non-legal VSELECTs reach this lowering, convert those into generic
17442   // shuffles and re-use the shuffle lowering path for blends.
17443   SmallVector<int, 32> Mask;
17444   if (createShuffleMaskFromVSELECT(Mask, Cond))
17445     return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
17446 
17447   return SDValue();
17448 }
17449 
LowerVSELECT(SDValue Op,SelectionDAG & DAG) const17450 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
17451   SDValue Cond = Op.getOperand(0);
17452   SDValue LHS = Op.getOperand(1);
17453   SDValue RHS = Op.getOperand(2);
17454 
17455   // A vselect where all conditions and data are constants can be optimized into
17456   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
17457   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
17458       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
17459       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
17460     return SDValue();
17461 
17462   // Try to lower this to a blend-style vector shuffle. This can handle all
17463   // constant condition cases.
17464   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
17465     return BlendOp;
17466 
17467   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
17468   // with patterns on the mask registers on AVX-512.
17469   MVT CondVT = Cond.getSimpleValueType();
17470   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
17471   if (CondEltSize == 1)
17472     return Op;
17473 
17474   // Variable blends are only legal from SSE4.1 onward.
17475   if (!Subtarget.hasSSE41())
17476     return SDValue();
17477 
17478   SDLoc dl(Op);
17479   MVT VT = Op.getSimpleValueType();
17480   unsigned EltSize = VT.getScalarSizeInBits();
17481   unsigned NumElts = VT.getVectorNumElements();
17482 
17483   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
17484   // into an i1 condition so that we can use the mask-based 512-bit blend
17485   // instructions.
17486   if (VT.getSizeInBits() == 512) {
17487     // Build a mask by testing the condition against zero.
17488     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
17489     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
17490                                 DAG.getConstant(0, dl, CondVT),
17491                                 ISD::SETNE);
17492     // Now return a new VSELECT using the mask.
17493     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
17494   }
17495 
17496   // SEXT/TRUNC cases where the mask doesn't match the destination size.
17497   if (CondEltSize != EltSize) {
17498     // If we don't have a sign splat, rely on the expansion.
17499     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
17500       return SDValue();
17501 
17502     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
17503     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
17504     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
17505     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
17506   }
17507 
17508   // Only some types will be legal on some subtargets. If we can emit a legal
17509   // VSELECT-matching blend, return Op, and but if we need to expand, return
17510   // a null value.
17511   switch (VT.SimpleTy) {
17512   default:
17513     // Most of the vector types have blends past SSE4.1.
17514     return Op;
17515 
17516   case MVT::v32i8:
17517     // The byte blends for AVX vectors were introduced only in AVX2.
17518     if (Subtarget.hasAVX2())
17519       return Op;
17520 
17521     return SDValue();
17522 
17523   case MVT::v8i16:
17524   case MVT::v16i16: {
17525     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
17526     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
17527     Cond = DAG.getBitcast(CastVT, Cond);
17528     LHS = DAG.getBitcast(CastVT, LHS);
17529     RHS = DAG.getBitcast(CastVT, RHS);
17530     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
17531     return DAG.getBitcast(VT, Select);
17532   }
17533   }
17534 }
17535 
LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,SelectionDAG & DAG)17536 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
17537   MVT VT = Op.getSimpleValueType();
17538   SDLoc dl(Op);
17539 
17540   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
17541     return SDValue();
17542 
17543   if (VT.getSizeInBits() == 8) {
17544     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
17545                                   Op.getOperand(0), Op.getOperand(1));
17546     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
17547   }
17548 
17549   if (VT == MVT::f32) {
17550     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
17551     // the result back to FR32 register. It's only worth matching if the
17552     // result has a single use which is a store or a bitcast to i32.  And in
17553     // the case of a store, it's not worth it if the index is a constant 0,
17554     // because a MOVSSmr can be used instead, which is smaller and faster.
17555     if (!Op.hasOneUse())
17556       return SDValue();
17557     SDNode *User = *Op.getNode()->use_begin();
17558     if ((User->getOpcode() != ISD::STORE ||
17559          isNullConstant(Op.getOperand(1))) &&
17560         (User->getOpcode() != ISD::BITCAST ||
17561          User->getValueType(0) != MVT::i32))
17562       return SDValue();
17563     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17564                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
17565                                   Op.getOperand(1));
17566     return DAG.getBitcast(MVT::f32, Extract);
17567   }
17568 
17569   if (VT == MVT::i32 || VT == MVT::i64) {
17570     // ExtractPS/pextrq works with constant index.
17571     if (isa<ConstantSDNode>(Op.getOperand(1)))
17572       return Op;
17573   }
17574 
17575   return SDValue();
17576 }
17577 
17578 /// Extract one bit from mask vector, like v16i1 or v8i1.
17579 /// AVX-512 feature.
ExtractBitFromMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17580 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
17581                                         const X86Subtarget &Subtarget) {
17582   SDValue Vec = Op.getOperand(0);
17583   SDLoc dl(Vec);
17584   MVT VecVT = Vec.getSimpleValueType();
17585   SDValue Idx = Op.getOperand(1);
17586   MVT EltVT = Op.getSimpleValueType();
17587 
17588   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
17589          "Unexpected vector type in ExtractBitFromMaskVector");
17590 
17591   // variable index can't be handled in mask registers,
17592   // extend vector to VR512/128
17593   if (!isa<ConstantSDNode>(Idx)) {
17594     unsigned NumElts = VecVT.getVectorNumElements();
17595     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
17596     // than extending to 128/256bit.
17597     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
17598     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
17599     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
17600     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
17601     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
17602   }
17603 
17604   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
17605   if (IdxVal == 0) // the operation is legal
17606     return Op;
17607 
17608   // Extend to natively supported kshift.
17609   unsigned NumElems = VecVT.getVectorNumElements();
17610   MVT WideVecVT = VecVT;
17611   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
17612     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17613     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
17614                       DAG.getUNDEF(WideVecVT), Vec,
17615                       DAG.getIntPtrConstant(0, dl));
17616   }
17617 
17618   // Use kshiftr instruction to move to the lower element.
17619   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
17620                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
17621 
17622   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
17623                      DAG.getIntPtrConstant(0, dl));
17624 }
17625 
17626 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const17627 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
17628                                            SelectionDAG &DAG) const {
17629   SDLoc dl(Op);
17630   SDValue Vec = Op.getOperand(0);
17631   MVT VecVT = Vec.getSimpleValueType();
17632   SDValue Idx = Op.getOperand(1);
17633 
17634   if (VecVT.getVectorElementType() == MVT::i1)
17635     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
17636 
17637   if (!isa<ConstantSDNode>(Idx)) {
17638     // Its more profitable to go through memory (1 cycles throughput)
17639     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
17640     // IACA tool was used to get performance estimation
17641     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
17642     //
17643     // example : extractelement <16 x i8> %a, i32 %i
17644     //
17645     // Block Throughput: 3.00 Cycles
17646     // Throughput Bottleneck: Port5
17647     //
17648     // | Num Of |   Ports pressure in cycles  |    |
17649     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
17650     // ---------------------------------------------
17651     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
17652     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
17653     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
17654     // Total Num Of Uops: 4
17655     //
17656     //
17657     // Block Throughput: 1.00 Cycles
17658     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
17659     //
17660     // |    |  Ports pressure in cycles   |  |
17661     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
17662     // ---------------------------------------------------------
17663     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
17664     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
17665     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
17666     // Total Num Of Uops: 4
17667 
17668     return SDValue();
17669   }
17670 
17671   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
17672 
17673   // If this is a 256-bit vector result, first extract the 128-bit vector and
17674   // then extract the element from the 128-bit vector.
17675   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
17676     // Get the 128-bit vector.
17677     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
17678     MVT EltVT = VecVT.getVectorElementType();
17679 
17680     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
17681     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
17682 
17683     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
17684     // this can be done with a mask.
17685     IdxVal &= ElemsPerChunk - 1;
17686     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
17687                        DAG.getIntPtrConstant(IdxVal, dl));
17688   }
17689 
17690   assert(VecVT.is128BitVector() && "Unexpected vector length");
17691 
17692   MVT VT = Op.getSimpleValueType();
17693 
17694   if (VT.getSizeInBits() == 16) {
17695     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
17696     // we're going to zero extend the register or fold the store (SSE41 only).
17697     if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
17698         !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
17699       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
17700                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17701                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
17702 
17703     // Transform it so it match pextrw which produces a 32-bit result.
17704     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
17705                                   Op.getOperand(0), Op.getOperand(1));
17706     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
17707   }
17708 
17709   if (Subtarget.hasSSE41())
17710     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
17711       return Res;
17712 
17713   // TODO: We only extract a single element from v16i8, we can probably afford
17714   // to be more aggressive here before using the default approach of spilling to
17715   // stack.
17716   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
17717     // Extract either the lowest i32 or any i16, and extract the sub-byte.
17718     int DWordIdx = IdxVal / 4;
17719     if (DWordIdx == 0) {
17720       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17721                                 DAG.getBitcast(MVT::v4i32, Vec),
17722                                 DAG.getIntPtrConstant(DWordIdx, dl));
17723       int ShiftVal = (IdxVal % 4) * 8;
17724       if (ShiftVal != 0)
17725         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
17726                           DAG.getConstant(ShiftVal, dl, MVT::i8));
17727       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
17728     }
17729 
17730     int WordIdx = IdxVal / 2;
17731     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
17732                               DAG.getBitcast(MVT::v8i16, Vec),
17733                               DAG.getIntPtrConstant(WordIdx, dl));
17734     int ShiftVal = (IdxVal % 2) * 8;
17735     if (ShiftVal != 0)
17736       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
17737                         DAG.getConstant(ShiftVal, dl, MVT::i8));
17738     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
17739   }
17740 
17741   if (VT.getSizeInBits() == 32) {
17742     if (IdxVal == 0)
17743       return Op;
17744 
17745     // SHUFPS the element to the lowest double word, then movss.
17746     int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
17747     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
17748     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
17749                        DAG.getIntPtrConstant(0, dl));
17750   }
17751 
17752   if (VT.getSizeInBits() == 64) {
17753     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
17754     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
17755     //        to match extract_elt for f64.
17756     if (IdxVal == 0)
17757       return Op;
17758 
17759     // UNPCKHPD the element to the lowest double word, then movsd.
17760     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
17761     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
17762     int Mask[2] = { 1, -1 };
17763     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
17764     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
17765                        DAG.getIntPtrConstant(0, dl));
17766   }
17767 
17768   return SDValue();
17769 }
17770 
17771 /// Insert one bit to mask vector, like v16i1 or v8i1.
17772 /// AVX-512 feature.
InsertBitToMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17773 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
17774                                      const X86Subtarget &Subtarget) {
17775   SDLoc dl(Op);
17776   SDValue Vec = Op.getOperand(0);
17777   SDValue Elt = Op.getOperand(1);
17778   SDValue Idx = Op.getOperand(2);
17779   MVT VecVT = Vec.getSimpleValueType();
17780 
17781   if (!isa<ConstantSDNode>(Idx)) {
17782     // Non constant index. Extend source and destination,
17783     // insert element and then truncate the result.
17784     unsigned NumElts = VecVT.getVectorNumElements();
17785     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
17786     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
17787     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
17788       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
17789       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
17790     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
17791   }
17792 
17793   // Copy into a k-register, extract to v1i1 and insert_subvector.
17794   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
17795 
17796   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec,
17797                      Op.getOperand(2));
17798 }
17799 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const17800 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
17801                                                   SelectionDAG &DAG) const {
17802   MVT VT = Op.getSimpleValueType();
17803   MVT EltVT = VT.getVectorElementType();
17804   unsigned NumElts = VT.getVectorNumElements();
17805 
17806   if (EltVT == MVT::i1)
17807     return InsertBitToMaskVector(Op, DAG, Subtarget);
17808 
17809   SDLoc dl(Op);
17810   SDValue N0 = Op.getOperand(0);
17811   SDValue N1 = Op.getOperand(1);
17812   SDValue N2 = Op.getOperand(2);
17813 
17814   auto *N2C = dyn_cast<ConstantSDNode>(N2);
17815   if (!N2C || N2C->getAPIntValue().uge(NumElts))
17816     return SDValue();
17817   uint64_t IdxVal = N2C->getZExtValue();
17818 
17819   bool IsZeroElt = X86::isZeroNode(N1);
17820   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
17821 
17822   // If we are inserting a element, see if we can do this more efficiently with
17823   // a blend shuffle with a rematerializable vector than a costly integer
17824   // insertion.
17825   if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
17826       16 <= EltVT.getSizeInBits()) {
17827     SmallVector<int, 8> BlendMask;
17828     for (unsigned i = 0; i != NumElts; ++i)
17829       BlendMask.push_back(i == IdxVal ? i + NumElts : i);
17830     SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
17831                                   : getOnesVector(VT, DAG, dl);
17832     return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
17833   }
17834 
17835   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
17836   // into that, and then insert the subvector back into the result.
17837   if (VT.is256BitVector() || VT.is512BitVector()) {
17838     // With a 256-bit vector, we can insert into the zero element efficiently
17839     // using a blend if we have AVX or AVX2 and the right data type.
17840     if (VT.is256BitVector() && IdxVal == 0) {
17841       // TODO: It is worthwhile to cast integer to floating point and back
17842       // and incur a domain crossing penalty if that's what we'll end up
17843       // doing anyway after extracting to a 128-bit vector.
17844       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
17845           (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
17846         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
17847         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
17848                            DAG.getTargetConstant(1, dl, MVT::i8));
17849       }
17850     }
17851 
17852     // Get the desired 128-bit vector chunk.
17853     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
17854 
17855     // Insert the element into the desired chunk.
17856     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
17857     assert(isPowerOf2_32(NumEltsIn128));
17858     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
17859     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
17860 
17861     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
17862                     DAG.getIntPtrConstant(IdxIn128, dl));
17863 
17864     // Insert the changed part back into the bigger vector
17865     return insert128BitVector(N0, V, IdxVal, DAG, dl);
17866   }
17867   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
17868 
17869   // This will be just movd/movq/movss/movsd.
17870   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode()) &&
17871       (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
17872        EltVT == MVT::i64)) {
17873     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
17874     return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
17875   }
17876 
17877   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
17878   // argument. SSE41 required for pinsrb.
17879   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
17880     unsigned Opc;
17881     if (VT == MVT::v8i16) {
17882       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
17883       Opc = X86ISD::PINSRW;
17884     } else {
17885       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
17886       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
17887       Opc = X86ISD::PINSRB;
17888     }
17889 
17890     if (N1.getValueType() != MVT::i32)
17891       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
17892     if (N2.getValueType() != MVT::i32)
17893       N2 = DAG.getIntPtrConstant(IdxVal, dl);
17894     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
17895   }
17896 
17897   if (Subtarget.hasSSE41()) {
17898     if (EltVT == MVT::f32) {
17899       // Bits [7:6] of the constant are the source select. This will always be
17900       //   zero here. The DAG Combiner may combine an extract_elt index into
17901       //   these bits. For example (insert (extract, 3), 2) could be matched by
17902       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
17903       // Bits [5:4] of the constant are the destination select. This is the
17904       //   value of the incoming immediate.
17905       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
17906       //   combine either bitwise AND or insert of float 0.0 to set these bits.
17907 
17908       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
17909       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
17910         // If this is an insertion of 32-bits into the low 32-bits of
17911         // a vector, we prefer to generate a blend with immediate rather
17912         // than an insertps. Blends are simpler operations in hardware and so
17913         // will always have equal or better performance than insertps.
17914         // But if optimizing for size and there's a load folding opportunity,
17915         // generate insertps because blendps does not have a 32-bit memory
17916         // operand form.
17917         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
17918         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
17919                            DAG.getTargetConstant(1, dl, MVT::i8));
17920       }
17921       // Create this as a scalar to vector..
17922       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
17923       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
17924                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
17925     }
17926 
17927     // PINSR* works with constant index.
17928     if (EltVT == MVT::i32 || EltVT == MVT::i64)
17929       return Op;
17930   }
17931 
17932   return SDValue();
17933 }
17934 
LowerSCALAR_TO_VECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17935 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
17936                                      SelectionDAG &DAG) {
17937   SDLoc dl(Op);
17938   MVT OpVT = Op.getSimpleValueType();
17939 
17940   // It's always cheaper to replace a xor+movd with xorps and simplifies further
17941   // combines.
17942   if (X86::isZeroNode(Op.getOperand(0)))
17943     return getZeroVector(OpVT, Subtarget, DAG, dl);
17944 
17945   // If this is a 256-bit vector result, first insert into a 128-bit
17946   // vector and then insert into the 256-bit vector.
17947   if (!OpVT.is128BitVector()) {
17948     // Insert into a 128-bit vector.
17949     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
17950     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
17951                                  OpVT.getVectorNumElements() / SizeFactor);
17952 
17953     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
17954 
17955     // Insert the 128-bit vector.
17956     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
17957   }
17958   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
17959          "Expected an SSE type!");
17960 
17961   // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
17962   if (OpVT == MVT::v4i32)
17963     return Op;
17964 
17965   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
17966   return DAG.getBitcast(
17967       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
17968 }
17969 
17970 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
17971 // simple superregister reference or explicit instructions to insert
17972 // the upper bits of a vector.
LowerINSERT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17973 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
17974                                      SelectionDAG &DAG) {
17975   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
17976 
17977   return insert1BitVector(Op, DAG, Subtarget);
17978 }
17979 
LowerEXTRACT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17980 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
17981                                       SelectionDAG &DAG) {
17982   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
17983          "Only vXi1 extract_subvectors need custom lowering");
17984 
17985   SDLoc dl(Op);
17986   SDValue Vec = Op.getOperand(0);
17987   SDValue Idx = Op.getOperand(1);
17988 
17989   if (!isa<ConstantSDNode>(Idx))
17990     return SDValue();
17991 
17992   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
17993   if (IdxVal == 0) // the operation is legal
17994     return Op;
17995 
17996   MVT VecVT = Vec.getSimpleValueType();
17997   unsigned NumElems = VecVT.getVectorNumElements();
17998 
17999   // Extend to natively supported kshift.
18000   MVT WideVecVT = VecVT;
18001   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
18002     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18003     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
18004                       DAG.getUNDEF(WideVecVT), Vec,
18005                       DAG.getIntPtrConstant(0, dl));
18006   }
18007 
18008   // Shift to the LSB.
18009   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
18010                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18011 
18012   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
18013                      DAG.getIntPtrConstant(0, dl));
18014 }
18015 
18016 // Returns the appropriate wrapper opcode for a global reference.
getGlobalWrapperKind(const GlobalValue * GV,const unsigned char OpFlags) const18017 unsigned X86TargetLowering::getGlobalWrapperKind(
18018     const GlobalValue *GV, const unsigned char OpFlags) const {
18019   // References to absolute symbols are never PC-relative.
18020   if (GV && GV->isAbsoluteSymbolRef())
18021     return X86ISD::Wrapper;
18022 
18023   CodeModel::Model M = getTargetMachine().getCodeModel();
18024   if (Subtarget.isPICStyleRIPRel() &&
18025       (M == CodeModel::Small || M == CodeModel::Kernel))
18026     return X86ISD::WrapperRIP;
18027 
18028   // GOTPCREL references must always use RIP.
18029   if (OpFlags == X86II::MO_GOTPCREL)
18030     return X86ISD::WrapperRIP;
18031 
18032   return X86ISD::Wrapper;
18033 }
18034 
18035 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
18036 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
18037 // one of the above mentioned nodes. It has to be wrapped because otherwise
18038 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
18039 // be used to form addressing mode. These wrapped nodes will be selected
18040 // into MOV32ri.
18041 SDValue
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const18042 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
18043   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
18044 
18045   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18046   // global base reg.
18047   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18048 
18049   auto PtrVT = getPointerTy(DAG.getDataLayout());
18050   SDValue Result = DAG.getTargetConstantPool(
18051       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
18052   SDLoc DL(CP);
18053   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
18054   // With PIC, the address is actually $g + Offset.
18055   if (OpFlag) {
18056     Result =
18057         DAG.getNode(ISD::ADD, DL, PtrVT,
18058                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18059   }
18060 
18061   return Result;
18062 }
18063 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const18064 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
18065   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
18066 
18067   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18068   // global base reg.
18069   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18070 
18071   auto PtrVT = getPointerTy(DAG.getDataLayout());
18072   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
18073   SDLoc DL(JT);
18074   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
18075 
18076   // With PIC, the address is actually $g + Offset.
18077   if (OpFlag)
18078     Result =
18079         DAG.getNode(ISD::ADD, DL, PtrVT,
18080                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18081 
18082   return Result;
18083 }
18084 
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const18085 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
18086                                                SelectionDAG &DAG) const {
18087   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18088 }
18089 
18090 SDValue
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const18091 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
18092   // Create the TargetBlockAddressAddress node.
18093   unsigned char OpFlags =
18094     Subtarget.classifyBlockAddressReference();
18095   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
18096   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
18097   SDLoc dl(Op);
18098   auto PtrVT = getPointerTy(DAG.getDataLayout());
18099   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
18100   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
18101 
18102   // With PIC, the address is actually $g + Offset.
18103   if (isGlobalRelativeToPICBase(OpFlags)) {
18104     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18105                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18106   }
18107 
18108   return Result;
18109 }
18110 
18111 /// Creates target global address or external symbol nodes for calls or
18112 /// other uses.
LowerGlobalOrExternal(SDValue Op,SelectionDAG & DAG,bool ForCall) const18113 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
18114                                                  bool ForCall) const {
18115   // Unpack the global address or external symbol.
18116   const SDLoc &dl = SDLoc(Op);
18117   const GlobalValue *GV = nullptr;
18118   int64_t Offset = 0;
18119   const char *ExternalSym = nullptr;
18120   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
18121     GV = G->getGlobal();
18122     Offset = G->getOffset();
18123   } else {
18124     const auto *ES = cast<ExternalSymbolSDNode>(Op);
18125     ExternalSym = ES->getSymbol();
18126   }
18127 
18128   // Calculate some flags for address lowering.
18129   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
18130   unsigned char OpFlags;
18131   if (ForCall)
18132     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
18133   else
18134     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
18135   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
18136   bool NeedsLoad = isGlobalStubReference(OpFlags);
18137 
18138   CodeModel::Model M = DAG.getTarget().getCodeModel();
18139   auto PtrVT = getPointerTy(DAG.getDataLayout());
18140   SDValue Result;
18141 
18142   if (GV) {
18143     // Create a target global address if this is a global. If possible, fold the
18144     // offset into the global address reference. Otherwise, ADD it on later.
18145     int64_t GlobalOffset = 0;
18146     if (OpFlags == X86II::MO_NO_FLAG &&
18147         X86::isOffsetSuitableForCodeModel(Offset, M)) {
18148       std::swap(GlobalOffset, Offset);
18149     }
18150     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
18151   } else {
18152     // If this is not a global address, this must be an external symbol.
18153     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
18154   }
18155 
18156   // If this is a direct call, avoid the wrapper if we don't need to do any
18157   // loads or adds. This allows SDAG ISel to match direct calls.
18158   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
18159     return Result;
18160 
18161   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
18162 
18163   // With PIC, the address is actually $g + Offset.
18164   if (HasPICReg) {
18165     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18166                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18167   }
18168 
18169   // For globals that require a load from a stub to get the address, emit the
18170   // load.
18171   if (NeedsLoad)
18172     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
18173                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18174 
18175   // If there was a non-zero offset that we didn't fold, create an explicit
18176   // addition for it.
18177   if (Offset != 0)
18178     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
18179                          DAG.getConstant(Offset, dl, PtrVT));
18180 
18181   return Result;
18182 }
18183 
18184 SDValue
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const18185 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
18186   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18187 }
18188 
18189 static SDValue
GetTLSADDR(SelectionDAG & DAG,SDValue Chain,GlobalAddressSDNode * GA,SDValue * InFlag,const EVT PtrVT,unsigned ReturnReg,unsigned char OperandFlags,bool LocalDynamic=false)18190 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
18191            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
18192            unsigned char OperandFlags, bool LocalDynamic = false) {
18193   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18194   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18195   SDLoc dl(GA);
18196   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18197                                            GA->getValueType(0),
18198                                            GA->getOffset(),
18199                                            OperandFlags);
18200 
18201   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
18202                                            : X86ISD::TLSADDR;
18203 
18204   if (InFlag) {
18205     SDValue Ops[] = { Chain,  TGA, *InFlag };
18206     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18207   } else {
18208     SDValue Ops[]  = { Chain, TGA };
18209     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18210   }
18211 
18212   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
18213   MFI.setAdjustsStack(true);
18214   MFI.setHasCalls(true);
18215 
18216   SDValue Flag = Chain.getValue(1);
18217   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
18218 }
18219 
18220 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
18221 static SDValue
LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18222 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18223                                 const EVT PtrVT) {
18224   SDValue InFlag;
18225   SDLoc dl(GA);  // ? function entry point might be better
18226   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18227                                    DAG.getNode(X86ISD::GlobalBaseReg,
18228                                                SDLoc(), PtrVT), InFlag);
18229   InFlag = Chain.getValue(1);
18230 
18231   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
18232 }
18233 
18234 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
18235 static SDValue
LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18236 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18237                                 const EVT PtrVT) {
18238   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
18239                     X86::RAX, X86II::MO_TLSGD);
18240 }
18241 
LowerToTLSLocalDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,bool is64Bit)18242 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
18243                                            SelectionDAG &DAG,
18244                                            const EVT PtrVT,
18245                                            bool is64Bit) {
18246   SDLoc dl(GA);
18247 
18248   // Get the start address of the TLS block for this module.
18249   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
18250       .getInfo<X86MachineFunctionInfo>();
18251   MFI->incNumLocalDynamicTLSAccesses();
18252 
18253   SDValue Base;
18254   if (is64Bit) {
18255     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
18256                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
18257   } else {
18258     SDValue InFlag;
18259     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18260         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
18261     InFlag = Chain.getValue(1);
18262     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
18263                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
18264   }
18265 
18266   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
18267   // of Base.
18268 
18269   // Build x@dtpoff.
18270   unsigned char OperandFlags = X86II::MO_DTPOFF;
18271   unsigned WrapperKind = X86ISD::Wrapper;
18272   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18273                                            GA->getValueType(0),
18274                                            GA->getOffset(), OperandFlags);
18275   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18276 
18277   // Add x@dtpoff with the base.
18278   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
18279 }
18280 
18281 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
LowerToTLSExecModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,TLSModel::Model model,bool is64Bit,bool isPIC)18282 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18283                                    const EVT PtrVT, TLSModel::Model model,
18284                                    bool is64Bit, bool isPIC) {
18285   SDLoc dl(GA);
18286 
18287   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
18288   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
18289                                                          is64Bit ? 257 : 256));
18290 
18291   SDValue ThreadPointer =
18292       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
18293                   MachinePointerInfo(Ptr));
18294 
18295   unsigned char OperandFlags = 0;
18296   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
18297   // initialexec.
18298   unsigned WrapperKind = X86ISD::Wrapper;
18299   if (model == TLSModel::LocalExec) {
18300     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
18301   } else if (model == TLSModel::InitialExec) {
18302     if (is64Bit) {
18303       OperandFlags = X86II::MO_GOTTPOFF;
18304       WrapperKind = X86ISD::WrapperRIP;
18305     } else {
18306       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
18307     }
18308   } else {
18309     llvm_unreachable("Unexpected model");
18310   }
18311 
18312   // emit "addl x@ntpoff,%eax" (local exec)
18313   // or "addl x@indntpoff,%eax" (initial exec)
18314   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
18315   SDValue TGA =
18316       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
18317                                  GA->getOffset(), OperandFlags);
18318   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18319 
18320   if (model == TLSModel::InitialExec) {
18321     if (isPIC && !is64Bit) {
18322       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
18323                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18324                            Offset);
18325     }
18326 
18327     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
18328                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18329   }
18330 
18331   // The address of the thread local variable is the add of the thread
18332   // pointer with the offset of the variable.
18333   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
18334 }
18335 
18336 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const18337 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
18338 
18339   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
18340 
18341   if (DAG.getTarget().useEmulatedTLS())
18342     return LowerToTLSEmulatedModel(GA, DAG);
18343 
18344   const GlobalValue *GV = GA->getGlobal();
18345   auto PtrVT = getPointerTy(DAG.getDataLayout());
18346   bool PositionIndependent = isPositionIndependent();
18347 
18348   if (Subtarget.isTargetELF()) {
18349     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
18350     switch (model) {
18351       case TLSModel::GeneralDynamic:
18352         if (Subtarget.is64Bit())
18353           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
18354         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
18355       case TLSModel::LocalDynamic:
18356         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
18357                                            Subtarget.is64Bit());
18358       case TLSModel::InitialExec:
18359       case TLSModel::LocalExec:
18360         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
18361                                    PositionIndependent);
18362     }
18363     llvm_unreachable("Unknown TLS model.");
18364   }
18365 
18366   if (Subtarget.isTargetDarwin()) {
18367     // Darwin only has one model of TLS.  Lower to that.
18368     unsigned char OpFlag = 0;
18369     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
18370                            X86ISD::WrapperRIP : X86ISD::Wrapper;
18371 
18372     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18373     // global base reg.
18374     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
18375     if (PIC32)
18376       OpFlag = X86II::MO_TLVP_PIC_BASE;
18377     else
18378       OpFlag = X86II::MO_TLVP;
18379     SDLoc DL(Op);
18380     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
18381                                                 GA->getValueType(0),
18382                                                 GA->getOffset(), OpFlag);
18383     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
18384 
18385     // With PIC32, the address is actually $g + Offset.
18386     if (PIC32)
18387       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
18388                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18389                            Offset);
18390 
18391     // Lowering the machine isd will make sure everything is in the right
18392     // location.
18393     SDValue Chain = DAG.getEntryNode();
18394     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18395     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
18396     SDValue Args[] = { Chain, Offset };
18397     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
18398     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
18399                                DAG.getIntPtrConstant(0, DL, true),
18400                                Chain.getValue(1), DL);
18401 
18402     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
18403     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18404     MFI.setAdjustsStack(true);
18405 
18406     // And our return value (tls address) is in the standard call return value
18407     // location.
18408     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
18409     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
18410   }
18411 
18412   if (Subtarget.isOSWindows()) {
18413     // Just use the implicit TLS architecture
18414     // Need to generate something similar to:
18415     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
18416     //                                  ; from TEB
18417     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
18418     //   mov     rcx, qword [rdx+rcx*8]
18419     //   mov     eax, .tls$:tlsvar
18420     //   [rax+rcx] contains the address
18421     // Windows 64bit: gs:0x58
18422     // Windows 32bit: fs:__tls_array
18423 
18424     SDLoc dl(GA);
18425     SDValue Chain = DAG.getEntryNode();
18426 
18427     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
18428     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
18429     // use its literal value of 0x2C.
18430     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
18431                                         ? Type::getInt8PtrTy(*DAG.getContext(),
18432                                                              256)
18433                                         : Type::getInt32PtrTy(*DAG.getContext(),
18434                                                               257));
18435 
18436     SDValue TlsArray = Subtarget.is64Bit()
18437                            ? DAG.getIntPtrConstant(0x58, dl)
18438                            : (Subtarget.isTargetWindowsGNU()
18439                                   ? DAG.getIntPtrConstant(0x2C, dl)
18440                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
18441 
18442     SDValue ThreadPointer =
18443         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
18444 
18445     SDValue res;
18446     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
18447       res = ThreadPointer;
18448     } else {
18449       // Load the _tls_index variable
18450       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
18451       if (Subtarget.is64Bit())
18452         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
18453                              MachinePointerInfo(), MVT::i32);
18454       else
18455         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
18456 
18457       auto &DL = DAG.getDataLayout();
18458       SDValue Scale =
18459           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
18460       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
18461 
18462       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
18463     }
18464 
18465     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
18466 
18467     // Get the offset of start of .tls section
18468     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18469                                              GA->getValueType(0),
18470                                              GA->getOffset(), X86II::MO_SECREL);
18471     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
18472 
18473     // The address of the thread local variable is the add of the thread
18474     // pointer with the offset of the variable.
18475     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
18476   }
18477 
18478   llvm_unreachable("TLS not implemented for this target.");
18479 }
18480 
18481 /// Lower SRA_PARTS and friends, which return two i32 values
18482 /// and take a 2 x i32 value to shift plus a shift amount.
18483 /// TODO: Can this be moved to general expansion code?
LowerShiftParts(SDValue Op,SelectionDAG & DAG)18484 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
18485   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
18486   MVT VT = Op.getSimpleValueType();
18487   unsigned VTBits = VT.getSizeInBits();
18488   SDLoc dl(Op);
18489   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
18490   SDValue ShOpLo = Op.getOperand(0);
18491   SDValue ShOpHi = Op.getOperand(1);
18492   SDValue ShAmt  = Op.getOperand(2);
18493   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
18494   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's optimized away
18495   // during isel.
18496   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
18497                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
18498   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
18499                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
18500                        : DAG.getConstant(0, dl, VT);
18501 
18502   SDValue Tmp2, Tmp3;
18503   if (Op.getOpcode() == ISD::SHL_PARTS) {
18504     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
18505     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
18506   } else {
18507     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
18508     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
18509   }
18510 
18511   // If the shift amount is larger or equal than the width of a part we can't
18512   // rely on the results of shld/shrd. Insert a test and select the appropriate
18513   // values for large shift amounts.
18514   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
18515                                 DAG.getConstant(VTBits, dl, MVT::i8));
18516   SDValue Cond = DAG.getSetCC(dl, MVT::i8, AndNode,
18517                              DAG.getConstant(0, dl, MVT::i8), ISD::SETNE);
18518 
18519   SDValue Hi, Lo;
18520   if (Op.getOpcode() == ISD::SHL_PARTS) {
18521     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
18522     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
18523   } else {
18524     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
18525     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
18526   }
18527 
18528   return DAG.getMergeValues({ Lo, Hi }, dl);
18529 }
18530 
LowerFunnelShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18531 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
18532                                 SelectionDAG &DAG) {
18533   MVT VT = Op.getSimpleValueType();
18534   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
18535          "Unexpected funnel shift opcode!");
18536 
18537   SDLoc DL(Op);
18538   SDValue Op0 = Op.getOperand(0);
18539   SDValue Op1 = Op.getOperand(1);
18540   SDValue Amt = Op.getOperand(2);
18541 
18542   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
18543 
18544   if (VT.isVector()) {
18545     assert(Subtarget.hasVBMI2() && "Expected VBMI2");
18546 
18547     if (IsFSHR)
18548       std::swap(Op0, Op1);
18549 
18550     APInt APIntShiftAmt;
18551     if (X86::isConstantSplat(Amt, APIntShiftAmt)) {
18552       uint64_t ShiftAmt = APIntShiftAmt.urem(VT.getScalarSizeInBits());
18553       return DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT, Op0,
18554                          Op1, DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18555     }
18556 
18557     return DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
18558                        Op0, Op1, Amt);
18559   }
18560 
18561   assert((VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
18562          "Unexpected funnel shift type!");
18563 
18564   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
18565   bool OptForSize = DAG.shouldOptForSize();
18566   if (!OptForSize && Subtarget.isSHLDSlow())
18567     return SDValue();
18568 
18569   if (IsFSHR)
18570     std::swap(Op0, Op1);
18571 
18572   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
18573   if (VT == MVT::i16)
18574     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
18575                       DAG.getConstant(15, DL, Amt.getValueType()));
18576 
18577   unsigned SHDOp = (IsFSHR ? X86ISD::SHRD : X86ISD::SHLD);
18578   return DAG.getNode(SHDOp, DL, VT, Op0, Op1, Amt);
18579 }
18580 
18581 // Try to use a packed vector operation to handle i64 on 32-bit targets when
18582 // AVX512DQ is enabled.
LowerI64IntToFP_AVX512DQ(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18583 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
18584                                         const X86Subtarget &Subtarget) {
18585   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
18586           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
18587           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
18588           Op.getOpcode() == ISD::UINT_TO_FP) &&
18589          "Unexpected opcode!");
18590   bool IsStrict = Op->isStrictFPOpcode();
18591   unsigned OpNo = IsStrict ? 1 : 0;
18592   SDValue Src = Op.getOperand(OpNo);
18593   MVT SrcVT = Src.getSimpleValueType();
18594   MVT VT = Op.getSimpleValueType();
18595 
18596    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
18597        (VT != MVT::f32 && VT != MVT::f64))
18598     return SDValue();
18599 
18600   // Pack the i64 into a vector, do the operation and extract.
18601 
18602   // Using 256-bit to ensure result is 128-bits for f32 case.
18603   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
18604   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
18605   MVT VecVT = MVT::getVectorVT(VT, NumElts);
18606 
18607   SDLoc dl(Op);
18608   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
18609   if (IsStrict) {
18610     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
18611                                  {Op.getOperand(0), InVec});
18612     SDValue Chain = CvtVec.getValue(1);
18613     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18614                                 DAG.getIntPtrConstant(0, dl));
18615     return DAG.getMergeValues({Value, Chain}, dl);
18616   }
18617 
18618   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
18619 
18620   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18621                      DAG.getIntPtrConstant(0, dl));
18622 }
18623 
useVectorCast(unsigned Opcode,MVT FromVT,MVT ToVT,const X86Subtarget & Subtarget)18624 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
18625                           const X86Subtarget &Subtarget) {
18626   switch (Opcode) {
18627     case ISD::SINT_TO_FP:
18628       // TODO: Handle wider types with AVX/AVX512.
18629       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
18630         return false;
18631       // CVTDQ2PS or (V)CVTDQ2PD
18632       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
18633 
18634     case ISD::UINT_TO_FP:
18635       // TODO: Handle wider types and i64 elements.
18636       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
18637         return false;
18638       // VCVTUDQ2PS or VCVTUDQ2PD
18639       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
18640 
18641     default:
18642       return false;
18643   }
18644 }
18645 
18646 /// Given a scalar cast operation that is extracted from a vector, try to
18647 /// vectorize the cast op followed by extraction. This will avoid an expensive
18648 /// round-trip between XMM and GPR.
vectorizeExtractedCast(SDValue Cast,SelectionDAG & DAG,const X86Subtarget & Subtarget)18649 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
18650                                       const X86Subtarget &Subtarget) {
18651   // TODO: This could be enhanced to handle smaller integer types by peeking
18652   // through an extend.
18653   SDValue Extract = Cast.getOperand(0);
18654   MVT DestVT = Cast.getSimpleValueType();
18655   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18656       !isa<ConstantSDNode>(Extract.getOperand(1)))
18657     return SDValue();
18658 
18659   // See if we have a 128-bit vector cast op for this type of cast.
18660   SDValue VecOp = Extract.getOperand(0);
18661   MVT FromVT = VecOp.getSimpleValueType();
18662   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
18663   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
18664   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
18665   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
18666     return SDValue();
18667 
18668   // If we are extracting from a non-zero element, first shuffle the source
18669   // vector to allow extracting from element zero.
18670   SDLoc DL(Cast);
18671   if (!isNullConstant(Extract.getOperand(1))) {
18672     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
18673     Mask[0] = Extract.getConstantOperandVal(1);
18674     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
18675   }
18676   // If the source vector is wider than 128-bits, extract the low part. Do not
18677   // create an unnecessarily wide vector cast op.
18678   if (FromVT != Vec128VT)
18679     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
18680 
18681   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
18682   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
18683   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
18684   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
18685                      DAG.getIntPtrConstant(0, DL));
18686 }
18687 
lowerINT_TO_FP_vXi64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18688 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
18689                                     const X86Subtarget &Subtarget) {
18690   SDLoc DL(Op);
18691   bool IsStrict = Op->isStrictFPOpcode();
18692   MVT VT = Op->getSimpleValueType(0);
18693   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
18694 
18695   if (Subtarget.hasDQI()) {
18696     assert(!Subtarget.hasVLX() && "Unexpected features");
18697 
18698     assert((Src.getSimpleValueType() == MVT::v2i64 ||
18699             Src.getSimpleValueType() == MVT::v4i64) &&
18700            "Unsupported custom type");
18701 
18702     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
18703     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
18704            "Unexpected VT!");
18705     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
18706 
18707     // Need to concat with zero vector for strict fp to avoid spurious
18708     // exceptions.
18709     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
18710                            : DAG.getUNDEF(MVT::v8i64);
18711     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
18712                       DAG.getIntPtrConstant(0, DL));
18713     SDValue Res, Chain;
18714     if (IsStrict) {
18715       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
18716                         {Op->getOperand(0), Src});
18717       Chain = Res.getValue(1);
18718     } else {
18719       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
18720     }
18721 
18722     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18723                       DAG.getIntPtrConstant(0, DL));
18724 
18725     if (IsStrict)
18726       return DAG.getMergeValues({Res, Chain}, DL);
18727     return Res;
18728   }
18729 
18730   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
18731                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
18732   if (VT != MVT::v4f32 || IsSigned)
18733     return SDValue();
18734 
18735   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
18736   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
18737   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
18738                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
18739                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
18740   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
18741   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
18742   SmallVector<SDValue, 4> SignCvts(4);
18743   SmallVector<SDValue, 4> Chains(4);
18744   for (int i = 0; i != 4; ++i) {
18745     SDValue Src = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
18746                               DAG.getIntPtrConstant(i, DL));
18747     if (IsStrict) {
18748       SignCvts[i] =
18749           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
18750                       {Op.getOperand(0), Src});
18751       Chains[i] = SignCvts[i].getValue(1);
18752     } else {
18753       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Src);
18754     }
18755   }
18756   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
18757 
18758   SDValue Slow, Chain;
18759   if (IsStrict) {
18760     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18761     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
18762                        {Chain, SignCvt, SignCvt});
18763     Chain = Slow.getValue(1);
18764   } else {
18765     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
18766   }
18767 
18768   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
18769   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
18770 
18771   if (IsStrict)
18772     return DAG.getMergeValues({Cvt, Chain}, DL);
18773 
18774   return Cvt;
18775 }
18776 
LowerSINT_TO_FP(SDValue Op,SelectionDAG & DAG) const18777 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
18778                                            SelectionDAG &DAG) const {
18779   bool IsStrict = Op->isStrictFPOpcode();
18780   unsigned OpNo = IsStrict ? 1 : 0;
18781   SDValue Src = Op.getOperand(OpNo);
18782   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
18783   MVT SrcVT = Src.getSimpleValueType();
18784   MVT VT = Op.getSimpleValueType();
18785   SDLoc dl(Op);
18786 
18787   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
18788     return Extract;
18789 
18790   if (SrcVT.isVector()) {
18791     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
18792       // Note: Since v2f64 is a legal type. We don't need to zero extend the
18793       // source for strict FP.
18794       if (IsStrict)
18795         return DAG.getNode(
18796             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
18797             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
18798                                 DAG.getUNDEF(SrcVT))});
18799       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
18800                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
18801                                      DAG.getUNDEF(SrcVT)));
18802     }
18803     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
18804       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
18805 
18806     return SDValue();
18807   }
18808 
18809   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
18810          "Unknown SINT_TO_FP to lower!");
18811 
18812   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
18813 
18814   // These are really Legal; return the operand so the caller accepts it as
18815   // Legal.
18816   if (SrcVT == MVT::i32 && UseSSEReg)
18817     return Op;
18818   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
18819     return Op;
18820 
18821   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
18822     return V;
18823 
18824   // SSE doesn't have an i16 conversion so we need to promote.
18825   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
18826     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
18827     if (IsStrict)
18828       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
18829                          {Chain, Ext});
18830 
18831     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
18832   }
18833 
18834   if (VT == MVT::f128)
18835     return LowerF128Call(Op, DAG, RTLIB::getSINTTOFP(SrcVT, VT));
18836 
18837   SDValue ValueToStore = Src;
18838   if (SrcVT == MVT::i64 && UseSSEReg && !Subtarget.is64Bit())
18839     // Bitcasting to f64 here allows us to do a single 64-bit store from
18840     // an SSE register, avoiding the store forwarding penalty that would come
18841     // with two 32-bit stores.
18842     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
18843 
18844   unsigned Size = SrcVT.getSizeInBits()/8;
18845   MachineFunction &MF = DAG.getMachineFunction();
18846   auto PtrVT = getPointerTy(MF.getDataLayout());
18847   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Size, false);
18848   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
18849   Chain = DAG.getStore(
18850       Chain, dl, ValueToStore, StackSlot,
18851       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
18852   std::pair<SDValue, SDValue> Tmp = BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
18853 
18854   if (IsStrict)
18855     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
18856 
18857   return Tmp.first;
18858 }
18859 
BuildFILD(SDValue Op,EVT SrcVT,SDValue Chain,SDValue StackSlot,SelectionDAG & DAG) const18860 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
18861                                      SDValue StackSlot,
18862                                      SelectionDAG &DAG) const {
18863   // Build the FILD
18864   SDLoc DL(Op);
18865   SDVTList Tys;
18866   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
18867   if (useSSE)
18868     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
18869   else
18870     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
18871 
18872   unsigned ByteSize = SrcVT.getSizeInBits() / 8;
18873 
18874   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
18875   MachineMemOperand *LoadMMO;
18876   if (FI) {
18877     int SSFI = FI->getIndex();
18878     LoadMMO = DAG.getMachineFunction().getMachineMemOperand(
18879         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
18880         MachineMemOperand::MOLoad, ByteSize, ByteSize);
18881   } else {
18882     LoadMMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
18883     StackSlot = StackSlot.getOperand(1);
18884   }
18885   SDValue FILDOps[] = {Chain, StackSlot};
18886   SDValue Result =
18887       DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, DL,
18888                               Tys, FILDOps, SrcVT, LoadMMO);
18889   Chain = Result.getValue(1);
18890 
18891   if (useSSE) {
18892     SDValue InFlag = Result.getValue(2);
18893 
18894     // FIXME: Currently the FST is glued to the FILD_FLAG. This
18895     // shouldn't be necessary except that RFP cannot be live across
18896     // multiple blocks. When stackifier is fixed, they can be uncoupled.
18897     MachineFunction &MF = DAG.getMachineFunction();
18898     unsigned SSFISize = Op.getValueSizeInBits() / 8;
18899     int SSFI = MF.getFrameInfo().CreateStackObject(SSFISize, SSFISize, false);
18900     auto PtrVT = getPointerTy(MF.getDataLayout());
18901     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
18902     Tys = DAG.getVTList(MVT::Other);
18903     SDValue FSTOps[] = {Chain, Result, StackSlot, InFlag};
18904     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
18905         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
18906         MachineMemOperand::MOStore, SSFISize, SSFISize);
18907 
18908     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps,
18909                                     Op.getValueType(), StoreMMO);
18910     Result = DAG.getLoad(
18911         Op.getValueType(), DL, Chain, StackSlot,
18912         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
18913     Chain = Result.getValue(1);
18914   }
18915 
18916   return { Result, Chain };
18917 }
18918 
18919 /// Horizontal vector math instructions may be slower than normal math with
18920 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
18921 /// implementation, and likely shuffle complexity of the alternate sequence.
shouldUseHorizontalOp(bool IsSingleSource,SelectionDAG & DAG,const X86Subtarget & Subtarget)18922 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
18923                                   const X86Subtarget &Subtarget) {
18924   bool IsOptimizingSize = DAG.shouldOptForSize();
18925   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
18926   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
18927 }
18928 
18929 /// 64-bit unsigned integer to double expansion.
LowerUINT_TO_FP_i64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18930 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
18931                                    const X86Subtarget &Subtarget) {
18932   // This algorithm is not obvious. Here it is what we're trying to output:
18933   /*
18934      movq       %rax,  %xmm0
18935      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
18936      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
18937      #ifdef __SSE3__
18938        haddpd   %xmm0, %xmm0
18939      #else
18940        pshufd   $0x4e, %xmm0, %xmm1
18941        addpd    %xmm1, %xmm0
18942      #endif
18943   */
18944 
18945   bool IsStrict = Op->isStrictFPOpcode();
18946   unsigned OpNo = IsStrict ? 1 : 0;
18947   SDLoc dl(Op);
18948   LLVMContext *Context = DAG.getContext();
18949 
18950   // Build some magic constants.
18951   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
18952   Constant *C0 = ConstantDataVector::get(*Context, CV0);
18953   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
18954   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
18955 
18956   SmallVector<Constant*,2> CV1;
18957   CV1.push_back(
18958     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
18959                                       APInt(64, 0x4330000000000000ULL))));
18960   CV1.push_back(
18961     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
18962                                       APInt(64, 0x4530000000000000ULL))));
18963   Constant *C1 = ConstantVector::get(CV1);
18964   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
18965 
18966   // Load the 64-bit value into an XMM register.
18967   SDValue XR1 =
18968       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(OpNo));
18969   SDValue CLod0 =
18970       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
18971                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
18972                   /* Alignment = */ 16);
18973   SDValue Unpck1 =
18974       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
18975 
18976   SDValue CLod1 =
18977       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
18978                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
18979                   /* Alignment = */ 16);
18980   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
18981   SDValue Sub;
18982   SDValue Chain;
18983   // TODO: Are there any fast-math-flags to propagate here?
18984   if (IsStrict) {
18985     Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
18986                       {Op.getOperand(0), XR2F, CLod1});
18987     Chain = Sub.getValue(1);
18988   } else
18989     Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
18990   SDValue Result;
18991 
18992   if (!IsStrict && Subtarget.hasSSE3() &&
18993       shouldUseHorizontalOp(true, DAG, Subtarget)) {
18994     // FIXME: Do we need a STRICT version of FHADD?
18995     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
18996   } else {
18997     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
18998     if (IsStrict) {
18999       Result = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v2f64, MVT::Other},
19000                            {Chain, Shuffle, Sub});
19001       Chain = Result.getValue(1);
19002     } else
19003       Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
19004   }
19005   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
19006                        DAG.getIntPtrConstant(0, dl));
19007   if (IsStrict)
19008     return DAG.getMergeValues({Result, Chain}, dl);
19009 
19010   return Result;
19011 }
19012 
19013 /// 32-bit unsigned integer to float expansion.
LowerUINT_TO_FP_i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19014 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
19015                                    const X86Subtarget &Subtarget) {
19016   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19017   SDLoc dl(Op);
19018   // FP constant to bias correct the final result.
19019   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19020                                    MVT::f64);
19021 
19022   // Load the 32-bit value into an XMM register.
19023   SDValue Load =
19024       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
19025 
19026   // Zero out the upper parts of the register.
19027   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
19028 
19029   // Or the load with the bias.
19030   SDValue Or = DAG.getNode(
19031       ISD::OR, dl, MVT::v2i64,
19032       DAG.getBitcast(MVT::v2i64, Load),
19033       DAG.getBitcast(MVT::v2i64,
19034                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
19035   Or =
19036       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
19037                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
19038 
19039   if (Op.getNode()->isStrictFPOpcode()) {
19040     // Subtract the bias.
19041     // TODO: Are there any fast-math-flags to propagate here?
19042     SDValue Chain = Op.getOperand(0);
19043     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
19044                               {Chain, Or, Bias});
19045 
19046     if (Op.getValueType() == Sub.getValueType())
19047       return Sub;
19048 
19049     // Handle final rounding.
19050     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
19051         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
19052 
19053     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
19054   }
19055 
19056   // Subtract the bias.
19057   // TODO: Are there any fast-math-flags to propagate here?
19058   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
19059 
19060   // Handle final rounding.
19061   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
19062 }
19063 
lowerUINT_TO_FP_v2i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)19064 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
19065                                      const X86Subtarget &Subtarget,
19066                                      const SDLoc &DL) {
19067   if (Op.getSimpleValueType() != MVT::v2f64)
19068     return SDValue();
19069 
19070   bool IsStrict = Op->isStrictFPOpcode();
19071 
19072   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
19073   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
19074 
19075   if (Subtarget.hasAVX512()) {
19076     if (!Subtarget.hasVLX()) {
19077       // Let generic type legalization widen this.
19078       if (!IsStrict)
19079         return SDValue();
19080       // Otherwise pad the integer input with 0s and widen the operation.
19081       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19082                        DAG.getConstant(0, DL, MVT::v2i32));
19083       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
19084                                 {Op.getOperand(0), N0});
19085       SDValue Chain = Res.getValue(1);
19086       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
19087                         DAG.getIntPtrConstant(0, DL));
19088       return DAG.getMergeValues({Res, Chain}, DL);
19089     }
19090 
19091     // Legalize to v4i32 type.
19092     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19093                      DAG.getUNDEF(MVT::v2i32));
19094     if (IsStrict)
19095       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
19096                          {Op.getOperand(0), N0});
19097     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
19098   }
19099 
19100   // Zero extend to 2i64, OR with the floating point representation of 2^52.
19101   // This gives us the floating point equivalent of 2^52 + the i32 integer
19102   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
19103   // point leaving just our i32 integers in double format.
19104   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
19105   SDValue VBias =
19106       DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
19107   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
19108                            DAG.getBitcast(MVT::v2i64, VBias));
19109   Or = DAG.getBitcast(MVT::v2f64, Or);
19110 
19111   if (IsStrict)
19112     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
19113                        {Op.getOperand(0), Or, VBias});
19114   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
19115 }
19116 
lowerUINT_TO_FP_vXi32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19117 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
19118                                      const X86Subtarget &Subtarget) {
19119   SDLoc DL(Op);
19120   bool IsStrict = Op->isStrictFPOpcode();
19121   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
19122   MVT VecIntVT = V.getSimpleValueType();
19123   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
19124          "Unsupported custom type");
19125 
19126   if (Subtarget.hasAVX512()) {
19127     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19128     assert(!Subtarget.hasVLX() && "Unexpected features");
19129     MVT VT = Op->getSimpleValueType(0);
19130 
19131     // v8i32->v8f64 is legal with AVX512 so just return it.
19132     if (VT == MVT::v8f64)
19133       return Op;
19134 
19135     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
19136            "Unexpected VT!");
19137     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
19138     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
19139     // Need to concat with zero vector for strict fp to avoid spurious
19140     // exceptions.
19141     SDValue Tmp =
19142         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
19143     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
19144                     DAG.getIntPtrConstant(0, DL));
19145     SDValue Res, Chain;
19146     if (IsStrict) {
19147       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
19148                         {Op->getOperand(0), V});
19149       Chain = Res.getValue(1);
19150     } else {
19151       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
19152     }
19153 
19154     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19155                       DAG.getIntPtrConstant(0, DL));
19156 
19157     if (IsStrict)
19158       return DAG.getMergeValues({Res, Chain}, DL);
19159     return Res;
19160   }
19161 
19162   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
19163       Op->getSimpleValueType(0) == MVT::v4f64) {
19164     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
19165     Constant *Bias = ConstantFP::get(
19166         *DAG.getContext(),
19167         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
19168     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19169     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, /*Alignment*/ 8);
19170     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
19171     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
19172     SDValue VBias = DAG.getMemIntrinsicNode(
19173         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
19174         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
19175         /*Alignment*/ 8, MachineMemOperand::MOLoad);
19176 
19177     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
19178                              DAG.getBitcast(MVT::v4i64, VBias));
19179     Or = DAG.getBitcast(MVT::v4f64, Or);
19180 
19181     if (IsStrict)
19182       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
19183                          {Op.getOperand(0), Or, VBias});
19184     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
19185   }
19186 
19187   // The algorithm is the following:
19188   // #ifdef __SSE4_1__
19189   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19190   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19191   //                                 (uint4) 0x53000000, 0xaa);
19192   // #else
19193   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19194   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19195   // #endif
19196   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19197   //     return (float4) lo + fhi;
19198 
19199   bool Is128 = VecIntVT == MVT::v4i32;
19200   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
19201   // If we convert to something else than the supported type, e.g., to v4f64,
19202   // abort early.
19203   if (VecFloatVT != Op->getSimpleValueType(0))
19204     return SDValue();
19205 
19206   // In the #idef/#else code, we have in common:
19207   // - The vector of constants:
19208   // -- 0x4b000000
19209   // -- 0x53000000
19210   // - A shift:
19211   // -- v >> 16
19212 
19213   // Create the splat vector for 0x4b000000.
19214   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
19215   // Create the splat vector for 0x53000000.
19216   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
19217 
19218   // Create the right shift.
19219   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
19220   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
19221 
19222   SDValue Low, High;
19223   if (Subtarget.hasSSE41()) {
19224     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
19225     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19226     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
19227     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
19228     // Low will be bitcasted right away, so do not bother bitcasting back to its
19229     // original type.
19230     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
19231                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19232     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19233     //                                 (uint4) 0x53000000, 0xaa);
19234     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
19235     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
19236     // High will be bitcasted right away, so do not bother bitcasting back to
19237     // its original type.
19238     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
19239                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19240   } else {
19241     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
19242     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19243     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
19244     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
19245 
19246     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19247     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
19248   }
19249 
19250   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
19251   SDValue VecCstFSub = DAG.getConstantFP(
19252       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
19253 
19254   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19255   // NOTE: By using fsub of a positive constant instead of fadd of a negative
19256   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
19257   // enabled. See PR24512.
19258   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
19259   // TODO: Are there any fast-math-flags to propagate here?
19260   //     (float4) lo;
19261   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
19262   //     return (float4) lo + fhi;
19263   if (IsStrict) {
19264     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
19265                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
19266     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
19267                        {FHigh.getValue(1), LowBitcast, FHigh});
19268   }
19269 
19270   SDValue FHigh =
19271       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
19272   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
19273 }
19274 
lowerUINT_TO_FP_vec(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19275 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
19276                                    const X86Subtarget &Subtarget) {
19277   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19278   SDValue N0 = Op.getOperand(OpNo);
19279   MVT SrcVT = N0.getSimpleValueType();
19280   SDLoc dl(Op);
19281 
19282   switch (SrcVT.SimpleTy) {
19283   default:
19284     llvm_unreachable("Custom UINT_TO_FP is not supported!");
19285   case MVT::v2i32:
19286     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
19287   case MVT::v4i32:
19288   case MVT::v8i32:
19289     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
19290   case MVT::v2i64:
19291   case MVT::v4i64:
19292     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19293   }
19294 }
19295 
LowerUINT_TO_FP(SDValue Op,SelectionDAG & DAG) const19296 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
19297                                            SelectionDAG &DAG) const {
19298   bool IsStrict = Op->isStrictFPOpcode();
19299   unsigned OpNo = IsStrict ? 1 : 0;
19300   SDValue Src = Op.getOperand(OpNo);
19301   SDLoc dl(Op);
19302   auto PtrVT = getPointerTy(DAG.getDataLayout());
19303   MVT SrcVT = Src.getSimpleValueType();
19304   MVT DstVT = Op->getSimpleValueType(0);
19305   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
19306 
19307   if (DstVT == MVT::f128)
19308     return LowerF128Call(Op, DAG, RTLIB::getUINTTOFP(SrcVT, DstVT));
19309 
19310   if (DstVT.isVector())
19311     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
19312 
19313   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19314     return Extract;
19315 
19316   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
19317       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
19318     // Conversions from unsigned i32 to f32/f64 are legal,
19319     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
19320     return Op;
19321   }
19322 
19323   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
19324   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
19325     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
19326     if (IsStrict)
19327       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
19328                          {Chain, Src});
19329     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
19330   }
19331 
19332   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19333     return V;
19334 
19335   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
19336     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
19337   if (SrcVT == MVT::i32 && X86ScalarSSEf64 && DstVT != MVT::f80)
19338     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
19339   if (Subtarget.is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
19340     return SDValue();
19341 
19342   // Make a 64-bit buffer, and use it to build an FILD.
19343   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
19344   if (SrcVT == MVT::i32) {
19345     SDValue OffsetSlot = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
19346     SDValue Store1 =
19347         DAG.getStore(Chain, dl, Src, StackSlot, MachinePointerInfo());
19348     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
19349                                   OffsetSlot, MachinePointerInfo());
19350     std::pair<SDValue, SDValue> Tmp =
19351         BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
19352     if (IsStrict)
19353       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19354 
19355     return Tmp.first;
19356   }
19357 
19358   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
19359   SDValue ValueToStore = Src;
19360   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
19361     // Bitcasting to f64 here allows us to do a single 64-bit store from
19362     // an SSE register, avoiding the store forwarding penalty that would come
19363     // with two 32-bit stores.
19364     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19365   }
19366   SDValue Store =
19367       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MachinePointerInfo());
19368   // For i64 source, we need to add the appropriate power of 2 if the input
19369   // was negative.  This is the same as the optimization in
19370   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
19371   // we must be careful to do the computation in x87 extended precision, not
19372   // in SSE. (The generic code can't know it's OK to do this, or how to.)
19373   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
19374   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
19375       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
19376       MachineMemOperand::MOLoad, 8, 8);
19377 
19378   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
19379   SDValue Ops[] = { Store, StackSlot };
19380   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
19381                                          MVT::i64, MMO);
19382   Chain = Fild.getValue(1);
19383 
19384 
19385   // Check whether the sign bit is set.
19386   SDValue SignSet = DAG.getSetCC(
19387       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
19388       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
19389 
19390   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
19391   APInt FF(64, 0x5F80000000000000ULL);
19392   SDValue FudgePtr = DAG.getConstantPool(
19393       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
19394 
19395   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
19396   SDValue Zero = DAG.getIntPtrConstant(0, dl);
19397   SDValue Four = DAG.getIntPtrConstant(4, dl);
19398   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
19399   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
19400 
19401   // Load the value out, extending it from f32 to f80.
19402   SDValue Fudge = DAG.getExtLoad(
19403       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
19404       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
19405       /* Alignment = */ 4);
19406   Chain = Fudge.getValue(1);
19407   // Extend everything to 80 bits to force it to be done on x87.
19408   // TODO: Are there any fast-math-flags to propagate here?
19409   if (IsStrict) {
19410     SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
19411                               {Chain, Fild, Fudge});
19412     // STRICT_FP_ROUND can't handle equal types.
19413     if (DstVT == MVT::f80)
19414       return Add;
19415     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
19416                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
19417   }
19418   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
19419   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
19420                      DAG.getIntPtrConstant(0, dl));
19421 }
19422 
19423 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
19424 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
19425 // just return an SDValue().
19426 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
19427 // to i16, i32 or i64, and we lower it to a legal sequence and return the
19428 // result.
19429 SDValue
FP_TO_INTHelper(SDValue Op,SelectionDAG & DAG,bool IsSigned,SDValue & Chain) const19430 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
19431                                    bool IsSigned, SDValue &Chain) const {
19432   bool IsStrict = Op->isStrictFPOpcode();
19433   SDLoc DL(Op);
19434 
19435   EVT DstTy = Op.getValueType();
19436   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
19437   EVT TheVT = Value.getValueType();
19438   auto PtrVT = getPointerTy(DAG.getDataLayout());
19439 
19440   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
19441     // f16 must be promoted before using the lowering in this routine.
19442     // fp128 does not use this lowering.
19443     return SDValue();
19444   }
19445 
19446   // If using FIST to compute an unsigned i64, we'll need some fixup
19447   // to handle values above the maximum signed i64.  A FIST is always
19448   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
19449   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
19450 
19451   // FIXME: This does not generate an invalid exception if the input does not
19452   // fit in i32. PR44019
19453   if (!IsSigned && DstTy != MVT::i64) {
19454     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
19455     // The low 32 bits of the fist result will have the correct uint32 result.
19456     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
19457     DstTy = MVT::i64;
19458   }
19459 
19460   assert(DstTy.getSimpleVT() <= MVT::i64 &&
19461          DstTy.getSimpleVT() >= MVT::i16 &&
19462          "Unknown FP_TO_INT to lower!");
19463 
19464   // We lower FP->int64 into FISTP64 followed by a load from a temporary
19465   // stack slot.
19466   MachineFunction &MF = DAG.getMachineFunction();
19467   unsigned MemSize = DstTy.getStoreSize();
19468   int SSFI = MF.getFrameInfo().CreateStackObject(MemSize, MemSize, false);
19469   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19470 
19471   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
19472 
19473   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
19474 
19475   if (UnsignedFixup) {
19476     //
19477     // Conversion to unsigned i64 is implemented with a select,
19478     // depending on whether the source value fits in the range
19479     // of a signed i64.  Let Thresh be the FP equivalent of
19480     // 0x8000000000000000ULL.
19481     //
19482     //  Adjust = (Value < Thresh) ? 0 : 0x80000000;
19483     //  FltOfs = (Value < Thresh) ? 0 : 0x80000000;
19484     //  FistSrc = (Value - FltOfs);
19485     //  Fist-to-mem64 FistSrc
19486     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
19487     //  to XOR'ing the high 32 bits with Adjust.
19488     //
19489     // Being a power of 2, Thresh is exactly representable in all FP formats.
19490     // For X87 we'd like to use the smallest FP type for this constant, but
19491     // for DAG type consistency we have to match the FP operand type.
19492 
19493     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
19494     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
19495     bool LosesInfo = false;
19496     if (TheVT == MVT::f64)
19497       // The rounding mode is irrelevant as the conversion should be exact.
19498       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
19499                               &LosesInfo);
19500     else if (TheVT == MVT::f80)
19501       Status = Thresh.convert(APFloat::x87DoubleExtended(),
19502                               APFloat::rmNearestTiesToEven, &LosesInfo);
19503 
19504     assert(Status == APFloat::opOK && !LosesInfo &&
19505            "FP conversion should have been exact");
19506 
19507     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
19508 
19509     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
19510                                    *DAG.getContext(), TheVT);
19511     SDValue Cmp;
19512     if (IsStrict) {
19513       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETLT,
19514                          Chain, /*IsSignaling*/ true);
19515       Chain = Cmp.getValue(1);
19516     } else {
19517       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETLT);
19518     }
19519 
19520     Adjust = DAG.getSelect(DL, MVT::i64, Cmp,
19521                            DAG.getConstant(0, DL, MVT::i64),
19522                            DAG.getConstant(APInt::getSignMask(64),
19523                                            DL, MVT::i64));
19524     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp,
19525                                    DAG.getConstantFP(0.0, DL, TheVT),
19526                                    ThreshVal);
19527 
19528     if (IsStrict) {
19529       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
19530                           { Chain, Value, FltOfs });
19531       Chain = Value.getValue(1);
19532     } else
19533       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
19534   }
19535 
19536   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
19537 
19538   // FIXME This causes a redundant load/store if the SSE-class value is already
19539   // in memory, such as if it is on the callstack.
19540   if (isScalarFPTypeInSSEReg(TheVT)) {
19541     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
19542     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
19543     SDVTList Tys = DAG.getVTList(TheVT, MVT::Other);
19544     SDValue Ops[] = { Chain, StackSlot };
19545 
19546     unsigned FLDSize = TheVT.getStoreSize();
19547     assert(FLDSize <= MemSize && "Stack slot not big enough");
19548     MachineMemOperand *MMO = MF.getMachineMemOperand(
19549         MPI, MachineMemOperand::MOLoad, FLDSize, FLDSize);
19550     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
19551     Chain = Value.getValue(1);
19552   }
19553 
19554   // Build the FP_TO_INT*_IN_MEM
19555   MachineMemOperand *MMO = MF.getMachineMemOperand(
19556       MPI, MachineMemOperand::MOStore, MemSize, MemSize);
19557   SDValue Ops[] = { Chain, Value, StackSlot };
19558   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
19559                                          DAG.getVTList(MVT::Other),
19560                                          Ops, DstTy, MMO);
19561 
19562   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
19563   Chain = Res.getValue(1);
19564 
19565   // If we need an unsigned fixup, XOR the result with adjust.
19566   if (UnsignedFixup)
19567     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
19568 
19569   return Res;
19570 }
19571 
LowerAVXExtend(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19572 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
19573                               const X86Subtarget &Subtarget) {
19574   MVT VT = Op.getSimpleValueType();
19575   SDValue In = Op.getOperand(0);
19576   MVT InVT = In.getSimpleValueType();
19577   SDLoc dl(Op);
19578   unsigned Opc = Op.getOpcode();
19579 
19580   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
19581   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
19582          "Unexpected extension opcode");
19583   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
19584          "Expected same number of elements");
19585   assert((VT.getVectorElementType() == MVT::i16 ||
19586           VT.getVectorElementType() == MVT::i32 ||
19587           VT.getVectorElementType() == MVT::i64) &&
19588          "Unexpected element type");
19589   assert((InVT.getVectorElementType() == MVT::i8 ||
19590           InVT.getVectorElementType() == MVT::i16 ||
19591           InVT.getVectorElementType() == MVT::i32) &&
19592          "Unexpected element type");
19593 
19594   unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
19595 
19596   // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
19597   if (InVT == MVT::v8i8) {
19598     if (VT != MVT::v8i64)
19599       return SDValue();
19600 
19601     In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
19602                      MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
19603     return DAG.getNode(ExtendInVecOpc, dl, VT, In);
19604   }
19605 
19606   if (Subtarget.hasInt256())
19607     return Op;
19608 
19609   // Optimize vectors in AVX mode:
19610   //
19611   //   v8i16 -> v8i32
19612   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
19613   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
19614   //   Concat upper and lower parts.
19615   //
19616   //   v4i32 -> v4i64
19617   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
19618   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
19619   //   Concat upper and lower parts.
19620   //
19621   MVT HalfVT = VT.getHalfNumVectorElementsVT();
19622   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
19623 
19624   // Short-circuit if we can determine that each 128-bit half is the same value.
19625   // Otherwise, this is difficult to match and optimize.
19626   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
19627     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
19628       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
19629 
19630   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
19631   SDValue Undef = DAG.getUNDEF(InVT);
19632   bool NeedZero = Opc == ISD::ZERO_EXTEND;
19633   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
19634   OpHi = DAG.getBitcast(HalfVT, OpHi);
19635 
19636   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
19637 }
19638 
19639 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
SplitAndExtendv16i1(unsigned ExtOpc,MVT VT,SDValue In,const SDLoc & dl,SelectionDAG & DAG)19640 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
19641                                    const SDLoc &dl, SelectionDAG &DAG) {
19642   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
19643   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
19644                            DAG.getIntPtrConstant(0, dl));
19645   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
19646                            DAG.getIntPtrConstant(8, dl));
19647   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
19648   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
19649   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
19650   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19651 }
19652 
LowerZERO_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)19653 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
19654                                       const X86Subtarget &Subtarget,
19655                                       SelectionDAG &DAG) {
19656   MVT VT = Op->getSimpleValueType(0);
19657   SDValue In = Op->getOperand(0);
19658   MVT InVT = In.getSimpleValueType();
19659   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
19660   SDLoc DL(Op);
19661   unsigned NumElts = VT.getVectorNumElements();
19662 
19663   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
19664   // avoids a constant pool load.
19665   if (VT.getVectorElementType() != MVT::i8) {
19666     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
19667     return DAG.getNode(ISD::SRL, DL, VT, Extend,
19668                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
19669   }
19670 
19671   // Extend VT if BWI is not supported.
19672   MVT ExtVT = VT;
19673   if (!Subtarget.hasBWI()) {
19674     // If v16i32 is to be avoided, we'll need to split and concatenate.
19675     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
19676       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
19677 
19678     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
19679   }
19680 
19681   // Widen to 512-bits if VLX is not supported.
19682   MVT WideVT = ExtVT;
19683   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
19684     NumElts *= 512 / ExtVT.getSizeInBits();
19685     InVT = MVT::getVectorVT(MVT::i1, NumElts);
19686     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
19687                      In, DAG.getIntPtrConstant(0, DL));
19688     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
19689                               NumElts);
19690   }
19691 
19692   SDValue One = DAG.getConstant(1, DL, WideVT);
19693   SDValue Zero = DAG.getConstant(0, DL, WideVT);
19694 
19695   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
19696 
19697   // Truncate if we had to extend above.
19698   if (VT != ExtVT) {
19699     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
19700     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
19701   }
19702 
19703   // Extract back to 128/256-bit if we widened.
19704   if (WideVT != VT)
19705     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
19706                               DAG.getIntPtrConstant(0, DL));
19707 
19708   return SelectedVal;
19709 }
19710 
LowerZERO_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)19711 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
19712                                 SelectionDAG &DAG) {
19713   SDValue In = Op.getOperand(0);
19714   MVT SVT = In.getSimpleValueType();
19715 
19716   if (SVT.getVectorElementType() == MVT::i1)
19717     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
19718 
19719   assert(Subtarget.hasAVX() && "Expected AVX support");
19720   return LowerAVXExtend(Op, DAG, Subtarget);
19721 }
19722 
19723 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
19724 /// It makes use of the fact that vectors with enough leading sign/zero bits
19725 /// prevent the PACKSS/PACKUS from saturating the results.
19726 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
19727 /// within each 128-bit lane.
truncateVectorWithPACK(unsigned Opcode,EVT DstVT,SDValue In,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)19728 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
19729                                       const SDLoc &DL, SelectionDAG &DAG,
19730                                       const X86Subtarget &Subtarget) {
19731   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
19732          "Unexpected PACK opcode");
19733   assert(DstVT.isVector() && "VT not a vector?");
19734 
19735   // Requires SSE2 but AVX512 has fast vector truncate.
19736   if (!Subtarget.hasSSE2())
19737     return SDValue();
19738 
19739   EVT SrcVT = In.getValueType();
19740 
19741   // No truncation required, we might get here due to recursive calls.
19742   if (SrcVT == DstVT)
19743     return In;
19744 
19745   // We only support vector truncation to 64bits or greater from a
19746   // 128bits or greater source.
19747   unsigned DstSizeInBits = DstVT.getSizeInBits();
19748   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
19749   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
19750     return SDValue();
19751 
19752   unsigned NumElems = SrcVT.getVectorNumElements();
19753   if (!isPowerOf2_32(NumElems))
19754     return SDValue();
19755 
19756   LLVMContext &Ctx = *DAG.getContext();
19757   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
19758   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
19759 
19760   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
19761 
19762   // Pack to the largest type possible:
19763   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
19764   EVT InVT = MVT::i16, OutVT = MVT::i8;
19765   if (SrcVT.getScalarSizeInBits() > 16 &&
19766       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
19767     InVT = MVT::i32;
19768     OutVT = MVT::i16;
19769   }
19770 
19771   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
19772   if (SrcVT.is128BitVector()) {
19773     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
19774     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
19775     In = DAG.getBitcast(InVT, In);
19776     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, In);
19777     Res = extractSubVector(Res, 0, DAG, DL, 64);
19778     return DAG.getBitcast(DstVT, Res);
19779   }
19780 
19781   // Extract lower/upper subvectors.
19782   unsigned NumSubElts = NumElems / 2;
19783   SDValue Lo = extractSubVector(In, 0 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
19784   SDValue Hi = extractSubVector(In, 1 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
19785 
19786   unsigned SubSizeInBits = SrcSizeInBits / 2;
19787   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
19788   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
19789 
19790   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
19791   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
19792     Lo = DAG.getBitcast(InVT, Lo);
19793     Hi = DAG.getBitcast(InVT, Hi);
19794     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
19795     return DAG.getBitcast(DstVT, Res);
19796   }
19797 
19798   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
19799   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
19800   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
19801     Lo = DAG.getBitcast(InVT, Lo);
19802     Hi = DAG.getBitcast(InVT, Hi);
19803     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
19804 
19805     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
19806     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
19807     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
19808     SmallVector<int, 64> Mask;
19809     int Scale = 64 / OutVT.getScalarSizeInBits();
19810     scaleShuffleMask<int>(Scale, ArrayRef<int>({ 0, 2, 1, 3 }), Mask);
19811     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
19812 
19813     if (DstVT.is256BitVector())
19814       return DAG.getBitcast(DstVT, Res);
19815 
19816     // If 512bit -> 128bit truncate another stage.
19817     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
19818     Res = DAG.getBitcast(PackedVT, Res);
19819     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
19820   }
19821 
19822   // Recursively pack lower/upper subvectors, concat result and pack again.
19823   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
19824   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumSubElts);
19825   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
19826   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
19827 
19828   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
19829   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
19830   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
19831 }
19832 
LowerTruncateVecI1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19833 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
19834                                   const X86Subtarget &Subtarget) {
19835 
19836   SDLoc DL(Op);
19837   MVT VT = Op.getSimpleValueType();
19838   SDValue In = Op.getOperand(0);
19839   MVT InVT = In.getSimpleValueType();
19840 
19841   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
19842 
19843   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
19844   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
19845   if (InVT.getScalarSizeInBits() <= 16) {
19846     if (Subtarget.hasBWI()) {
19847       // legal, will go to VPMOVB2M, VPMOVW2M
19848       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
19849         // We need to shift to get the lsb into sign position.
19850         // Shift packed bytes not supported natively, bitcast to word
19851         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
19852         In = DAG.getNode(ISD::SHL, DL, ExtVT,
19853                          DAG.getBitcast(ExtVT, In),
19854                          DAG.getConstant(ShiftInx, DL, ExtVT));
19855         In = DAG.getBitcast(InVT, In);
19856       }
19857       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
19858                           In, ISD::SETGT);
19859     }
19860     // Use TESTD/Q, extended vector to packed dword/qword.
19861     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
19862            "Unexpected vector type.");
19863     unsigned NumElts = InVT.getVectorNumElements();
19864     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
19865     // We need to change to a wider element type that we have support for.
19866     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
19867     // For 16 element vectors we extend to v16i32 unless we are explicitly
19868     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
19869     // we need to split into two 8 element vectors which we can extend to v8i32,
19870     // truncate and concat the results. There's an additional complication if
19871     // the original type is v16i8. In that case we can't split the v16i8 so
19872     // first we pre-extend it to v16i16 which we can split to v8i16, then extend
19873     // to v8i32, truncate that to v8i1 and concat the two halves.
19874     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
19875       if (InVT == MVT::v16i8) {
19876         // First we need to sign extend up to 256-bits so we can split that.
19877         InVT = MVT::v16i16;
19878         In = DAG.getNode(ISD::SIGN_EXTEND, DL, InVT, In);
19879       }
19880       SDValue Lo = extract128BitVector(In, 0, DAG, DL);
19881       SDValue Hi = extract128BitVector(In, 8, DAG, DL);
19882       // We're split now, just emit two truncates and a concat. The two
19883       // truncates will trigger legalization to come back to this function.
19884       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
19885       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
19886       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
19887     }
19888     // We either have 8 elements or we're allowed to use 512-bit vectors.
19889     // If we have VLX, we want to use the narrowest vector that can get the
19890     // job done so we use vXi32.
19891     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
19892     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
19893     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
19894     InVT = ExtVT;
19895     ShiftInx = InVT.getScalarSizeInBits() - 1;
19896   }
19897 
19898   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
19899     // We need to shift to get the lsb into sign position.
19900     In = DAG.getNode(ISD::SHL, DL, InVT, In,
19901                      DAG.getConstant(ShiftInx, DL, InVT));
19902   }
19903   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
19904   if (Subtarget.hasDQI())
19905     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
19906   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
19907 }
19908 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const19909 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
19910   SDLoc DL(Op);
19911   MVT VT = Op.getSimpleValueType();
19912   SDValue In = Op.getOperand(0);
19913   MVT InVT = In.getSimpleValueType();
19914   unsigned InNumEltBits = InVT.getScalarSizeInBits();
19915 
19916   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
19917          "Invalid TRUNCATE operation");
19918 
19919   // If we're called by the type legalizer, handle a few cases.
19920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19921   if (!TLI.isTypeLegal(InVT)) {
19922     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
19923         VT.is128BitVector()) {
19924       assert(Subtarget.hasVLX() && "Unexpected subtarget!");
19925       // The default behavior is to truncate one step, concatenate, and then
19926       // truncate the remainder. We'd rather produce two 64-bit results and
19927       // concatenate those.
19928       SDValue Lo, Hi;
19929       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
19930 
19931       EVT LoVT, HiVT;
19932       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
19933 
19934       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
19935       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
19936       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
19937     }
19938 
19939     // Otherwise let default legalization handle it.
19940     return SDValue();
19941   }
19942 
19943   if (VT.getVectorElementType() == MVT::i1)
19944     return LowerTruncateVecI1(Op, DAG, Subtarget);
19945 
19946   // vpmovqb/w/d, vpmovdb/w, vpmovwb
19947   if (Subtarget.hasAVX512()) {
19948     // word to byte only under BWI. Otherwise we have to promoted to v16i32
19949     // and then truncate that. But we should only do that if we haven't been
19950     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
19951     // handled by isel patterns.
19952     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
19953         Subtarget.canExtendTo512DQ())
19954       return Op;
19955   }
19956 
19957   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
19958   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
19959 
19960   // Truncate with PACKUS if we are truncating a vector with leading zero bits
19961   // that extend all the way to the packed/truncated value.
19962   // Pre-SSE41 we can only use PACKUSWB.
19963   KnownBits Known = DAG.computeKnownBits(In);
19964   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
19965     if (SDValue V =
19966             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
19967       return V;
19968 
19969   // Truncate with PACKSS if we are truncating a vector with sign-bits that
19970   // extend all the way to the packed/truncated value.
19971   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
19972     if (SDValue V =
19973             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
19974       return V;
19975 
19976   // Handle truncation of V256 to V128 using shuffles.
19977   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
19978 
19979   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
19980     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
19981     if (Subtarget.hasInt256()) {
19982       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
19983       In = DAG.getBitcast(MVT::v8i32, In);
19984       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
19985       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
19986                          DAG.getIntPtrConstant(0, DL));
19987     }
19988 
19989     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
19990                                DAG.getIntPtrConstant(0, DL));
19991     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
19992                                DAG.getIntPtrConstant(2, DL));
19993     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
19994     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
19995     static const int ShufMask[] = {0, 2, 4, 6};
19996     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
19997   }
19998 
19999   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
20000     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
20001     if (Subtarget.hasInt256()) {
20002       In = DAG.getBitcast(MVT::v32i8, In);
20003 
20004       // The PSHUFB mask:
20005       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
20006                                       -1, -1, -1, -1, -1, -1, -1, -1,
20007                                       16, 17, 20, 21, 24, 25, 28, 29,
20008                                       -1, -1, -1, -1, -1, -1, -1, -1 };
20009       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
20010       In = DAG.getBitcast(MVT::v4i64, In);
20011 
20012       static const int ShufMask2[] = {0,  2,  -1,  -1};
20013       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, In, ShufMask2);
20014       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20015                        DAG.getIntPtrConstant(0, DL));
20016       return DAG.getBitcast(VT, In);
20017     }
20018 
20019     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
20020                                DAG.getIntPtrConstant(0, DL));
20021 
20022     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
20023                                DAG.getIntPtrConstant(4, DL));
20024 
20025     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
20026     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
20027 
20028     // The PSHUFB mask:
20029     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
20030                                    -1, -1, -1, -1, -1, -1, -1, -1};
20031 
20032     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
20033     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
20034 
20035     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
20036     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
20037 
20038     // The MOVLHPS Mask:
20039     static const int ShufMask2[] = {0, 1, 4, 5};
20040     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
20041     return DAG.getBitcast(MVT::v8i16, res);
20042   }
20043 
20044   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
20045     // Use an AND to zero uppper bits for PACKUS.
20046     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
20047 
20048     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
20049                                DAG.getIntPtrConstant(0, DL));
20050     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
20051                                DAG.getIntPtrConstant(8, DL));
20052     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
20053   }
20054 
20055   llvm_unreachable("All 256->128 cases should have been handled above!");
20056 }
20057 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const20058 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
20059   bool IsStrict = Op->isStrictFPOpcode();
20060   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
20061                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
20062   MVT VT = Op->getSimpleValueType(0);
20063   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20064   MVT SrcVT = Src.getSimpleValueType();
20065   SDLoc dl(Op);
20066 
20067   if (VT.isVector()) {
20068     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
20069       MVT ResVT = MVT::v4i32;
20070       MVT TruncVT = MVT::v4i1;
20071       unsigned Opc;
20072       if (IsStrict)
20073         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
20074       else
20075         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20076 
20077       if (!IsSigned && !Subtarget.hasVLX()) {
20078         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
20079         // Widen to 512-bits.
20080         ResVT = MVT::v8i32;
20081         TruncVT = MVT::v8i1;
20082         Opc = Op.getOpcode();
20083         // Need to concat with zero vector for strict fp to avoid spurious
20084         // exceptions.
20085         // TODO: Should we just do this for non-strict as well?
20086         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
20087                                : DAG.getUNDEF(MVT::v8f64);
20088         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
20089                           DAG.getIntPtrConstant(0, dl));
20090       }
20091       SDValue Res, Chain;
20092       if (IsStrict) {
20093         Res =
20094             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Op->getOperand(0), Src});
20095         Chain = Res.getValue(1);
20096       } else {
20097         Res = DAG.getNode(Opc, dl, ResVT, Src);
20098       }
20099 
20100       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
20101       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
20102                         DAG.getIntPtrConstant(0, dl));
20103       if (IsStrict)
20104         return DAG.getMergeValues({Res, Chain}, dl);
20105       return Res;
20106     }
20107 
20108     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
20109     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
20110       assert(!IsSigned && "Expected unsigned conversion!");
20111       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
20112       return Op;
20113     }
20114 
20115     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
20116     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
20117         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32)) {
20118       assert(!IsSigned && "Expected unsigned conversion!");
20119       assert(Subtarget.useAVX512Regs() && !Subtarget.hasVLX() &&
20120              "Unexpected features!");
20121       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20122       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20123       // Need to concat with zero vector for strict fp to avoid spurious
20124       // exceptions.
20125       // TODO: Should we just do this for non-strict as well?
20126       SDValue Tmp =
20127           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20128       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20129                         DAG.getIntPtrConstant(0, dl));
20130 
20131       SDValue Res, Chain;
20132       if (IsStrict) {
20133         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
20134                           {Op->getOperand(0), Src});
20135         Chain = Res.getValue(1);
20136       } else {
20137         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
20138       }
20139 
20140       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20141                         DAG.getIntPtrConstant(0, dl));
20142 
20143       if (IsStrict)
20144         return DAG.getMergeValues({Res, Chain}, dl);
20145       return Res;
20146     }
20147 
20148     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
20149     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
20150         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32)) {
20151       assert(Subtarget.useAVX512Regs() && Subtarget.hasDQI() &&
20152              !Subtarget.hasVLX() && "Unexpected features!");
20153       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20154       // Need to concat with zero vector for strict fp to avoid spurious
20155       // exceptions.
20156       // TODO: Should we just do this for non-strict as well?
20157       SDValue Tmp =
20158           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20159       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20160                         DAG.getIntPtrConstant(0, dl));
20161 
20162       SDValue Res, Chain;
20163       if (IsStrict) {
20164         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
20165                           {Op->getOperand(0), Src});
20166         Chain = Res.getValue(1);
20167       } else {
20168         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
20169       }
20170 
20171       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20172                         DAG.getIntPtrConstant(0, dl));
20173 
20174       if (IsStrict)
20175         return DAG.getMergeValues({Res, Chain}, dl);
20176       return Res;
20177     }
20178 
20179     if (VT == MVT::v2i64 && SrcVT  == MVT::v2f32) {
20180       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
20181       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
20182                                 DAG.getUNDEF(MVT::v2f32));
20183       if (IsStrict) {
20184         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
20185                                 : X86ISD::STRICT_CVTTP2UI;
20186         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
20187       }
20188       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20189       return DAG.getNode(Opc, dl, VT, Tmp);
20190     }
20191 
20192     return SDValue();
20193   }
20194 
20195   assert(!VT.isVector());
20196 
20197   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
20198 
20199   if (!IsSigned && UseSSEReg) {
20200     // Conversions from f32/f64 with AVX512 should be legal.
20201     if (Subtarget.hasAVX512())
20202       return Op;
20203 
20204     // Use default expansion for i64.
20205     if (VT == MVT::i64)
20206       return SDValue();
20207 
20208     assert(VT == MVT::i32 && "Unexpected VT!");
20209 
20210     // Promote i32 to i64 and use a signed operation on 64-bit targets.
20211     // FIXME: This does not generate an invalid exception if the input does not
20212     // fit in i32. PR44019
20213     if (Subtarget.is64Bit()) {
20214       SDValue Res, Chain;
20215       if (IsStrict) {
20216         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i64, MVT::Other},
20217                           { Op.getOperand(0), Src });
20218         Chain = Res.getValue(1);
20219       } else
20220         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
20221 
20222       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20223       if (IsStrict)
20224         return DAG.getMergeValues({ Res, Chain }, dl);
20225       return Res;
20226     }
20227 
20228     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
20229     // use fisttp which will be handled later.
20230     if (!Subtarget.hasSSE3())
20231       return SDValue();
20232   }
20233 
20234   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
20235   // FIXME: This does not generate an invalid exception if the input does not
20236   // fit in i16. PR44019
20237   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
20238     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
20239     SDValue Res, Chain;
20240     if (IsStrict) {
20241       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i32, MVT::Other},
20242                         { Op.getOperand(0), Src });
20243       Chain = Res.getValue(1);
20244     } else
20245       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
20246 
20247     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20248     if (IsStrict)
20249       return DAG.getMergeValues({ Res, Chain }, dl);
20250     return Res;
20251   }
20252 
20253   // If this is a FP_TO_SINT using SSEReg we're done.
20254   if (UseSSEReg && IsSigned)
20255     return Op;
20256 
20257   // fp128 needs to use a libcall.
20258   if (SrcVT == MVT::f128) {
20259     RTLIB::Libcall LC;
20260     if (IsSigned)
20261       LC = RTLIB::getFPTOSINT(SrcVT, VT);
20262     else
20263       LC = RTLIB::getFPTOUINT(SrcVT, VT);
20264 
20265     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20266     MakeLibCallOptions CallOptions;
20267     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
20268                                                   SDLoc(Op), Chain);
20269 
20270     if (IsStrict)
20271       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
20272 
20273     return Tmp.first;
20274   }
20275 
20276   // Fall back to X87.
20277   SDValue Chain;
20278   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
20279     if (IsStrict)
20280       return DAG.getMergeValues({V, Chain}, dl);
20281     return V;
20282   }
20283 
20284   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
20285 }
20286 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const20287 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20288   bool IsStrict = Op->isStrictFPOpcode();
20289 
20290   SDLoc DL(Op);
20291   MVT VT = Op.getSimpleValueType();
20292   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
20293   MVT SVT = In.getSimpleValueType();
20294 
20295   if (VT == MVT::f128) {
20296     RTLIB::Libcall LC = RTLIB::getFPEXT(SVT, VT);
20297     return LowerF128Call(Op, DAG, LC);
20298   }
20299 
20300   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
20301 
20302   SDValue Res =
20303       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
20304   if (IsStrict)
20305     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
20306                        {Op->getOperand(0), Res});
20307   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
20308 }
20309 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const20310 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20311   bool IsStrict = Op->isStrictFPOpcode();
20312 
20313   MVT VT = Op.getSimpleValueType();
20314   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
20315   MVT SVT = In.getSimpleValueType();
20316 
20317   // It's legal except when f128 is involved
20318   if (SVT != MVT::f128)
20319     return Op;
20320 
20321   RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, VT);
20322 
20323   // FP_ROUND node has a second operand indicating whether it is known to be
20324   // precise. That doesn't take part in the LibCall so we can't directly use
20325   // LowerF128Call.
20326 
20327   SDLoc dl(Op);
20328   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20329   MakeLibCallOptions CallOptions;
20330   std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, In, CallOptions,
20331                                                 dl, Chain);
20332 
20333   if (IsStrict)
20334     return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
20335 
20336   return Tmp.first;
20337 }
20338 
20339 /// Depending on uarch and/or optimizing for size, we might prefer to use a
20340 /// vector operation in place of the typical scalar operation.
lowerAddSubToHorizontalOp(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)20341 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
20342                                          const X86Subtarget &Subtarget) {
20343   // If both operands have other uses, this is probably not profitable.
20344   SDValue LHS = Op.getOperand(0);
20345   SDValue RHS = Op.getOperand(1);
20346   if (!LHS.hasOneUse() && !RHS.hasOneUse())
20347     return Op;
20348 
20349   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
20350   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
20351   if (IsFP && !Subtarget.hasSSE3())
20352     return Op;
20353   if (!IsFP && !Subtarget.hasSSSE3())
20354     return Op;
20355 
20356   // Extract from a common vector.
20357   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20358       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20359       LHS.getOperand(0) != RHS.getOperand(0) ||
20360       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
20361       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
20362       !shouldUseHorizontalOp(true, DAG, Subtarget))
20363     return Op;
20364 
20365   // Allow commuted 'hadd' ops.
20366   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
20367   unsigned HOpcode;
20368   switch (Op.getOpcode()) {
20369     case ISD::ADD: HOpcode = X86ISD::HADD; break;
20370     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
20371     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
20372     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
20373     default:
20374       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
20375   }
20376   unsigned LExtIndex = LHS.getConstantOperandVal(1);
20377   unsigned RExtIndex = RHS.getConstantOperandVal(1);
20378   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
20379       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
20380     std::swap(LExtIndex, RExtIndex);
20381 
20382   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
20383     return Op;
20384 
20385   SDValue X = LHS.getOperand(0);
20386   EVT VecVT = X.getValueType();
20387   unsigned BitWidth = VecVT.getSizeInBits();
20388   unsigned NumLanes = BitWidth / 128;
20389   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
20390   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
20391          "Not expecting illegal vector widths here");
20392 
20393   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
20394   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
20395   SDLoc DL(Op);
20396   if (BitWidth == 256 || BitWidth == 512) {
20397     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
20398     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
20399     LExtIndex %= NumEltsPerLane;
20400   }
20401 
20402   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
20403   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
20404   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
20405   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
20406   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
20407   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
20408                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
20409 }
20410 
20411 /// Depending on uarch and/or optimizing for size, we might prefer to use a
20412 /// vector operation in place of the typical scalar operation.
lowerFaddFsub(SDValue Op,SelectionDAG & DAG) const20413 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
20414   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
20415          "Only expecting float/double");
20416   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
20417 }
20418 
20419 /// The only differences between FABS and FNEG are the mask and the logic op.
20420 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
LowerFABSorFNEG(SDValue Op,SelectionDAG & DAG)20421 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
20422   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
20423          "Wrong opcode for lowering FABS or FNEG.");
20424 
20425   bool IsFABS = (Op.getOpcode() == ISD::FABS);
20426 
20427   // If this is a FABS and it has an FNEG user, bail out to fold the combination
20428   // into an FNABS. We'll lower the FABS after that if it is still in use.
20429   if (IsFABS)
20430     for (SDNode *User : Op->uses())
20431       if (User->getOpcode() == ISD::FNEG)
20432         return Op;
20433 
20434   SDLoc dl(Op);
20435   MVT VT = Op.getSimpleValueType();
20436 
20437   bool IsF128 = (VT == MVT::f128);
20438   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
20439           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
20440           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
20441          "Unexpected type in LowerFABSorFNEG");
20442 
20443   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
20444   // decide if we should generate a 16-byte constant mask when we only need 4 or
20445   // 8 bytes for the scalar case.
20446 
20447   // There are no scalar bitwise logical SSE/AVX instructions, so we
20448   // generate a 16-byte vector constant and logic op even for the scalar case.
20449   // Using a 16-byte mask allows folding the load of the mask with
20450   // the logic op, so it can save (~4 bytes) on code size.
20451   bool IsFakeVector = !VT.isVector() && !IsF128;
20452   MVT LogicVT = VT;
20453   if (IsFakeVector)
20454     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
20455 
20456   unsigned EltBits = VT.getScalarSizeInBits();
20457   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
20458   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
20459                            APInt::getSignMask(EltBits);
20460   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
20461   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
20462 
20463   SDValue Op0 = Op.getOperand(0);
20464   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
20465   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
20466                      IsFNABS ? X86ISD::FOR  :
20467                                X86ISD::FXOR;
20468   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
20469 
20470   if (VT.isVector() || IsF128)
20471     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
20472 
20473   // For the scalar case extend to a 128-bit vector, perform the logic op,
20474   // and extract the scalar result back out.
20475   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
20476   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
20477   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
20478                      DAG.getIntPtrConstant(0, dl));
20479 }
20480 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG)20481 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
20482   SDValue Mag = Op.getOperand(0);
20483   SDValue Sign = Op.getOperand(1);
20484   SDLoc dl(Op);
20485 
20486   // If the sign operand is smaller, extend it first.
20487   MVT VT = Op.getSimpleValueType();
20488   if (Sign.getSimpleValueType().bitsLT(VT))
20489     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
20490 
20491   // And if it is bigger, shrink it first.
20492   if (Sign.getSimpleValueType().bitsGT(VT))
20493     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(1, dl));
20494 
20495   // At this point the operands and the result should have the same
20496   // type, and that won't be f80 since that is not custom lowered.
20497   bool IsF128 = (VT == MVT::f128);
20498   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
20499           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
20500           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
20501          "Unexpected type in LowerFCOPYSIGN");
20502 
20503   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
20504 
20505   // Perform all scalar logic operations as 16-byte vectors because there are no
20506   // scalar FP logic instructions in SSE.
20507   // TODO: This isn't necessary. If we used scalar types, we might avoid some
20508   // unnecessary splats, but we might miss load folding opportunities. Should
20509   // this decision be based on OptimizeForSize?
20510   bool IsFakeVector = !VT.isVector() && !IsF128;
20511   MVT LogicVT = VT;
20512   if (IsFakeVector)
20513     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
20514 
20515   // The mask constants are automatically splatted for vector types.
20516   unsigned EltSizeInBits = VT.getScalarSizeInBits();
20517   SDValue SignMask = DAG.getConstantFP(
20518       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
20519   SDValue MagMask = DAG.getConstantFP(
20520       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
20521 
20522   // First, clear all bits but the sign bit from the second operand (sign).
20523   if (IsFakeVector)
20524     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
20525   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
20526 
20527   // Next, clear the sign bit from the first operand (magnitude).
20528   // TODO: If we had general constant folding for FP logic ops, this check
20529   // wouldn't be necessary.
20530   SDValue MagBits;
20531   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
20532     APFloat APF = Op0CN->getValueAPF();
20533     APF.clearSign();
20534     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
20535   } else {
20536     // If the magnitude operand wasn't a constant, we need to AND out the sign.
20537     if (IsFakeVector)
20538       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
20539     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
20540   }
20541 
20542   // OR the magnitude value with the sign bit.
20543   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
20544   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
20545                                           DAG.getIntPtrConstant(0, dl));
20546 }
20547 
LowerFGETSIGN(SDValue Op,SelectionDAG & DAG)20548 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
20549   SDValue N0 = Op.getOperand(0);
20550   SDLoc dl(Op);
20551   MVT VT = Op.getSimpleValueType();
20552 
20553   MVT OpVT = N0.getSimpleValueType();
20554   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
20555          "Unexpected type for FGETSIGN");
20556 
20557   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
20558   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
20559   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
20560   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
20561   Res = DAG.getZExtOrTrunc(Res, dl, VT);
20562   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
20563   return Res;
20564 }
20565 
20566 /// Helper for creating a X86ISD::SETCC node.
getSETCC(X86::CondCode Cond,SDValue EFLAGS,const SDLoc & dl,SelectionDAG & DAG)20567 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
20568                         SelectionDAG &DAG) {
20569   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20570                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
20571 }
20572 
20573 /// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
20574 /// style scalarized (associative) reduction patterns.
matchScalarReduction(SDValue Op,ISD::NodeType BinOp,SmallVectorImpl<SDValue> & SrcOps)20575 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
20576                                  SmallVectorImpl<SDValue> &SrcOps) {
20577   SmallVector<SDValue, 8> Opnds;
20578   DenseMap<SDValue, APInt> SrcOpMap;
20579   EVT VT = MVT::Other;
20580 
20581   // Recognize a special case where a vector is casted into wide integer to
20582   // test all 0s.
20583   assert(Op.getOpcode() == unsigned(BinOp) &&
20584          "Unexpected bit reduction opcode");
20585   Opnds.push_back(Op.getOperand(0));
20586   Opnds.push_back(Op.getOperand(1));
20587 
20588   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
20589     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
20590     // BFS traverse all BinOp operands.
20591     if (I->getOpcode() == unsigned(BinOp)) {
20592       Opnds.push_back(I->getOperand(0));
20593       Opnds.push_back(I->getOperand(1));
20594       // Re-evaluate the number of nodes to be traversed.
20595       e += 2; // 2 more nodes (LHS and RHS) are pushed.
20596       continue;
20597     }
20598 
20599     // Quit if a non-EXTRACT_VECTOR_ELT
20600     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20601       return false;
20602 
20603     // Quit if without a constant index.
20604     SDValue Idx = I->getOperand(1);
20605     if (!isa<ConstantSDNode>(Idx))
20606       return false;
20607 
20608     SDValue Src = I->getOperand(0);
20609     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
20610     if (M == SrcOpMap.end()) {
20611       VT = Src.getValueType();
20612       // Quit if not the same type.
20613       if (SrcOpMap.begin() != SrcOpMap.end() &&
20614           VT != SrcOpMap.begin()->first.getValueType())
20615         return false;
20616       unsigned NumElts = VT.getVectorNumElements();
20617       APInt EltCount = APInt::getNullValue(NumElts);
20618       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
20619       SrcOps.push_back(Src);
20620     }
20621     // Quit if element already used.
20622     unsigned CIdx = cast<ConstantSDNode>(Idx)->getZExtValue();
20623     if (M->second[CIdx])
20624       return false;
20625     M->second.setBit(CIdx);
20626   }
20627 
20628   // Quit if not all elements are used.
20629   for (DenseMap<SDValue, APInt>::const_iterator I = SrcOpMap.begin(),
20630                                                 E = SrcOpMap.end();
20631        I != E; ++I) {
20632     if (!I->second.isAllOnesValue())
20633       return false;
20634   }
20635 
20636   return true;
20637 }
20638 
20639 // Check whether an OR'd tree is PTEST-able.
LowerVectorAllZeroTest(SDValue Op,ISD::CondCode CC,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & X86CC)20640 static SDValue LowerVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
20641                                       const X86Subtarget &Subtarget,
20642                                       SelectionDAG &DAG, SDValue &X86CC) {
20643   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
20644 
20645   if (!Subtarget.hasSSE41() || !Op->hasOneUse())
20646     return SDValue();
20647 
20648   SmallVector<SDValue, 8> VecIns;
20649   if (!matchScalarReduction(Op, ISD::OR, VecIns))
20650     return SDValue();
20651 
20652   // Quit if not 128/256-bit vector.
20653   EVT VT = VecIns[0].getValueType();
20654   if (!VT.is128BitVector() && !VT.is256BitVector())
20655     return SDValue();
20656 
20657   SDLoc DL(Op);
20658   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
20659 
20660   // Cast all vectors into TestVT for PTEST.
20661   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
20662     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
20663 
20664   // If more than one full vector is evaluated, OR them first before PTEST.
20665   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
20666     // Each iteration will OR 2 nodes and append the result until there is only
20667     // 1 node left, i.e. the final OR'd value of all vectors.
20668     SDValue LHS = VecIns[Slot];
20669     SDValue RHS = VecIns[Slot + 1];
20670     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
20671   }
20672 
20673   X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE,
20674                                 DL, MVT::i8);
20675   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIns.back(), VecIns.back());
20676 }
20677 
20678 /// return true if \c Op has a use that doesn't just read flags.
hasNonFlagsUse(SDValue Op)20679 static bool hasNonFlagsUse(SDValue Op) {
20680   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
20681        ++UI) {
20682     SDNode *User = *UI;
20683     unsigned UOpNo = UI.getOperandNo();
20684     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
20685       // Look pass truncate.
20686       UOpNo = User->use_begin().getOperandNo();
20687       User = *User->use_begin();
20688     }
20689 
20690     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
20691         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
20692       return true;
20693   }
20694   return false;
20695 }
20696 
20697 // Transform to an x86-specific ALU node with flags if there is a chance of
20698 // using an RMW op or only the flags are used. Otherwise, leave
20699 // the node alone and emit a 'cmp' or 'test' instruction.
isProfitableToUseFlagOp(SDValue Op)20700 static bool isProfitableToUseFlagOp(SDValue Op) {
20701   for (SDNode *U : Op->uses())
20702     if (U->getOpcode() != ISD::CopyToReg &&
20703         U->getOpcode() != ISD::SETCC &&
20704         U->getOpcode() != ISD::STORE)
20705       return false;
20706 
20707   return true;
20708 }
20709 
20710 /// Emit nodes that will be selected as "test Op0,Op0", or something
20711 /// equivalent.
EmitTest(SDValue Op,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)20712 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
20713                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
20714   // CF and OF aren't always set the way we want. Determine which
20715   // of these we need.
20716   bool NeedCF = false;
20717   bool NeedOF = false;
20718   switch (X86CC) {
20719   default: break;
20720   case X86::COND_A: case X86::COND_AE:
20721   case X86::COND_B: case X86::COND_BE:
20722     NeedCF = true;
20723     break;
20724   case X86::COND_G: case X86::COND_GE:
20725   case X86::COND_L: case X86::COND_LE:
20726   case X86::COND_O: case X86::COND_NO: {
20727     // Check if we really need to set the
20728     // Overflow flag. If NoSignedWrap is present
20729     // that is not actually needed.
20730     switch (Op->getOpcode()) {
20731     case ISD::ADD:
20732     case ISD::SUB:
20733     case ISD::MUL:
20734     case ISD::SHL:
20735       if (Op.getNode()->getFlags().hasNoSignedWrap())
20736         break;
20737       LLVM_FALLTHROUGH;
20738     default:
20739       NeedOF = true;
20740       break;
20741     }
20742     break;
20743   }
20744   }
20745   // See if we can use the EFLAGS value from the operand instead of
20746   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
20747   // we prove that the arithmetic won't overflow, we can't use OF or CF.
20748   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
20749     // Emit a CMP with 0, which is the TEST pattern.
20750     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
20751                        DAG.getConstant(0, dl, Op.getValueType()));
20752   }
20753   unsigned Opcode = 0;
20754   unsigned NumOperands = 0;
20755 
20756   SDValue ArithOp = Op;
20757 
20758   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
20759   // which may be the result of a CAST.  We use the variable 'Op', which is the
20760   // non-casted variable when we check for possible users.
20761   switch (ArithOp.getOpcode()) {
20762   case ISD::AND:
20763     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
20764     // because a TEST instruction will be better.
20765     if (!hasNonFlagsUse(Op))
20766       break;
20767 
20768     LLVM_FALLTHROUGH;
20769   case ISD::ADD:
20770   case ISD::SUB:
20771   case ISD::OR:
20772   case ISD::XOR:
20773     if (!isProfitableToUseFlagOp(Op))
20774       break;
20775 
20776     // Otherwise use a regular EFLAGS-setting instruction.
20777     switch (ArithOp.getOpcode()) {
20778     default: llvm_unreachable("unexpected operator!");
20779     case ISD::ADD: Opcode = X86ISD::ADD; break;
20780     case ISD::SUB: Opcode = X86ISD::SUB; break;
20781     case ISD::XOR: Opcode = X86ISD::XOR; break;
20782     case ISD::AND: Opcode = X86ISD::AND; break;
20783     case ISD::OR:  Opcode = X86ISD::OR;  break;
20784     }
20785 
20786     NumOperands = 2;
20787     break;
20788   case X86ISD::ADD:
20789   case X86ISD::SUB:
20790   case X86ISD::OR:
20791   case X86ISD::XOR:
20792   case X86ISD::AND:
20793     return SDValue(Op.getNode(), 1);
20794   case ISD::SSUBO:
20795   case ISD::USUBO: {
20796     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
20797     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20798     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
20799                        Op->getOperand(1)).getValue(1);
20800   }
20801   default:
20802     break;
20803   }
20804 
20805   if (Opcode == 0) {
20806     // Emit a CMP with 0, which is the TEST pattern.
20807     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
20808                        DAG.getConstant(0, dl, Op.getValueType()));
20809   }
20810   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20811   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
20812 
20813   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
20814   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
20815   return SDValue(New.getNode(), 1);
20816 }
20817 
20818 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
20819 /// equivalent.
EmitCmp(SDValue Op0,SDValue Op1,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue Chain,bool IsSignaling)20820 static std::pair<SDValue, SDValue> EmitCmp(SDValue Op0, SDValue Op1,
20821                                            unsigned X86CC, const SDLoc &dl,
20822                                            SelectionDAG &DAG,
20823                                            const X86Subtarget &Subtarget,
20824                                            SDValue Chain, bool IsSignaling) {
20825   if (isNullConstant(Op1))
20826     return std::make_pair(EmitTest(Op0, X86CC, dl, DAG, Subtarget), Chain);
20827 
20828   EVT CmpVT = Op0.getValueType();
20829 
20830   if (CmpVT.isFloatingPoint()) {
20831     if (Chain) {
20832       SDValue Res =
20833           DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
20834                       dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
20835       return std::make_pair(Res, Res.getValue(1));
20836     }
20837     return std::make_pair(DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1),
20838                           SDValue());
20839   }
20840 
20841   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
20842           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
20843 
20844   // Only promote the compare up to I32 if it is a 16 bit operation
20845   // with an immediate.  16 bit immediates are to be avoided.
20846   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
20847       !DAG.getMachineFunction().getFunction().hasMinSize()) {
20848     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
20849     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
20850     // Don't do this if the immediate can fit in 8-bits.
20851     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
20852         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
20853       unsigned ExtendOp =
20854           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
20855       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
20856         // For equality comparisons try to use SIGN_EXTEND if the input was
20857         // truncate from something with enough sign bits.
20858         if (Op0.getOpcode() == ISD::TRUNCATE) {
20859           SDValue In = Op0.getOperand(0);
20860           unsigned EffBits =
20861               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
20862           if (EffBits <= 16)
20863             ExtendOp = ISD::SIGN_EXTEND;
20864         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
20865           SDValue In = Op1.getOperand(0);
20866           unsigned EffBits =
20867               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
20868           if (EffBits <= 16)
20869             ExtendOp = ISD::SIGN_EXTEND;
20870         }
20871       }
20872 
20873       CmpVT = MVT::i32;
20874       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
20875       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
20876     }
20877   }
20878 
20879   // Try to shrink i64 compares if the input has enough zero bits.
20880   // FIXME: Do this for non-constant compares for constant on LHS?
20881   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
20882       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
20883       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
20884       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
20885     CmpVT = MVT::i32;
20886     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
20887     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
20888   }
20889 
20890   // Use SUB instead of CMP to enable CSE between SUB and CMP.
20891   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
20892   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
20893   return std::make_pair(Sub.getValue(1), SDValue());
20894 }
20895 
20896 /// Convert a comparison if required by the subtarget.
ConvertCmpIfNecessary(SDValue Cmp,SelectionDAG & DAG) const20897 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
20898                                                  SelectionDAG &DAG) const {
20899   // If the subtarget does not support the FUCOMI instruction, floating-point
20900   // comparisons have to be converted.
20901   bool IsCmp = Cmp.getOpcode() == X86ISD::CMP;
20902   bool IsStrictCmp = Cmp.getOpcode() == X86ISD::STRICT_FCMP ||
20903                      Cmp.getOpcode() == X86ISD::STRICT_FCMPS;
20904 
20905   if (Subtarget.hasCMov() || (!IsCmp && !IsStrictCmp) ||
20906       !Cmp.getOperand(IsStrictCmp ? 1 : 0).getValueType().isFloatingPoint() ||
20907       !Cmp.getOperand(IsStrictCmp ? 2 : 1).getValueType().isFloatingPoint())
20908     return Cmp;
20909 
20910   // The instruction selector will select an FUCOM instruction instead of
20911   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
20912   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
20913   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86any_fcmp ...)), 8))))
20914   SDLoc dl(Cmp);
20915   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
20916   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
20917   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
20918                             DAG.getConstant(8, dl, MVT::i8));
20919   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
20920 
20921   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
20922   assert(Subtarget.hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
20923   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
20924 }
20925 
20926 /// Check if replacement of SQRT with RSQRT should be disabled.
isFsqrtCheap(SDValue Op,SelectionDAG & DAG) const20927 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
20928   EVT VT = Op.getValueType();
20929 
20930   // We never want to use both SQRT and RSQRT instructions for the same input.
20931   if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
20932     return false;
20933 
20934   if (VT.isVector())
20935     return Subtarget.hasFastVectorFSQRT();
20936   return Subtarget.hasFastScalarFSQRT();
20937 }
20938 
20939 /// The minimum architected relative accuracy is 2^-12. We need one
20940 /// Newton-Raphson step to have a good float result (24 bits of precision).
getSqrtEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps,bool & UseOneConstNR,bool Reciprocal) const20941 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
20942                                            SelectionDAG &DAG, int Enabled,
20943                                            int &RefinementSteps,
20944                                            bool &UseOneConstNR,
20945                                            bool Reciprocal) const {
20946   EVT VT = Op.getValueType();
20947 
20948   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
20949   // It is likely not profitable to do this for f64 because a double-precision
20950   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
20951   // instructions: convert to single, rsqrtss, convert back to double, refine
20952   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
20953   // along with FMA, this could be a throughput win.
20954   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
20955   // after legalize types.
20956   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
20957       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
20958       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
20959       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
20960       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
20961     if (RefinementSteps == ReciprocalEstimate::Unspecified)
20962       RefinementSteps = 1;
20963 
20964     UseOneConstNR = false;
20965     // There is no FSQRT for 512-bits, but there is RSQRT14.
20966     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
20967     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
20968   }
20969   return SDValue();
20970 }
20971 
20972 /// The minimum architected relative accuracy is 2^-12. We need one
20973 /// Newton-Raphson step to have a good float result (24 bits of precision).
getRecipEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps) const20974 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
20975                                             int Enabled,
20976                                             int &RefinementSteps) const {
20977   EVT VT = Op.getValueType();
20978 
20979   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
20980   // It is likely not profitable to do this for f64 because a double-precision
20981   // reciprocal estimate with refinement on x86 prior to FMA requires
20982   // 15 instructions: convert to single, rcpss, convert back to double, refine
20983   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
20984   // along with FMA, this could be a throughput win.
20985 
20986   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
20987       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
20988       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
20989       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
20990     // Enable estimate codegen with 1 refinement step for vector division.
20991     // Scalar division estimates are disabled because they break too much
20992     // real-world code. These defaults are intended to match GCC behavior.
20993     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
20994       return SDValue();
20995 
20996     if (RefinementSteps == ReciprocalEstimate::Unspecified)
20997       RefinementSteps = 1;
20998 
20999     // There is no FSQRT for 512-bits, but there is RCP14.
21000     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
21001     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
21002   }
21003   return SDValue();
21004 }
21005 
21006 /// If we have at least two divisions that use the same divisor, convert to
21007 /// multiplication by a reciprocal. This may need to be adjusted for a given
21008 /// CPU if a division's cost is not at least twice the cost of a multiplication.
21009 /// This is because we still need one division to calculate the reciprocal and
21010 /// then we need two multiplies by that reciprocal as replacements for the
21011 /// original divisions.
combineRepeatedFPDivisors() const21012 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
21013   return 2;
21014 }
21015 
21016 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const21017 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
21018                                  SelectionDAG &DAG,
21019                                  SmallVectorImpl<SDNode *> &Created) const {
21020   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
21021   if (isIntDivCheap(N->getValueType(0), Attr))
21022     return SDValue(N,0); // Lower SDIV as SDIV
21023 
21024   assert((Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) &&
21025          "Unexpected divisor!");
21026 
21027   // Only perform this transform if CMOV is supported otherwise the select
21028   // below will become a branch.
21029   if (!Subtarget.hasCMov())
21030     return SDValue();
21031 
21032   // fold (sdiv X, pow2)
21033   EVT VT = N->getValueType(0);
21034   // FIXME: Support i8.
21035   if (VT != MVT::i16 && VT != MVT::i32 &&
21036       !(Subtarget.is64Bit() && VT == MVT::i64))
21037     return SDValue();
21038 
21039   unsigned Lg2 = Divisor.countTrailingZeros();
21040 
21041   // If the divisor is 2 or -2, the default expansion is better.
21042   if (Lg2 == 1)
21043     return SDValue();
21044 
21045   SDLoc DL(N);
21046   SDValue N0 = N->getOperand(0);
21047   SDValue Zero = DAG.getConstant(0, DL, VT);
21048   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
21049   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
21050 
21051   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
21052   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
21053   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
21054   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
21055 
21056   Created.push_back(Cmp.getNode());
21057   Created.push_back(Add.getNode());
21058   Created.push_back(CMov.getNode());
21059 
21060   // Divide by pow2.
21061   SDValue SRA =
21062       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
21063 
21064   // If we're dividing by a positive value, we're done.  Otherwise, we must
21065   // negate the result.
21066   if (Divisor.isNonNegative())
21067     return SRA;
21068 
21069   Created.push_back(SRA.getNode());
21070   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
21071 }
21072 
21073 /// Result of 'and' is compared against zero. Change to a BT node if possible.
21074 /// Returns the BT node and the condition code needed to use it.
LowerAndToBT(SDValue And,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC)21075 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
21076                             const SDLoc &dl, SelectionDAG &DAG,
21077                             SDValue &X86CC) {
21078   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
21079   SDValue Op0 = And.getOperand(0);
21080   SDValue Op1 = And.getOperand(1);
21081   if (Op0.getOpcode() == ISD::TRUNCATE)
21082     Op0 = Op0.getOperand(0);
21083   if (Op1.getOpcode() == ISD::TRUNCATE)
21084     Op1 = Op1.getOperand(0);
21085 
21086   SDValue Src, BitNo;
21087   if (Op1.getOpcode() == ISD::SHL)
21088     std::swap(Op0, Op1);
21089   if (Op0.getOpcode() == ISD::SHL) {
21090     if (isOneConstant(Op0.getOperand(0))) {
21091       // If we looked past a truncate, check that it's only truncating away
21092       // known zeros.
21093       unsigned BitWidth = Op0.getValueSizeInBits();
21094       unsigned AndBitWidth = And.getValueSizeInBits();
21095       if (BitWidth > AndBitWidth) {
21096         KnownBits Known = DAG.computeKnownBits(Op0);
21097         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
21098           return SDValue();
21099       }
21100       Src = Op1;
21101       BitNo = Op0.getOperand(1);
21102     }
21103   } else if (Op1.getOpcode() == ISD::Constant) {
21104     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
21105     uint64_t AndRHSVal = AndRHS->getZExtValue();
21106     SDValue AndLHS = Op0;
21107 
21108     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
21109       Src = AndLHS.getOperand(0);
21110       BitNo = AndLHS.getOperand(1);
21111     } else {
21112       // Use BT if the immediate can't be encoded in a TEST instruction or we
21113       // are optimizing for size and the immedaite won't fit in a byte.
21114       bool OptForSize = DAG.shouldOptForSize();
21115       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
21116           isPowerOf2_64(AndRHSVal)) {
21117         Src = AndLHS;
21118         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
21119                                 Src.getValueType());
21120       }
21121     }
21122   }
21123 
21124   // No patterns found, give up.
21125   if (!Src.getNode())
21126     return SDValue();
21127 
21128   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
21129   // instruction.  Since the shift amount is in-range-or-undefined, we know
21130   // that doing a bittest on the i32 value is ok.  We extend to i32 because
21131   // the encoding for the i16 version is larger than the i32 version.
21132   // Also promote i16 to i32 for performance / code size reason.
21133   if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
21134     Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
21135 
21136   // See if we can use the 32-bit instruction instead of the 64-bit one for a
21137   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
21138   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
21139   // known to be zero.
21140   if (Src.getValueType() == MVT::i64 &&
21141       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
21142     Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
21143 
21144   // If the operand types disagree, extend the shift amount to match.  Since
21145   // BT ignores high bits (like shifts) we can use anyextend.
21146   if (Src.getValueType() != BitNo.getValueType())
21147     BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
21148 
21149   X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
21150                                 dl, MVT::i8);
21151   return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
21152 }
21153 
21154 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
21155 /// CMPs.
translateX86FSETCC(ISD::CondCode SetCCOpcode,SDValue & Op0,SDValue & Op1,bool & IsAlwaysSignaling)21156 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
21157                                    SDValue &Op1, bool &IsAlwaysSignaling) {
21158   unsigned SSECC;
21159   bool Swap = false;
21160 
21161   // SSE Condition code mapping:
21162   //  0 - EQ
21163   //  1 - LT
21164   //  2 - LE
21165   //  3 - UNORD
21166   //  4 - NEQ
21167   //  5 - NLT
21168   //  6 - NLE
21169   //  7 - ORD
21170   switch (SetCCOpcode) {
21171   default: llvm_unreachable("Unexpected SETCC condition");
21172   case ISD::SETOEQ:
21173   case ISD::SETEQ:  SSECC = 0; break;
21174   case ISD::SETOGT:
21175   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
21176   case ISD::SETLT:
21177   case ISD::SETOLT: SSECC = 1; break;
21178   case ISD::SETOGE:
21179   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
21180   case ISD::SETLE:
21181   case ISD::SETOLE: SSECC = 2; break;
21182   case ISD::SETUO:  SSECC = 3; break;
21183   case ISD::SETUNE:
21184   case ISD::SETNE:  SSECC = 4; break;
21185   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
21186   case ISD::SETUGE: SSECC = 5; break;
21187   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
21188   case ISD::SETUGT: SSECC = 6; break;
21189   case ISD::SETO:   SSECC = 7; break;
21190   case ISD::SETUEQ: SSECC = 8; break;
21191   case ISD::SETONE: SSECC = 12; break;
21192   }
21193   if (Swap)
21194     std::swap(Op0, Op1);
21195 
21196   switch (SetCCOpcode) {
21197   default:
21198     IsAlwaysSignaling = true;
21199     break;
21200   case ISD::SETEQ:
21201   case ISD::SETOEQ:
21202   case ISD::SETUEQ:
21203   case ISD::SETNE:
21204   case ISD::SETONE:
21205   case ISD::SETUNE:
21206   case ISD::SETO:
21207   case ISD::SETUO:
21208     IsAlwaysSignaling = false;
21209     break;
21210   }
21211 
21212   return SSECC;
21213 }
21214 
21215 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
21216 /// concatenate the result back.
Lower256IntVSETCC(SDValue Op,SelectionDAG & DAG)21217 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
21218   MVT VT = Op.getSimpleValueType();
21219 
21220   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
21221          "Unsupported value type for operation");
21222 
21223   unsigned NumElems = VT.getVectorNumElements();
21224   SDLoc dl(Op);
21225   SDValue CC = Op.getOperand(2);
21226 
21227   // Extract the LHS vectors
21228   SDValue LHS = Op.getOperand(0);
21229   SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
21230   SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
21231 
21232   // Extract the RHS vectors
21233   SDValue RHS = Op.getOperand(1);
21234   SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
21235   SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
21236 
21237   // Issue the operation on the smaller types and concatenate the result back
21238   MVT EltVT = VT.getVectorElementType();
21239   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
21240   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
21241                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
21242                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
21243 }
21244 
LowerIntVSETCC_AVX512(SDValue Op,SelectionDAG & DAG)21245 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
21246 
21247   SDValue Op0 = Op.getOperand(0);
21248   SDValue Op1 = Op.getOperand(1);
21249   SDValue CC = Op.getOperand(2);
21250   MVT VT = Op.getSimpleValueType();
21251   SDLoc dl(Op);
21252 
21253   assert(VT.getVectorElementType() == MVT::i1 &&
21254          "Cannot set masked compare for this operation");
21255 
21256   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
21257 
21258   // Prefer SETGT over SETLT.
21259   if (SetCCOpcode == ISD::SETLT) {
21260     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
21261     std::swap(Op0, Op1);
21262   }
21263 
21264   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
21265 }
21266 
21267 /// Given a buildvector constant, return a new vector constant with each element
21268 /// incremented or decremented. If incrementing or decrementing would result in
21269 /// unsigned overflow or underflow or this is not a simple vector constant,
21270 /// return an empty value.
incDecVectorConstant(SDValue V,SelectionDAG & DAG,bool IsInc)21271 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
21272   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
21273   if (!BV)
21274     return SDValue();
21275 
21276   MVT VT = V.getSimpleValueType();
21277   MVT EltVT = VT.getVectorElementType();
21278   unsigned NumElts = VT.getVectorNumElements();
21279   SmallVector<SDValue, 8> NewVecC;
21280   SDLoc DL(V);
21281   for (unsigned i = 0; i < NumElts; ++i) {
21282     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
21283     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
21284       return SDValue();
21285 
21286     // Avoid overflow/underflow.
21287     const APInt &EltC = Elt->getAPIntValue();
21288     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isNullValue()))
21289       return SDValue();
21290 
21291     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
21292   }
21293 
21294   return DAG.getBuildVector(VT, DL, NewVecC);
21295 }
21296 
21297 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
21298 /// Op0 u<= Op1:
21299 ///   t = psubus Op0, Op1
21300 ///   pcmpeq t, <0..0>
LowerVSETCCWithSUBUS(SDValue Op0,SDValue Op1,MVT VT,ISD::CondCode Cond,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)21301 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
21302                                     ISD::CondCode Cond, const SDLoc &dl,
21303                                     const X86Subtarget &Subtarget,
21304                                     SelectionDAG &DAG) {
21305   if (!Subtarget.hasSSE2())
21306     return SDValue();
21307 
21308   MVT VET = VT.getVectorElementType();
21309   if (VET != MVT::i8 && VET != MVT::i16)
21310     return SDValue();
21311 
21312   switch (Cond) {
21313   default:
21314     return SDValue();
21315   case ISD::SETULT: {
21316     // If the comparison is against a constant we can turn this into a
21317     // setule.  With psubus, setule does not require a swap.  This is
21318     // beneficial because the constant in the register is no longer
21319     // destructed as the destination so it can be hoisted out of a loop.
21320     // Only do this pre-AVX since vpcmp* is no longer destructive.
21321     if (Subtarget.hasAVX())
21322       return SDValue();
21323     SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
21324     if (!ULEOp1)
21325       return SDValue();
21326     Op1 = ULEOp1;
21327     break;
21328   }
21329   case ISD::SETUGT: {
21330     // If the comparison is against a constant, we can turn this into a setuge.
21331     // This is beneficial because materializing a constant 0 for the PCMPEQ is
21332     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
21333     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
21334     SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
21335     if (!UGEOp1)
21336       return SDValue();
21337     Op1 = Op0;
21338     Op0 = UGEOp1;
21339     break;
21340   }
21341   // Psubus is better than flip-sign because it requires no inversion.
21342   case ISD::SETUGE:
21343     std::swap(Op0, Op1);
21344     break;
21345   case ISD::SETULE:
21346     break;
21347   }
21348 
21349   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
21350   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
21351                      DAG.getConstant(0, dl, VT));
21352 }
21353 
LowerVSETCC(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)21354 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
21355                            SelectionDAG &DAG) {
21356   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
21357                   Op.getOpcode() == ISD::STRICT_FSETCCS;
21358   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
21359   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
21360   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
21361   MVT VT = Op->getSimpleValueType(0);
21362   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
21363   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
21364   SDLoc dl(Op);
21365 
21366   if (isFP) {
21367 #ifndef NDEBUG
21368     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
21369     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
21370 #endif
21371 
21372     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
21373     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21374 
21375     unsigned Opc;
21376     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1) {
21377       assert(VT.getVectorNumElements() <= 16);
21378       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
21379     } else {
21380       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
21381       // The SSE/AVX packed FP comparison nodes are defined with a
21382       // floating-point vector result that matches the operand type. This allows
21383       // them to work with an SSE1 target (integer vector types are not legal).
21384       VT = Op0.getSimpleValueType();
21385     }
21386 
21387     SDValue Cmp;
21388     bool IsAlwaysSignaling;
21389     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
21390     if (!Subtarget.hasAVX()) {
21391       // TODO: We could use following steps to handle a quiet compare with
21392       // signaling encodings.
21393       // 1. Get ordered masks from a quiet ISD::SETO
21394       // 2. Use the masks to mask potential unordered elements in operand A, B
21395       // 3. Get the compare results of masked A, B
21396       // 4. Calculating final result using the mask and result from 3
21397       // But currently, we just fall back to scalar operations.
21398       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
21399         return SDValue();
21400 
21401       // Insert an extra signaling instruction to raise exception.
21402       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
21403         SDValue SignalCmp = DAG.getNode(
21404             Opc, dl, {VT, MVT::Other},
21405             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
21406         // FIXME: It seems we need to update the flags of all new strict nodes.
21407         // Otherwise, mayRaiseFPException in MI will return false due to
21408         // NoFPExcept = false by default. However, I didn't find it in other
21409         // patches.
21410         SignalCmp->setFlags(Op->getFlags());
21411         Chain = SignalCmp.getValue(1);
21412       }
21413 
21414       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
21415       // emit two comparisons and a logic op to tie them together.
21416       if (SSECC >= 8) {
21417         // LLVM predicate is SETUEQ or SETONE.
21418         unsigned CC0, CC1;
21419         unsigned CombineOpc;
21420         if (Cond == ISD::SETUEQ) {
21421           CC0 = 3; // UNORD
21422           CC1 = 0; // EQ
21423           CombineOpc = X86ISD::FOR;
21424         } else {
21425           assert(Cond == ISD::SETONE);
21426           CC0 = 7; // ORD
21427           CC1 = 4; // NEQ
21428           CombineOpc = X86ISD::FAND;
21429         }
21430 
21431         SDValue Cmp0, Cmp1;
21432         if (IsStrict) {
21433           Cmp0 = DAG.getNode(
21434               Opc, dl, {VT, MVT::Other},
21435               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
21436           Cmp1 = DAG.getNode(
21437               Opc, dl, {VT, MVT::Other},
21438               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
21439           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
21440                               Cmp1.getValue(1));
21441         } else {
21442           Cmp0 = DAG.getNode(
21443               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
21444           Cmp1 = DAG.getNode(
21445               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
21446         }
21447         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
21448       } else {
21449         if (IsStrict) {
21450           Cmp = DAG.getNode(
21451               Opc, dl, {VT, MVT::Other},
21452               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
21453           Chain = Cmp.getValue(1);
21454         } else
21455           Cmp = DAG.getNode(
21456               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
21457       }
21458     } else {
21459       // Handle all other FP comparisons here.
21460       if (IsStrict) {
21461         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
21462         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
21463         Cmp = DAG.getNode(
21464             Opc, dl, {VT, MVT::Other},
21465             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
21466         Chain = Cmp.getValue(1);
21467       } else
21468         Cmp = DAG.getNode(
21469             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
21470     }
21471 
21472     // If this is SSE/AVX CMPP, bitcast the result back to integer to match the
21473     // result type of SETCC. The bitcast is expected to be optimized away
21474     // during combining/isel.
21475     Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
21476 
21477     if (IsStrict)
21478       return DAG.getMergeValues({Cmp, Chain}, dl);
21479 
21480     return Cmp;
21481   }
21482 
21483   assert(!IsStrict && "Strict SETCC only handles FP operands.");
21484 
21485   MVT VTOp0 = Op0.getSimpleValueType();
21486   (void)VTOp0;
21487   assert(VTOp0 == Op1.getSimpleValueType() &&
21488          "Expected operands with same type!");
21489   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
21490          "Invalid number of packed elements for source and destination!");
21491 
21492   // The non-AVX512 code below works under the assumption that source and
21493   // destination types are the same.
21494   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
21495          "Value types for source and destination must be the same!");
21496 
21497   // The result is boolean, but operands are int/float
21498   if (VT.getVectorElementType() == MVT::i1) {
21499     // In AVX-512 architecture setcc returns mask with i1 elements,
21500     // But there is no compare instruction for i8 and i16 elements in KNL.
21501     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
21502            "Unexpected operand type");
21503     return LowerIntVSETCC_AVX512(Op, DAG);
21504   }
21505 
21506   // Lower using XOP integer comparisons.
21507   if (VT.is128BitVector() && Subtarget.hasXOP()) {
21508     // Translate compare code to XOP PCOM compare mode.
21509     unsigned CmpMode = 0;
21510     switch (Cond) {
21511     default: llvm_unreachable("Unexpected SETCC condition");
21512     case ISD::SETULT:
21513     case ISD::SETLT: CmpMode = 0x00; break;
21514     case ISD::SETULE:
21515     case ISD::SETLE: CmpMode = 0x01; break;
21516     case ISD::SETUGT:
21517     case ISD::SETGT: CmpMode = 0x02; break;
21518     case ISD::SETUGE:
21519     case ISD::SETGE: CmpMode = 0x03; break;
21520     case ISD::SETEQ: CmpMode = 0x04; break;
21521     case ISD::SETNE: CmpMode = 0x05; break;
21522     }
21523 
21524     // Are we comparing unsigned or signed integers?
21525     unsigned Opc =
21526         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
21527 
21528     return DAG.getNode(Opc, dl, VT, Op0, Op1,
21529                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
21530   }
21531 
21532   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
21533   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
21534   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
21535     SDValue BC0 = peekThroughBitcasts(Op0);
21536     if (BC0.getOpcode() == ISD::AND) {
21537       APInt UndefElts;
21538       SmallVector<APInt, 64> EltBits;
21539       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
21540                                         VT.getScalarSizeInBits(), UndefElts,
21541                                         EltBits, false, false)) {
21542         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
21543           Cond = ISD::SETEQ;
21544           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
21545         }
21546       }
21547     }
21548   }
21549 
21550   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
21551   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
21552       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
21553     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
21554     if (C1 && C1->getAPIntValue().isPowerOf2()) {
21555       unsigned BitWidth = VT.getScalarSizeInBits();
21556       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
21557 
21558       SDValue Result = Op0.getOperand(0);
21559       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
21560                            DAG.getConstant(ShiftAmt, dl, VT));
21561       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
21562                            DAG.getConstant(BitWidth - 1, dl, VT));
21563       return Result;
21564     }
21565   }
21566 
21567   // Break 256-bit integer vector compare into smaller ones.
21568   if (VT.is256BitVector() && !Subtarget.hasInt256())
21569     return Lower256IntVSETCC(Op, DAG);
21570 
21571   // If this is a SETNE against the signed minimum value, change it to SETGT.
21572   // If this is a SETNE against the signed maximum value, change it to SETLT.
21573   // which will be swapped to SETGT.
21574   // Otherwise we use PCMPEQ+invert.
21575   APInt ConstValue;
21576   if (Cond == ISD::SETNE &&
21577       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
21578     if (ConstValue.isMinSignedValue())
21579       Cond = ISD::SETGT;
21580     else if (ConstValue.isMaxSignedValue())
21581       Cond = ISD::SETLT;
21582   }
21583 
21584   // If both operands are known non-negative, then an unsigned compare is the
21585   // same as a signed compare and there's no need to flip signbits.
21586   // TODO: We could check for more general simplifications here since we're
21587   // computing known bits.
21588   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
21589                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
21590 
21591   // Special case: Use min/max operations for unsigned compares.
21592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21593   if (ISD::isUnsignedIntSetCC(Cond) &&
21594       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
21595       TLI.isOperationLegal(ISD::UMIN, VT)) {
21596     // If we have a constant operand, increment/decrement it and change the
21597     // condition to avoid an invert.
21598     if (Cond == ISD::SETUGT) {
21599       // X > C --> X >= (C+1) --> X == umax(X, C+1)
21600       if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
21601         Op1 = UGTOp1;
21602         Cond = ISD::SETUGE;
21603       }
21604     }
21605     if (Cond == ISD::SETULT) {
21606       // X < C --> X <= (C-1) --> X == umin(X, C-1)
21607       if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
21608         Op1 = ULTOp1;
21609         Cond = ISD::SETULE;
21610       }
21611     }
21612     bool Invert = false;
21613     unsigned Opc;
21614     switch (Cond) {
21615     default: llvm_unreachable("Unexpected condition code");
21616     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
21617     case ISD::SETULE: Opc = ISD::UMIN; break;
21618     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
21619     case ISD::SETUGE: Opc = ISD::UMAX; break;
21620     }
21621 
21622     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
21623     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
21624 
21625     // If the logical-not of the result is required, perform that now.
21626     if (Invert)
21627       Result = DAG.getNOT(dl, Result, VT);
21628 
21629     return Result;
21630   }
21631 
21632   // Try to use SUBUS and PCMPEQ.
21633   if (SDValue V = LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
21634     return V;
21635 
21636   // We are handling one of the integer comparisons here. Since SSE only has
21637   // GT and EQ comparisons for integer, swapping operands and multiple
21638   // operations may be required for some comparisons.
21639   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
21640                                                             : X86ISD::PCMPGT;
21641   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
21642               Cond == ISD::SETGE || Cond == ISD::SETUGE;
21643   bool Invert = Cond == ISD::SETNE ||
21644                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
21645 
21646   if (Swap)
21647     std::swap(Op0, Op1);
21648 
21649   // Check that the operation in question is available (most are plain SSE2,
21650   // but PCMPGTQ and PCMPEQQ have different requirements).
21651   if (VT == MVT::v2i64) {
21652     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
21653       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
21654 
21655       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
21656       // the odd elements over the even elements.
21657       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
21658         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
21659         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
21660 
21661         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
21662         static const int MaskHi[] = { 1, 1, 3, 3 };
21663         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
21664 
21665         return DAG.getBitcast(VT, Result);
21666       }
21667 
21668       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
21669         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
21670         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
21671 
21672         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
21673         static const int MaskHi[] = { 1, 1, 3, 3 };
21674         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
21675 
21676         return DAG.getBitcast(VT, Result);
21677       }
21678 
21679       // Since SSE has no unsigned integer comparisons, we need to flip the sign
21680       // bits of the inputs before performing those operations. The lower
21681       // compare is always unsigned.
21682       SDValue SB;
21683       if (FlipSigns) {
21684         SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
21685       } else {
21686         SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
21687       }
21688       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
21689       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
21690 
21691       // Cast everything to the right type.
21692       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
21693       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
21694 
21695       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
21696       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
21697       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
21698 
21699       // Create masks for only the low parts/high parts of the 64 bit integers.
21700       static const int MaskHi[] = { 1, 1, 3, 3 };
21701       static const int MaskLo[] = { 0, 0, 2, 2 };
21702       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
21703       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
21704       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
21705 
21706       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
21707       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
21708 
21709       if (Invert)
21710         Result = DAG.getNOT(dl, Result, MVT::v4i32);
21711 
21712       return DAG.getBitcast(VT, Result);
21713     }
21714 
21715     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
21716       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
21717       // pcmpeqd + pshufd + pand.
21718       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
21719 
21720       // First cast everything to the right type.
21721       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
21722       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
21723 
21724       // Do the compare.
21725       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
21726 
21727       // Make sure the lower and upper halves are both all-ones.
21728       static const int Mask[] = { 1, 0, 3, 2 };
21729       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
21730       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
21731 
21732       if (Invert)
21733         Result = DAG.getNOT(dl, Result, MVT::v4i32);
21734 
21735       return DAG.getBitcast(VT, Result);
21736     }
21737   }
21738 
21739   // Since SSE has no unsigned integer comparisons, we need to flip the sign
21740   // bits of the inputs before performing those operations.
21741   if (FlipSigns) {
21742     MVT EltVT = VT.getVectorElementType();
21743     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
21744                                  VT);
21745     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
21746     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
21747   }
21748 
21749   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
21750 
21751   // If the logical-not of the result is required, perform that now.
21752   if (Invert)
21753     Result = DAG.getNOT(dl, Result, VT);
21754 
21755   return Result;
21756 }
21757 
21758 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
EmitAVX512Test(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue & X86CC)21759 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
21760                               const SDLoc &dl, SelectionDAG &DAG,
21761                               const X86Subtarget &Subtarget,
21762                               SDValue &X86CC) {
21763   // Only support equality comparisons.
21764   if (CC != ISD::SETEQ && CC != ISD::SETNE)
21765     return SDValue();
21766 
21767   // Must be a bitcast from vXi1.
21768   if (Op0.getOpcode() != ISD::BITCAST)
21769     return SDValue();
21770 
21771   Op0 = Op0.getOperand(0);
21772   MVT VT = Op0.getSimpleValueType();
21773   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
21774       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
21775       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
21776     return SDValue();
21777 
21778   X86::CondCode X86Cond;
21779   if (isNullConstant(Op1)) {
21780     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
21781   } else if (isAllOnesConstant(Op1)) {
21782     // C flag is set for all ones.
21783     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
21784   } else
21785     return SDValue();
21786 
21787   // If the input is an AND, we can combine it's operands into the KTEST.
21788   bool KTestable = false;
21789   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
21790     KTestable = true;
21791   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
21792     KTestable = true;
21793   if (!isNullConstant(Op1))
21794     KTestable = false;
21795   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
21796     SDValue LHS = Op0.getOperand(0);
21797     SDValue RHS = Op0.getOperand(1);
21798     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
21799     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
21800   }
21801 
21802   // If the input is an OR, we can combine it's operands into the KORTEST.
21803   SDValue LHS = Op0;
21804   SDValue RHS = Op0;
21805   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
21806     LHS = Op0.getOperand(0);
21807     RHS = Op0.getOperand(1);
21808   }
21809 
21810   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
21811   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
21812 }
21813 
21814 /// Emit flags for the given setcc condition and operands. Also returns the
21815 /// corresponding X86 condition code constant in X86CC.
emitFlagsForSetcc(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC,SDValue & Chain,bool IsSignaling) const21816 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
21817                                              ISD::CondCode CC, const SDLoc &dl,
21818                                              SelectionDAG &DAG, SDValue &X86CC,
21819                                              SDValue &Chain,
21820                                              bool IsSignaling) const {
21821   // Optimize to BT if possible.
21822   // Lower (X & (1 << N)) == 0 to BT(X, N).
21823   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
21824   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
21825   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
21826       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
21827     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
21828       return BT;
21829   }
21830 
21831   // Try to use PTEST for a tree ORs equality compared with 0.
21832   // TODO: We could do AND tree with all 1s as well by using the C flag.
21833   if (Op0.getOpcode() == ISD::OR && isNullConstant(Op1) &&
21834       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
21835     if (SDValue PTEST = LowerVectorAllZeroTest(Op0, CC, Subtarget, DAG, X86CC))
21836       return PTEST;
21837   }
21838 
21839   // Try to lower using KORTEST or KTEST.
21840   if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
21841     return Test;
21842 
21843   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
21844   // these.
21845   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
21846       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
21847     // If the input is a setcc, then reuse the input setcc or use a new one with
21848     // the inverted condition.
21849     if (Op0.getOpcode() == X86ISD::SETCC) {
21850       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
21851 
21852       X86CC = Op0.getOperand(0);
21853       if (Invert) {
21854         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
21855         CCode = X86::GetOppositeBranchCondition(CCode);
21856         X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
21857       }
21858 
21859       return Op0.getOperand(1);
21860     }
21861   }
21862 
21863   // Try to use the carry flag from the add in place of an separate CMP for:
21864   // (seteq (add X, -1), -1). Similar for setne.
21865   if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
21866       Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
21867     if (isProfitableToUseFlagOp(Op0)) {
21868       SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
21869 
21870       SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
21871                                 Op0.getOperand(1));
21872       DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
21873       X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
21874       X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
21875       return SDValue(New.getNode(), 1);
21876     }
21877   }
21878 
21879   bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
21880   X86::CondCode CondCode = TranslateX86CC(CC, dl, IsFP, Op0, Op1, DAG);
21881   if (CondCode == X86::COND_INVALID)
21882     return SDValue();
21883 
21884   std::pair<SDValue, SDValue> Tmp =
21885       EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget, Chain, IsSignaling);
21886   SDValue EFLAGS = Tmp.first;
21887   if (Chain)
21888     Chain = Tmp.second;
21889   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
21890   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
21891   return EFLAGS;
21892 }
21893 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const21894 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
21895 
21896   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
21897                   Op.getOpcode() == ISD::STRICT_FSETCCS;
21898   MVT VT = Op->getSimpleValueType(0);
21899 
21900   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
21901 
21902   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
21903   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21904   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
21905   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
21906   SDLoc dl(Op);
21907   ISD::CondCode CC =
21908       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
21909 
21910   // Handle f128 first, since one possible outcome is a normal integer
21911   // comparison which gets handled by emitFlagsForSetcc.
21912   if (Op0.getValueType() == MVT::f128) {
21913     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
21914                         Op.getOpcode() == ISD::STRICT_FSETCCS);
21915 
21916     // If softenSetCCOperands returned a scalar, use it.
21917     if (!Op1.getNode()) {
21918       assert(Op0.getValueType() == Op.getValueType() &&
21919              "Unexpected setcc expansion!");
21920       if (IsStrict)
21921         return DAG.getMergeValues({Op0, Chain}, dl);
21922       return Op0;
21923     }
21924   }
21925 
21926   SDValue X86CC;
21927   SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC, Chain,
21928                                      Op.getOpcode() == ISD::STRICT_FSETCCS);
21929   if (!EFLAGS)
21930     return SDValue();
21931 
21932   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
21933 
21934   if (IsStrict)
21935     return DAG.getMergeValues({Res, Chain}, dl);
21936 
21937   return Res;
21938 }
21939 
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG) const21940 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
21941   SDValue LHS = Op.getOperand(0);
21942   SDValue RHS = Op.getOperand(1);
21943   SDValue Carry = Op.getOperand(2);
21944   SDValue Cond = Op.getOperand(3);
21945   SDLoc DL(Op);
21946 
21947   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
21948   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
21949 
21950   // Recreate the carry if needed.
21951   EVT CarryVT = Carry.getValueType();
21952   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
21953   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
21954                       Carry, DAG.getConstant(NegOne, DL, CarryVT));
21955 
21956   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
21957   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
21958   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
21959 }
21960 
21961 // This function returns three things: the arithmetic computation itself
21962 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
21963 // flag and the condition code define the case in which the arithmetic
21964 // computation overflows.
21965 static std::pair<SDValue, SDValue>
getX86XALUOOp(X86::CondCode & Cond,SDValue Op,SelectionDAG & DAG)21966 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
21967   assert(Op.getResNo() == 0 && "Unexpected result number!");
21968   SDValue Value, Overflow;
21969   SDValue LHS = Op.getOperand(0);
21970   SDValue RHS = Op.getOperand(1);
21971   unsigned BaseOp = 0;
21972   SDLoc DL(Op);
21973   switch (Op.getOpcode()) {
21974   default: llvm_unreachable("Unknown ovf instruction!");
21975   case ISD::SADDO:
21976     BaseOp = X86ISD::ADD;
21977     Cond = X86::COND_O;
21978     break;
21979   case ISD::UADDO:
21980     BaseOp = X86ISD::ADD;
21981     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
21982     break;
21983   case ISD::SSUBO:
21984     BaseOp = X86ISD::SUB;
21985     Cond = X86::COND_O;
21986     break;
21987   case ISD::USUBO:
21988     BaseOp = X86ISD::SUB;
21989     Cond = X86::COND_B;
21990     break;
21991   case ISD::SMULO:
21992     BaseOp = X86ISD::SMUL;
21993     Cond = X86::COND_O;
21994     break;
21995   case ISD::UMULO:
21996     BaseOp = X86ISD::UMUL;
21997     Cond = X86::COND_O;
21998     break;
21999   }
22000 
22001   if (BaseOp) {
22002     // Also sets EFLAGS.
22003     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22004     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
22005     Overflow = Value.getValue(1);
22006   }
22007 
22008   return std::make_pair(Value, Overflow);
22009 }
22010 
LowerXALUO(SDValue Op,SelectionDAG & DAG)22011 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
22012   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
22013   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
22014   // looks for this combo and may remove the "setcc" instruction if the "setcc"
22015   // has only one use.
22016   SDLoc DL(Op);
22017   X86::CondCode Cond;
22018   SDValue Value, Overflow;
22019   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
22020 
22021   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
22022   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
22023   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
22024 }
22025 
22026 /// Return true if opcode is a X86 logical comparison.
isX86LogicalCmp(SDValue Op)22027 static bool isX86LogicalCmp(SDValue Op) {
22028   unsigned Opc = Op.getOpcode();
22029   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
22030       Opc == X86ISD::SAHF)
22031     return true;
22032   if (Op.getResNo() == 1 &&
22033       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
22034        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
22035        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
22036     return true;
22037 
22038   return false;
22039 }
22040 
isTruncWithZeroHighBitsInput(SDValue V,SelectionDAG & DAG)22041 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
22042   if (V.getOpcode() != ISD::TRUNCATE)
22043     return false;
22044 
22045   SDValue VOp0 = V.getOperand(0);
22046   unsigned InBits = VOp0.getValueSizeInBits();
22047   unsigned Bits = V.getValueSizeInBits();
22048   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
22049 }
22050 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const22051 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
22052   bool AddTest = true;
22053   SDValue Cond  = Op.getOperand(0);
22054   SDValue Op1 = Op.getOperand(1);
22055   SDValue Op2 = Op.getOperand(2);
22056   SDLoc DL(Op);
22057   MVT VT = Op1.getSimpleValueType();
22058   SDValue CC;
22059 
22060   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
22061   // are available or VBLENDV if AVX is available.
22062   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
22063   if (Cond.getOpcode() == ISD::SETCC &&
22064       ((Subtarget.hasSSE2() && VT == MVT::f64) ||
22065        (Subtarget.hasSSE1() && VT == MVT::f32)) &&
22066       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
22067     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
22068     bool IsAlwaysSignaling;
22069     unsigned SSECC =
22070         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
22071                            CondOp0, CondOp1, IsAlwaysSignaling);
22072 
22073     if (Subtarget.hasAVX512()) {
22074       SDValue Cmp =
22075           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
22076                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
22077       assert(!VT.isVector() && "Not a scalar type?");
22078       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
22079     }
22080 
22081     if (SSECC < 8 || Subtarget.hasAVX()) {
22082       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
22083                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
22084 
22085       // If we have AVX, we can use a variable vector select (VBLENDV) instead
22086       // of 3 logic instructions for size savings and potentially speed.
22087       // Unfortunately, there is no scalar form of VBLENDV.
22088 
22089       // If either operand is a +0.0 constant, don't try this. We can expect to
22090       // optimize away at least one of the logic instructions later in that
22091       // case, so that sequence would be faster than a variable blend.
22092 
22093       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
22094       // uses XMM0 as the selection register. That may need just as many
22095       // instructions as the AND/ANDN/OR sequence due to register moves, so
22096       // don't bother.
22097       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
22098           !isNullFPConstant(Op2)) {
22099         // Convert to vectors, do a VSELECT, and convert back to scalar.
22100         // All of the conversions should be optimized away.
22101         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
22102         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
22103         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
22104         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
22105 
22106         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
22107         VCmp = DAG.getBitcast(VCmpVT, VCmp);
22108 
22109         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
22110 
22111         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
22112                            VSel, DAG.getIntPtrConstant(0, DL));
22113       }
22114       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
22115       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
22116       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
22117     }
22118   }
22119 
22120   // AVX512 fallback is to lower selects of scalar floats to masked moves.
22121   if ((VT == MVT::f64 || VT == MVT::f32) && Subtarget.hasAVX512()) {
22122     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
22123     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
22124   }
22125 
22126   // For v64i1 without 64-bit support we need to split and rejoin.
22127   if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
22128     assert(Subtarget.hasBWI() && "Expected BWI to be legal");
22129     SDValue Op1Lo = extractSubVector(Op1, 0, DAG, DL, 32);
22130     SDValue Op2Lo = extractSubVector(Op2, 0, DAG, DL, 32);
22131     SDValue Op1Hi = extractSubVector(Op1, 32, DAG, DL, 32);
22132     SDValue Op2Hi = extractSubVector(Op2, 32, DAG, DL, 32);
22133     SDValue Lo = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Lo, Op2Lo);
22134     SDValue Hi = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Hi, Op2Hi);
22135     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
22136   }
22137 
22138   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
22139     SDValue Op1Scalar;
22140     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
22141       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
22142     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
22143       Op1Scalar = Op1.getOperand(0);
22144     SDValue Op2Scalar;
22145     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
22146       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
22147     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
22148       Op2Scalar = Op2.getOperand(0);
22149     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
22150       SDValue newSelect = DAG.getSelect(DL, Op1Scalar.getValueType(), Cond,
22151                                         Op1Scalar, Op2Scalar);
22152       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
22153         return DAG.getBitcast(VT, newSelect);
22154       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
22155       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
22156                          DAG.getIntPtrConstant(0, DL));
22157     }
22158   }
22159 
22160   if (Cond.getOpcode() == ISD::SETCC) {
22161     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
22162       Cond = NewCond;
22163       // If the condition was updated, it's possible that the operands of the
22164       // select were also updated (for example, EmitTest has a RAUW). Refresh
22165       // the local references to the select operands in case they got stale.
22166       Op1 = Op.getOperand(1);
22167       Op2 = Op.getOperand(2);
22168     }
22169   }
22170 
22171   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
22172   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
22173   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
22174   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
22175   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
22176   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
22177   if (Cond.getOpcode() == X86ISD::SETCC &&
22178       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
22179       isNullConstant(Cond.getOperand(1).getOperand(1))) {
22180     SDValue Cmp = Cond.getOperand(1);
22181     unsigned CondCode = Cond.getConstantOperandVal(0);
22182 
22183     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
22184         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
22185       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
22186       SDValue CmpOp0 = Cmp.getOperand(0);
22187 
22188       // Apply further optimizations for special cases
22189       // (select (x != 0), -1, 0) -> neg & sbb
22190       // (select (x == 0), 0, -1) -> neg & sbb
22191       if (isNullConstant(Y) &&
22192           (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
22193         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
22194         SDValue CmpZero = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Zero, CmpOp0);
22195         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22196         Zero = DAG.getConstant(0, DL, Op.getValueType());
22197         return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, CmpZero);
22198       }
22199 
22200       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22201                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
22202       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
22203 
22204       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22205       SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
22206       SDValue Res =   // Res = 0 or -1.
22207         DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp);
22208 
22209       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
22210         Res = DAG.getNOT(DL, Res, Res.getValueType());
22211 
22212       if (!isNullConstant(Op2))
22213         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
22214       return Res;
22215     } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
22216                Cmp.getOperand(0).getOpcode() == ISD::AND &&
22217                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
22218       SDValue CmpOp0 = Cmp.getOperand(0);
22219       SDValue Src1, Src2;
22220       // true if Op2 is XOR or OR operator and one of its operands
22221       // is equal to Op1
22222       // ( a , a op b) || ( b , a op b)
22223       auto isOrXorPattern = [&]() {
22224         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
22225             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
22226           Src1 =
22227               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
22228           Src2 = Op1;
22229           return true;
22230         }
22231         return false;
22232       };
22233 
22234       if (isOrXorPattern()) {
22235         SDValue Neg;
22236         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
22237         // we need mask of all zeros or ones with same size of the other
22238         // operands.
22239         if (CmpSz > VT.getSizeInBits())
22240           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
22241         else if (CmpSz < VT.getSizeInBits())
22242           Neg = DAG.getNode(ISD::AND, DL, VT,
22243               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
22244               DAG.getConstant(1, DL, VT));
22245         else
22246           Neg = CmpOp0;
22247         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
22248                                    Neg); // -(and (x, 0x1))
22249         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
22250         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
22251       }
22252     }
22253   }
22254 
22255   // Look past (and (setcc_carry (cmp ...)), 1).
22256   if (Cond.getOpcode() == ISD::AND &&
22257       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
22258       isOneConstant(Cond.getOperand(1)))
22259     Cond = Cond.getOperand(0);
22260 
22261   // If condition flag is set by a X86ISD::CMP, then use it as the condition
22262   // setting operand in place of the X86ISD::SETCC.
22263   unsigned CondOpcode = Cond.getOpcode();
22264   if (CondOpcode == X86ISD::SETCC ||
22265       CondOpcode == X86ISD::SETCC_CARRY) {
22266     CC = Cond.getOperand(0);
22267 
22268     SDValue Cmp = Cond.getOperand(1);
22269     bool IllegalFPCMov = false;
22270     if (VT.isFloatingPoint() && !VT.isVector() &&
22271         !isScalarFPTypeInSSEReg(VT))  // FPStack?
22272       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
22273 
22274     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
22275         Cmp.getOpcode() == X86ISD::BT) { // FIXME
22276       Cond = Cmp;
22277       AddTest = false;
22278     }
22279   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
22280              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
22281              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
22282     SDValue Value;
22283     X86::CondCode X86Cond;
22284     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
22285 
22286     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
22287     AddTest = false;
22288   }
22289 
22290   if (AddTest) {
22291     // Look past the truncate if the high bits are known zero.
22292     if (isTruncWithZeroHighBitsInput(Cond, DAG))
22293       Cond = Cond.getOperand(0);
22294 
22295     // We know the result of AND is compared against zero. Try to match
22296     // it to BT.
22297     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
22298       SDValue BTCC;
22299       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
22300         CC = BTCC;
22301         Cond = BT;
22302         AddTest = false;
22303       }
22304     }
22305   }
22306 
22307   if (AddTest) {
22308     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
22309     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
22310   }
22311 
22312   // a <  b ? -1 :  0 -> RES = ~setcc_carry
22313   // a <  b ?  0 : -1 -> RES = setcc_carry
22314   // a >= b ? -1 :  0 -> RES = setcc_carry
22315   // a >= b ?  0 : -1 -> RES = ~setcc_carry
22316   if (Cond.getOpcode() == X86ISD::SUB) {
22317     Cond = ConvertCmpIfNecessary(Cond, DAG);
22318     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
22319 
22320     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
22321         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
22322         (isNullConstant(Op1) || isNullConstant(Op2))) {
22323       SDValue Res =
22324           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
22325                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
22326       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
22327         return DAG.getNOT(DL, Res, Res.getValueType());
22328       return Res;
22329     }
22330   }
22331 
22332   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
22333   // widen the cmov and push the truncate through. This avoids introducing a new
22334   // branch during isel and doesn't add any extensions.
22335   if (Op.getValueType() == MVT::i8 &&
22336       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
22337     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
22338     if (T1.getValueType() == T2.getValueType() &&
22339         // Blacklist CopyFromReg to avoid partial register stalls.
22340         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
22341       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
22342                                  CC, Cond);
22343       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
22344     }
22345   }
22346 
22347   // Or finally, promote i8 cmovs if we have CMOV,
22348   //                 or i16 cmovs if it won't prevent folding a load.
22349   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
22350   //        legal, but EmitLoweredSelect() can not deal with these extensions
22351   //        being inserted between two CMOV's. (in i16 case too TBN)
22352   //        https://bugs.llvm.org/show_bug.cgi?id=40974
22353   if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
22354       (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) &&
22355        !MayFoldLoad(Op2))) {
22356     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
22357     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
22358     SDValue Ops[] = { Op2, Op1, CC, Cond };
22359     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
22360     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
22361   }
22362 
22363   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
22364   // condition is true.
22365   SDValue Ops[] = { Op2, Op1, CC, Cond };
22366   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
22367 }
22368 
LowerSIGN_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22369 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
22370                                      const X86Subtarget &Subtarget,
22371                                      SelectionDAG &DAG) {
22372   MVT VT = Op->getSimpleValueType(0);
22373   SDValue In = Op->getOperand(0);
22374   MVT InVT = In.getSimpleValueType();
22375   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
22376   MVT VTElt = VT.getVectorElementType();
22377   SDLoc dl(Op);
22378 
22379   unsigned NumElts = VT.getVectorNumElements();
22380 
22381   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
22382   MVT ExtVT = VT;
22383   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
22384     // If v16i32 is to be avoided, we'll need to split and concatenate.
22385     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
22386       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
22387 
22388     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
22389   }
22390 
22391   // Widen to 512-bits if VLX is not supported.
22392   MVT WideVT = ExtVT;
22393   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
22394     NumElts *= 512 / ExtVT.getSizeInBits();
22395     InVT = MVT::getVectorVT(MVT::i1, NumElts);
22396     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
22397                      In, DAG.getIntPtrConstant(0, dl));
22398     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
22399   }
22400 
22401   SDValue V;
22402   MVT WideEltVT = WideVT.getVectorElementType();
22403   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
22404       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
22405     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
22406   } else {
22407     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
22408     SDValue Zero = DAG.getConstant(0, dl, WideVT);
22409     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
22410   }
22411 
22412   // Truncate if we had to extend i16/i8 above.
22413   if (VT != ExtVT) {
22414     WideVT = MVT::getVectorVT(VTElt, NumElts);
22415     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
22416   }
22417 
22418   // Extract back to 128/256-bit if we widened.
22419   if (WideVT != VT)
22420     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
22421                     DAG.getIntPtrConstant(0, dl));
22422 
22423   return V;
22424 }
22425 
LowerANY_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22426 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
22427                                SelectionDAG &DAG) {
22428   SDValue In = Op->getOperand(0);
22429   MVT InVT = In.getSimpleValueType();
22430 
22431   if (InVT.getVectorElementType() == MVT::i1)
22432     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
22433 
22434   assert(Subtarget.hasAVX() && "Expected AVX support");
22435   return LowerAVXExtend(Op, DAG, Subtarget);
22436 }
22437 
22438 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
22439 // For sign extend this needs to handle all vector sizes and SSE4.1 and
22440 // non-SSE4.1 targets. For zero extend this should only handle inputs of
22441 // MVT::v64i8 when BWI is not supported, but AVX512 is.
LowerEXTEND_VECTOR_INREG(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22442 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
22443                                         const X86Subtarget &Subtarget,
22444                                         SelectionDAG &DAG) {
22445   SDValue In = Op->getOperand(0);
22446   MVT VT = Op->getSimpleValueType(0);
22447   MVT InVT = In.getSimpleValueType();
22448 
22449   MVT SVT = VT.getVectorElementType();
22450   MVT InSVT = InVT.getVectorElementType();
22451   assert(SVT.getSizeInBits() > InSVT.getSizeInBits());
22452 
22453   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
22454     return SDValue();
22455   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
22456     return SDValue();
22457   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
22458       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
22459       !(VT.is512BitVector() && Subtarget.hasAVX512()))
22460     return SDValue();
22461 
22462   SDLoc dl(Op);
22463   unsigned Opc = Op.getOpcode();
22464   unsigned NumElts = VT.getVectorNumElements();
22465 
22466   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
22467   // For 512-bit vectors, we need 128-bits or 256-bits.
22468   if (InVT.getSizeInBits() > 128) {
22469     // Input needs to be at least the same number of elements as output, and
22470     // at least 128-bits.
22471     int InSize = InSVT.getSizeInBits() * NumElts;
22472     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
22473     InVT = In.getSimpleValueType();
22474   }
22475 
22476   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
22477   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
22478   // need to be handled here for 256/512-bit results.
22479   if (Subtarget.hasInt256()) {
22480     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
22481 
22482     if (InVT.getVectorNumElements() != NumElts)
22483       return DAG.getNode(Op.getOpcode(), dl, VT, In);
22484 
22485     // FIXME: Apparently we create inreg operations that could be regular
22486     // extends.
22487     unsigned ExtOpc =
22488         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
22489                                              : ISD::ZERO_EXTEND;
22490     return DAG.getNode(ExtOpc, dl, VT, In);
22491   }
22492 
22493   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
22494   if (Subtarget.hasAVX()) {
22495     assert(VT.is256BitVector() && "256-bit vector expected");
22496     MVT HalfVT = VT.getHalfNumVectorElementsVT();
22497     int HalfNumElts = HalfVT.getVectorNumElements();
22498 
22499     unsigned NumSrcElts = InVT.getVectorNumElements();
22500     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
22501     for (int i = 0; i != HalfNumElts; ++i)
22502       HiMask[i] = HalfNumElts + i;
22503 
22504     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
22505     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
22506     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
22507     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
22508   }
22509 
22510   // We should only get here for sign extend.
22511   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
22512   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
22513 
22514   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
22515   SDValue Curr = In;
22516   SDValue SignExt = Curr;
22517 
22518   // As SRAI is only available on i16/i32 types, we expand only up to i32
22519   // and handle i64 separately.
22520   if (InVT != MVT::v4i32) {
22521     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
22522 
22523     unsigned DestWidth = DestVT.getScalarSizeInBits();
22524     unsigned Scale = DestWidth / InSVT.getSizeInBits();
22525 
22526     unsigned InNumElts = InVT.getVectorNumElements();
22527     unsigned DestElts = DestVT.getVectorNumElements();
22528 
22529     // Build a shuffle mask that takes each input element and places it in the
22530     // MSBs of the new element size.
22531     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
22532     for (unsigned i = 0; i != DestElts; ++i)
22533       Mask[i * Scale + (Scale - 1)] = i;
22534 
22535     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
22536     Curr = DAG.getBitcast(DestVT, Curr);
22537 
22538     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
22539     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
22540                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
22541   }
22542 
22543   if (VT == MVT::v2i64) {
22544     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
22545     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
22546     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
22547     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
22548     SignExt = DAG.getBitcast(VT, SignExt);
22549   }
22550 
22551   return SignExt;
22552 }
22553 
LowerSIGN_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22554 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
22555                                 SelectionDAG &DAG) {
22556   MVT VT = Op->getSimpleValueType(0);
22557   SDValue In = Op->getOperand(0);
22558   MVT InVT = In.getSimpleValueType();
22559   SDLoc dl(Op);
22560 
22561   if (InVT.getVectorElementType() == MVT::i1)
22562     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
22563 
22564   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
22565   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
22566          "Expected same number of elements");
22567   assert((VT.getVectorElementType() == MVT::i16 ||
22568           VT.getVectorElementType() == MVT::i32 ||
22569           VT.getVectorElementType() == MVT::i64) &&
22570          "Unexpected element type");
22571   assert((InVT.getVectorElementType() == MVT::i8 ||
22572           InVT.getVectorElementType() == MVT::i16 ||
22573           InVT.getVectorElementType() == MVT::i32) &&
22574          "Unexpected element type");
22575 
22576   // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
22577   if (InVT == MVT::v8i8) {
22578     if (VT != MVT::v8i64)
22579       return SDValue();
22580 
22581     In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
22582                      MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
22583     return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, VT, In);
22584   }
22585 
22586   if (Subtarget.hasInt256())
22587     return Op;
22588 
22589   // Optimize vectors in AVX mode
22590   // Sign extend  v8i16 to v8i32 and
22591   //              v4i32 to v4i64
22592   //
22593   // Divide input vector into two parts
22594   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
22595   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
22596   // concat the vectors to original VT
22597   MVT HalfVT = VT.getHalfNumVectorElementsVT();
22598   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
22599 
22600   unsigned NumElems = InVT.getVectorNumElements();
22601   SmallVector<int,8> ShufMask(NumElems, -1);
22602   for (unsigned i = 0; i != NumElems/2; ++i)
22603     ShufMask[i] = i + NumElems/2;
22604 
22605   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
22606   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
22607 
22608   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
22609 }
22610 
22611 /// Change a vector store into a pair of half-size vector stores.
splitVectorStore(StoreSDNode * Store,SelectionDAG & DAG)22612 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
22613   SDValue StoredVal = Store->getValue();
22614   assert((StoredVal.getValueType().is256BitVector() ||
22615           StoredVal.getValueType().is512BitVector()) &&
22616          "Expecting 256/512-bit op");
22617 
22618   // Splitting volatile memory ops is not allowed unless the operation was not
22619   // legal to begin with. Assume the input store is legal (this transform is
22620   // only used for targets with AVX). Note: It is possible that we have an
22621   // illegal type like v2i128, and so we could allow splitting a volatile store
22622   // in that case if that is important.
22623   if (!Store->isSimple())
22624     return SDValue();
22625 
22626   EVT StoreVT = StoredVal.getValueType();
22627   unsigned NumElems = StoreVT.getVectorNumElements();
22628   unsigned HalfSize = StoredVal.getValueSizeInBits() / 2;
22629   unsigned HalfAlign = (128 == HalfSize ? 16 : 32);
22630 
22631   SDLoc DL(Store);
22632   SDValue Value0 = extractSubVector(StoredVal, 0, DAG, DL, HalfSize);
22633   SDValue Value1 = extractSubVector(StoredVal, NumElems / 2, DAG, DL, HalfSize);
22634   SDValue Ptr0 = Store->getBasePtr();
22635   SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, HalfAlign, DL);
22636   unsigned Alignment = Store->getAlignment();
22637   SDValue Ch0 =
22638       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
22639                    Alignment, Store->getMemOperand()->getFlags());
22640   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
22641                              Store->getPointerInfo().getWithOffset(HalfAlign),
22642                              MinAlign(Alignment, HalfAlign),
22643                              Store->getMemOperand()->getFlags());
22644   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
22645 }
22646 
22647 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
22648 /// type.
scalarizeVectorStore(StoreSDNode * Store,MVT StoreVT,SelectionDAG & DAG)22649 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
22650                                     SelectionDAG &DAG) {
22651   SDValue StoredVal = Store->getValue();
22652   assert(StoreVT.is128BitVector() &&
22653          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
22654   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
22655 
22656   // Splitting volatile memory ops is not allowed unless the operation was not
22657   // legal to begin with. We are assuming the input op is legal (this transform
22658   // is only used for targets with AVX).
22659   if (!Store->isSimple())
22660     return SDValue();
22661 
22662   MVT StoreSVT = StoreVT.getScalarType();
22663   unsigned NumElems = StoreVT.getVectorNumElements();
22664   unsigned ScalarSize = StoreSVT.getStoreSize();
22665   unsigned Alignment = Store->getAlignment();
22666 
22667   SDLoc DL(Store);
22668   SmallVector<SDValue, 4> Stores;
22669   for (unsigned i = 0; i != NumElems; ++i) {
22670     unsigned Offset = i * ScalarSize;
22671     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(), Offset, DL);
22672     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
22673                               DAG.getIntPtrConstant(i, DL));
22674     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
22675                               Store->getPointerInfo().getWithOffset(Offset),
22676                               MinAlign(Alignment, Offset),
22677                               Store->getMemOperand()->getFlags());
22678     Stores.push_back(Ch);
22679   }
22680   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
22681 }
22682 
LowerStore(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22683 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
22684                           SelectionDAG &DAG) {
22685   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
22686   SDLoc dl(St);
22687   SDValue StoredVal = St->getValue();
22688 
22689   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
22690   if (StoredVal.getValueType().isVector() &&
22691       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
22692     assert(StoredVal.getValueType().getVectorNumElements() <= 8 &&
22693            "Unexpected VT");
22694     assert(!St->isTruncatingStore() && "Expected non-truncating store");
22695     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
22696            "Expected AVX512F without AVX512DQI");
22697 
22698     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
22699                             DAG.getUNDEF(MVT::v16i1), StoredVal,
22700                             DAG.getIntPtrConstant(0, dl));
22701     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
22702     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
22703 
22704     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
22705                         St->getPointerInfo(), St->getAlignment(),
22706                         St->getMemOperand()->getFlags());
22707   }
22708 
22709   if (St->isTruncatingStore())
22710     return SDValue();
22711 
22712   // If this is a 256-bit store of concatenated ops, we are better off splitting
22713   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
22714   // and each half can execute independently. Some cores would split the op into
22715   // halves anyway, so the concat (vinsertf128) is purely an extra op.
22716   MVT StoreVT = StoredVal.getSimpleValueType();
22717   if (StoreVT.is256BitVector()) {
22718     SmallVector<SDValue, 4> CatOps;
22719     if (StoredVal.hasOneUse() && collectConcatOps(StoredVal.getNode(), CatOps))
22720       return splitVectorStore(St, DAG);
22721     return SDValue();
22722   }
22723 
22724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22725   assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&
22726          "Unexpected VT");
22727   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
22728              TargetLowering::TypeWidenVector && "Unexpected type action!");
22729 
22730   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
22731   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
22732                           DAG.getUNDEF(StoreVT));
22733 
22734   if (Subtarget.hasSSE2()) {
22735     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
22736     // and store it.
22737     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
22738     MVT CastVT = MVT::getVectorVT(StVT, 2);
22739     StoredVal = DAG.getBitcast(CastVT, StoredVal);
22740     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
22741                             DAG.getIntPtrConstant(0, dl));
22742 
22743     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
22744                         St->getPointerInfo(), St->getAlignment(),
22745                         St->getMemOperand()->getFlags());
22746   }
22747   assert(Subtarget.hasSSE1() && "Expected SSE");
22748   SDVTList Tys = DAG.getVTList(MVT::Other);
22749   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
22750   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
22751                                  St->getMemOperand());
22752 }
22753 
22754 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
22755 // may emit an illegal shuffle but the expansion is still better than scalar
22756 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
22757 // we'll emit a shuffle and a arithmetic shift.
22758 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
22759 // TODO: It is possible to support ZExt by zeroing the undef values during
22760 // the shuffle phase or after the shuffle.
LowerLoad(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22761 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
22762                                  SelectionDAG &DAG) {
22763   MVT RegVT = Op.getSimpleValueType();
22764   assert(RegVT.isVector() && "We only custom lower vector loads.");
22765   assert(RegVT.isInteger() &&
22766          "We only custom lower integer vector loads.");
22767 
22768   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
22769   SDLoc dl(Ld);
22770 
22771   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
22772   if (RegVT.getVectorElementType() == MVT::i1) {
22773     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
22774     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
22775     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
22776            "Expected AVX512F without AVX512DQI");
22777 
22778     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
22779                                 Ld->getPointerInfo(), Ld->getAlignment(),
22780                                 Ld->getMemOperand()->getFlags());
22781 
22782     // Replace chain users with the new chain.
22783     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
22784 
22785     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
22786     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
22787                       DAG.getBitcast(MVT::v16i1, Val),
22788                       DAG.getIntPtrConstant(0, dl));
22789     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
22790   }
22791 
22792   return SDValue();
22793 }
22794 
22795 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
22796 /// each of which has no other use apart from the AND / OR.
isAndOrOfSetCCs(SDValue Op,unsigned & Opc)22797 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
22798   Opc = Op.getOpcode();
22799   if (Opc != ISD::OR && Opc != ISD::AND)
22800     return false;
22801   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
22802           Op.getOperand(0).hasOneUse() &&
22803           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
22804           Op.getOperand(1).hasOneUse());
22805 }
22806 
22807 /// Return true if node is an ISD::XOR of a X86ISD::SETCC and 1 and that the
22808 /// SETCC node has a single use.
isXor1OfSetCC(SDValue Op)22809 static bool isXor1OfSetCC(SDValue Op) {
22810   if (Op.getOpcode() != ISD::XOR)
22811     return false;
22812   if (isOneConstant(Op.getOperand(1)))
22813     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
22814            Op.getOperand(0).hasOneUse();
22815   return false;
22816 }
22817 
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const22818 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
22819   bool addTest = true;
22820   SDValue Chain = Op.getOperand(0);
22821   SDValue Cond  = Op.getOperand(1);
22822   SDValue Dest  = Op.getOperand(2);
22823   SDLoc dl(Op);
22824   SDValue CC;
22825   bool Inverted = false;
22826 
22827   if (Cond.getOpcode() == ISD::SETCC) {
22828     // Check for setcc([su]{add,sub,mul}o == 0).
22829     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
22830         isNullConstant(Cond.getOperand(1)) &&
22831         Cond.getOperand(0).getResNo() == 1 &&
22832         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
22833          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
22834          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
22835          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
22836          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
22837          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
22838       Inverted = true;
22839       Cond = Cond.getOperand(0);
22840     } else {
22841       if (SDValue NewCond = LowerSETCC(Cond, DAG))
22842         Cond = NewCond;
22843     }
22844   }
22845 #if 0
22846   // FIXME: LowerXALUO doesn't handle these!!
22847   else if (Cond.getOpcode() == X86ISD::ADD  ||
22848            Cond.getOpcode() == X86ISD::SUB  ||
22849            Cond.getOpcode() == X86ISD::SMUL ||
22850            Cond.getOpcode() == X86ISD::UMUL)
22851     Cond = LowerXALUO(Cond, DAG);
22852 #endif
22853 
22854   // Look pass (and (setcc_carry (cmp ...)), 1).
22855   if (Cond.getOpcode() == ISD::AND &&
22856       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
22857       isOneConstant(Cond.getOperand(1)))
22858     Cond = Cond.getOperand(0);
22859 
22860   // If condition flag is set by a X86ISD::CMP, then use it as the condition
22861   // setting operand in place of the X86ISD::SETCC.
22862   unsigned CondOpcode = Cond.getOpcode();
22863   if (CondOpcode == X86ISD::SETCC ||
22864       CondOpcode == X86ISD::SETCC_CARRY) {
22865     CC = Cond.getOperand(0);
22866 
22867     SDValue Cmp = Cond.getOperand(1);
22868     unsigned Opc = Cmp.getOpcode();
22869     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
22870     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
22871       Cond = Cmp;
22872       addTest = false;
22873     } else {
22874       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
22875       default: break;
22876       case X86::COND_O:
22877       case X86::COND_B:
22878         // These can only come from an arithmetic instruction with overflow,
22879         // e.g. SADDO, UADDO.
22880         Cond = Cond.getOperand(1);
22881         addTest = false;
22882         break;
22883       }
22884     }
22885   }
22886   CondOpcode = Cond.getOpcode();
22887   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
22888       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
22889       CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
22890     SDValue Value;
22891     X86::CondCode X86Cond;
22892     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
22893 
22894     if (Inverted)
22895       X86Cond = X86::GetOppositeBranchCondition(X86Cond);
22896 
22897     CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
22898     addTest = false;
22899   } else {
22900     unsigned CondOpc;
22901     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
22902       SDValue Cmp = Cond.getOperand(0).getOperand(1);
22903       if (CondOpc == ISD::OR) {
22904         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
22905         // two branches instead of an explicit OR instruction with a
22906         // separate test.
22907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
22908             isX86LogicalCmp(Cmp)) {
22909           CC = Cond.getOperand(0).getOperand(0);
22910           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
22911                               Chain, Dest, CC, Cmp);
22912           CC = Cond.getOperand(1).getOperand(0);
22913           Cond = Cmp;
22914           addTest = false;
22915         }
22916       } else { // ISD::AND
22917         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
22918         // two branches instead of an explicit AND instruction with a
22919         // separate test. However, we only do this if this block doesn't
22920         // have a fall-through edge, because this requires an explicit
22921         // jmp when the condition is false.
22922         if (Cmp == Cond.getOperand(1).getOperand(1) &&
22923             isX86LogicalCmp(Cmp) &&
22924             Op.getNode()->hasOneUse()) {
22925           X86::CondCode CCode0 =
22926               (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
22927           CCode0 = X86::GetOppositeBranchCondition(CCode0);
22928           CC = DAG.getTargetConstant(CCode0, dl, MVT::i8);
22929           SDNode *User = *Op.getNode()->use_begin();
22930           // Look for an unconditional branch following this conditional branch.
22931           // We need this because we need to reverse the successors in order
22932           // to implement FCMP_OEQ.
22933           if (User->getOpcode() == ISD::BR) {
22934             SDValue FalseBB = User->getOperand(1);
22935             SDNode *NewBR =
22936               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
22937             assert(NewBR == User);
22938             (void)NewBR;
22939             Dest = FalseBB;
22940 
22941             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), Chain,
22942                                 Dest, CC, Cmp);
22943             X86::CondCode CCode1 =
22944                 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
22945             CCode1 = X86::GetOppositeBranchCondition(CCode1);
22946             CC = DAG.getTargetConstant(CCode1, dl, MVT::i8);
22947             Cond = Cmp;
22948             addTest = false;
22949           }
22950         }
22951       }
22952     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
22953       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
22954       // It should be transformed during dag combiner except when the condition
22955       // is set by a arithmetics with overflow node.
22956       X86::CondCode CCode =
22957         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
22958       CCode = X86::GetOppositeBranchCondition(CCode);
22959       CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
22960       Cond = Cond.getOperand(0).getOperand(1);
22961       addTest = false;
22962     } else if (Cond.getOpcode() == ISD::SETCC &&
22963                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
22964       // For FCMP_OEQ, we can emit
22965       // two branches instead of an explicit AND instruction with a
22966       // separate test. However, we only do this if this block doesn't
22967       // have a fall-through edge, because this requires an explicit
22968       // jmp when the condition is false.
22969       if (Op.getNode()->hasOneUse()) {
22970         SDNode *User = *Op.getNode()->use_begin();
22971         // Look for an unconditional branch following this conditional branch.
22972         // We need this because we need to reverse the successors in order
22973         // to implement FCMP_OEQ.
22974         if (User->getOpcode() == ISD::BR) {
22975           SDValue FalseBB = User->getOperand(1);
22976           SDNode *NewBR =
22977             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
22978           assert(NewBR == User);
22979           (void)NewBR;
22980           Dest = FalseBB;
22981 
22982           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
22983                                     Cond.getOperand(0), Cond.getOperand(1));
22984           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
22985           CC = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
22986           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
22987                               Chain, Dest, CC, Cmp);
22988           CC = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
22989           Cond = Cmp;
22990           addTest = false;
22991         }
22992       }
22993     } else if (Cond.getOpcode() == ISD::SETCC &&
22994                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
22995       // For FCMP_UNE, we can emit
22996       // two branches instead of an explicit OR instruction with a
22997       // separate test.
22998       SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
22999                                 Cond.getOperand(0), Cond.getOperand(1));
23000       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
23001       CC = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
23002       Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
23003                           Chain, Dest, CC, Cmp);
23004       CC = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
23005       Cond = Cmp;
23006       addTest = false;
23007     }
23008   }
23009 
23010   if (addTest) {
23011     // Look pass the truncate if the high bits are known zero.
23012     if (isTruncWithZeroHighBitsInput(Cond, DAG))
23013         Cond = Cond.getOperand(0);
23014 
23015     // We know the result of AND is compared against zero. Try to match
23016     // it to BT.
23017     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
23018       SDValue BTCC;
23019       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, dl, DAG, BTCC)) {
23020         CC = BTCC;
23021         Cond = BT;
23022         addTest = false;
23023       }
23024     }
23025   }
23026 
23027   if (addTest) {
23028     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
23029     CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23030     Cond = EmitTest(Cond, X86Cond, dl, DAG, Subtarget);
23031   }
23032   Cond = ConvertCmpIfNecessary(Cond, DAG);
23033   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
23034                      Chain, Dest, CC, Cond);
23035 }
23036 
23037 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
23038 // Calls to _alloca are needed to probe the stack when allocating more than 4k
23039 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
23040 // that the guard pages used by the OS virtual memory manager are allocated in
23041 // correct sequence.
23042 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const23043 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
23044                                            SelectionDAG &DAG) const {
23045   MachineFunction &MF = DAG.getMachineFunction();
23046   bool SplitStack = MF.shouldSplitStack();
23047   bool EmitStackProbe = !getStackProbeSymbolName(MF).empty();
23048   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
23049                SplitStack || EmitStackProbe;
23050   SDLoc dl(Op);
23051 
23052   // Get the inputs.
23053   SDNode *Node = Op.getNode();
23054   SDValue Chain = Op.getOperand(0);
23055   SDValue Size  = Op.getOperand(1);
23056   MaybeAlign Alignment(Op.getConstantOperandVal(2));
23057   EVT VT = Node->getValueType(0);
23058 
23059   // Chain the dynamic stack allocation so that it doesn't modify the stack
23060   // pointer when other instructions are using the stack.
23061   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
23062 
23063   bool Is64Bit = Subtarget.is64Bit();
23064   MVT SPTy = getPointerTy(DAG.getDataLayout());
23065 
23066   SDValue Result;
23067   if (!Lower) {
23068     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23069     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
23070     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
23071                     " not tell us which reg is the stack pointer!");
23072 
23073     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
23074     Chain = SP.getValue(1);
23075     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
23076     const Align StackAlign(TFI.getStackAlignment());
23077     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
23078     if (Alignment && Alignment > StackAlign)
23079       Result =
23080           DAG.getNode(ISD::AND, dl, VT, Result,
23081                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
23082     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
23083   } else if (SplitStack) {
23084     MachineRegisterInfo &MRI = MF.getRegInfo();
23085 
23086     if (Is64Bit) {
23087       // The 64 bit implementation of segmented stacks needs to clobber both r10
23088       // r11. This makes it impossible to use it along with nested parameters.
23089       const Function &F = MF.getFunction();
23090       for (const auto &A : F.args()) {
23091         if (A.hasNestAttr())
23092           report_fatal_error("Cannot use segmented stacks with functions that "
23093                              "have nested arguments.");
23094       }
23095     }
23096 
23097     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
23098     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
23099     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
23100     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
23101                                 DAG.getRegister(Vreg, SPTy));
23102   } else {
23103     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
23104     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
23105     MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
23106 
23107     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23108     Register SPReg = RegInfo->getStackRegister();
23109     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
23110     Chain = SP.getValue(1);
23111 
23112     if (Alignment) {
23113       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
23114                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
23115       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
23116     }
23117 
23118     Result = SP;
23119   }
23120 
23121   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
23122                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
23123 
23124   SDValue Ops[2] = {Result, Chain};
23125   return DAG.getMergeValues(Ops, dl);
23126 }
23127 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const23128 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
23129   MachineFunction &MF = DAG.getMachineFunction();
23130   auto PtrVT = getPointerTy(MF.getDataLayout());
23131   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
23132 
23133   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
23134   SDLoc DL(Op);
23135 
23136   if (!Subtarget.is64Bit() ||
23137       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
23138     // vastart just stores the address of the VarArgsFrameIndex slot into the
23139     // memory location argument.
23140     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
23141     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
23142                         MachinePointerInfo(SV));
23143   }
23144 
23145   // __va_list_tag:
23146   //   gp_offset         (0 - 6 * 8)
23147   //   fp_offset         (48 - 48 + 8 * 16)
23148   //   overflow_arg_area (point to parameters coming in memory).
23149   //   reg_save_area
23150   SmallVector<SDValue, 8> MemOps;
23151   SDValue FIN = Op.getOperand(1);
23152   // Store gp_offset
23153   SDValue Store = DAG.getStore(
23154       Op.getOperand(0), DL,
23155       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
23156       MachinePointerInfo(SV));
23157   MemOps.push_back(Store);
23158 
23159   // Store fp_offset
23160   FIN = DAG.getMemBasePlusOffset(FIN, 4, DL);
23161   Store = DAG.getStore(
23162       Op.getOperand(0), DL,
23163       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
23164       MachinePointerInfo(SV, 4));
23165   MemOps.push_back(Store);
23166 
23167   // Store ptr to overflow_arg_area
23168   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
23169   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
23170   Store =
23171       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
23172   MemOps.push_back(Store);
23173 
23174   // Store ptr to reg_save_area.
23175   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
23176       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
23177   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
23178   Store = DAG.getStore(
23179       Op.getOperand(0), DL, RSFIN, FIN,
23180       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
23181   MemOps.push_back(Store);
23182   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
23183 }
23184 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const23185 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
23186   assert(Subtarget.is64Bit() &&
23187          "LowerVAARG only handles 64-bit va_arg!");
23188   assert(Op.getNumOperands() == 4);
23189 
23190   MachineFunction &MF = DAG.getMachineFunction();
23191   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
23192     // The Win64 ABI uses char* instead of a structure.
23193     return DAG.expandVAArg(Op.getNode());
23194 
23195   SDValue Chain = Op.getOperand(0);
23196   SDValue SrcPtr = Op.getOperand(1);
23197   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
23198   unsigned Align = Op.getConstantOperandVal(3);
23199   SDLoc dl(Op);
23200 
23201   EVT ArgVT = Op.getNode()->getValueType(0);
23202   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
23203   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
23204   uint8_t ArgMode;
23205 
23206   // Decide which area this value should be read from.
23207   // TODO: Implement the AMD64 ABI in its entirety. This simple
23208   // selection mechanism works only for the basic types.
23209   if (ArgVT == MVT::f80) {
23210     llvm_unreachable("va_arg for f80 not yet implemented");
23211   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
23212     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
23213   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
23214     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
23215   } else {
23216     llvm_unreachable("Unhandled argument type in LowerVAARG");
23217   }
23218 
23219   if (ArgMode == 2) {
23220     // Sanity Check: Make sure using fp_offset makes sense.
23221     assert(!Subtarget.useSoftFloat() &&
23222            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
23223            Subtarget.hasSSE1());
23224   }
23225 
23226   // Insert VAARG_64 node into the DAG
23227   // VAARG_64 returns two values: Variable Argument Address, Chain
23228   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
23229                        DAG.getConstant(ArgMode, dl, MVT::i8),
23230                        DAG.getConstant(Align, dl, MVT::i32)};
23231   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
23232   SDValue VAARG = DAG.getMemIntrinsicNode(
23233     X86ISD::VAARG_64, dl,
23234     VTs, InstOps, MVT::i64,
23235     MachinePointerInfo(SV),
23236     /*Align=*/0,
23237     MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
23238   Chain = VAARG.getValue(1);
23239 
23240   // Load the next argument and return it
23241   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
23242 }
23243 
LowerVACOPY(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23244 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
23245                            SelectionDAG &DAG) {
23246   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
23247   // where a va_list is still an i8*.
23248   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
23249   if (Subtarget.isCallingConvWin64(
23250         DAG.getMachineFunction().getFunction().getCallingConv()))
23251     // Probably a Win64 va_copy.
23252     return DAG.expandVACopy(Op.getNode());
23253 
23254   SDValue Chain = Op.getOperand(0);
23255   SDValue DstPtr = Op.getOperand(1);
23256   SDValue SrcPtr = Op.getOperand(2);
23257   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
23258   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
23259   SDLoc DL(Op);
23260 
23261   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
23262                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
23263                        false, false,
23264                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
23265 }
23266 
23267 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
getTargetVShiftUniformOpcode(unsigned Opc,bool IsVariable)23268 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
23269   switch (Opc) {
23270   case ISD::SHL:
23271   case X86ISD::VSHL:
23272   case X86ISD::VSHLI:
23273     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
23274   case ISD::SRL:
23275   case X86ISD::VSRL:
23276   case X86ISD::VSRLI:
23277     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
23278   case ISD::SRA:
23279   case X86ISD::VSRA:
23280   case X86ISD::VSRAI:
23281     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
23282   }
23283   llvm_unreachable("Unknown target vector shift node");
23284 }
23285 
23286 /// Handle vector element shifts where the shift amount is a constant.
23287 /// Takes immediate version of shift as input.
getTargetVShiftByConstNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,uint64_t ShiftAmt,SelectionDAG & DAG)23288 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
23289                                           SDValue SrcOp, uint64_t ShiftAmt,
23290                                           SelectionDAG &DAG) {
23291   MVT ElementType = VT.getVectorElementType();
23292 
23293   // Bitcast the source vector to the output type, this is mainly necessary for
23294   // vXi8/vXi64 shifts.
23295   if (VT != SrcOp.getSimpleValueType())
23296     SrcOp = DAG.getBitcast(VT, SrcOp);
23297 
23298   // Fold this packed shift into its first operand if ShiftAmt is 0.
23299   if (ShiftAmt == 0)
23300     return SrcOp;
23301 
23302   // Check for ShiftAmt >= element width
23303   if (ShiftAmt >= ElementType.getSizeInBits()) {
23304     if (Opc == X86ISD::VSRAI)
23305       ShiftAmt = ElementType.getSizeInBits() - 1;
23306     else
23307       return DAG.getConstant(0, dl, VT);
23308   }
23309 
23310   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
23311          && "Unknown target vector shift-by-constant node");
23312 
23313   // Fold this packed vector shift into a build vector if SrcOp is a
23314   // vector of Constants or UNDEFs.
23315   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
23316     SmallVector<SDValue, 8> Elts;
23317     unsigned NumElts = SrcOp->getNumOperands();
23318 
23319     switch (Opc) {
23320     default: llvm_unreachable("Unknown opcode!");
23321     case X86ISD::VSHLI:
23322       for (unsigned i = 0; i != NumElts; ++i) {
23323         SDValue CurrentOp = SrcOp->getOperand(i);
23324         if (CurrentOp->isUndef()) {
23325           Elts.push_back(CurrentOp);
23326           continue;
23327         }
23328         auto *ND = cast<ConstantSDNode>(CurrentOp);
23329         const APInt &C = ND->getAPIntValue();
23330         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
23331       }
23332       break;
23333     case X86ISD::VSRLI:
23334       for (unsigned i = 0; i != NumElts; ++i) {
23335         SDValue CurrentOp = SrcOp->getOperand(i);
23336         if (CurrentOp->isUndef()) {
23337           Elts.push_back(CurrentOp);
23338           continue;
23339         }
23340         auto *ND = cast<ConstantSDNode>(CurrentOp);
23341         const APInt &C = ND->getAPIntValue();
23342         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
23343       }
23344       break;
23345     case X86ISD::VSRAI:
23346       for (unsigned i = 0; i != NumElts; ++i) {
23347         SDValue CurrentOp = SrcOp->getOperand(i);
23348         if (CurrentOp->isUndef()) {
23349           Elts.push_back(CurrentOp);
23350           continue;
23351         }
23352         auto *ND = cast<ConstantSDNode>(CurrentOp);
23353         const APInt &C = ND->getAPIntValue();
23354         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
23355       }
23356       break;
23357     }
23358 
23359     return DAG.getBuildVector(VT, dl, Elts);
23360   }
23361 
23362   return DAG.getNode(Opc, dl, VT, SrcOp,
23363                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
23364 }
23365 
23366 /// Handle vector element shifts where the shift amount may or may not be a
23367 /// constant. Takes immediate version of shift as input.
getTargetVShiftNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,SDValue ShAmt,const X86Subtarget & Subtarget,SelectionDAG & DAG)23368 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
23369                                    SDValue SrcOp, SDValue ShAmt,
23370                                    const X86Subtarget &Subtarget,
23371                                    SelectionDAG &DAG) {
23372   MVT SVT = ShAmt.getSimpleValueType();
23373   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
23374 
23375   // Catch shift-by-constant.
23376   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
23377     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
23378                                       CShAmt->getZExtValue(), DAG);
23379 
23380   // Change opcode to non-immediate version.
23381   Opc = getTargetVShiftUniformOpcode(Opc, true);
23382 
23383   // Need to build a vector containing shift amount.
23384   // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
23385   // +====================+============+=======================================+
23386   // | ShAmt is           | HasSSE4.1? | Construct ShAmt vector as             |
23387   // +====================+============+=======================================+
23388   // | i64                | Yes, No    | Use ShAmt as lowest elt               |
23389   // | i32                | Yes        | zero-extend in-reg                    |
23390   // | (i32 zext(i16/i8)) | Yes        | zero-extend in-reg                    |
23391   // | (i32 zext(i16/i8)) | No         | byte-shift-in-reg                     |
23392   // | i16/i32            | No         | v4i32 build_vector(ShAmt, 0, ud, ud)) |
23393   // +====================+============+=======================================+
23394 
23395   if (SVT == MVT::i64)
23396     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
23397   else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
23398            ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23399            (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
23400             ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
23401     ShAmt = ShAmt.getOperand(0);
23402     MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
23403     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
23404     if (Subtarget.hasSSE41())
23405       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
23406                           MVT::v2i64, ShAmt);
23407     else {
23408       SDValue ByteShift = DAG.getTargetConstant(
23409           (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
23410       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
23411       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
23412                           ByteShift);
23413       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
23414                           ByteShift);
23415     }
23416   } else if (Subtarget.hasSSE41() &&
23417              ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23418     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
23419     ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
23420                         MVT::v2i64, ShAmt);
23421   } else {
23422     SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
23423                         DAG.getUNDEF(SVT)};
23424     ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
23425   }
23426 
23427   // The return type has to be a 128-bit type with the same element
23428   // type as the input type.
23429   MVT EltVT = VT.getVectorElementType();
23430   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
23431 
23432   ShAmt = DAG.getBitcast(ShVT, ShAmt);
23433   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
23434 }
23435 
23436 /// Return Mask with the necessary casting or extending
23437 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
getMaskNode(SDValue Mask,MVT MaskVT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)23438 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
23439                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
23440                            const SDLoc &dl) {
23441 
23442   if (isAllOnesConstant(Mask))
23443     return DAG.getConstant(1, dl, MaskVT);
23444   if (X86::isZeroNode(Mask))
23445     return DAG.getConstant(0, dl, MaskVT);
23446 
23447   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
23448 
23449   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
23450     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
23451     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
23452     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
23453     SDValue Lo, Hi;
23454     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
23455                         DAG.getConstant(0, dl, MVT::i32));
23456     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
23457                         DAG.getConstant(1, dl, MVT::i32));
23458 
23459     Lo = DAG.getBitcast(MVT::v32i1, Lo);
23460     Hi = DAG.getBitcast(MVT::v32i1, Hi);
23461 
23462     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
23463   } else {
23464     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
23465                                      Mask.getSimpleValueType().getSizeInBits());
23466     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
23467     // are extracted by EXTRACT_SUBVECTOR.
23468     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
23469                        DAG.getBitcast(BitcastVT, Mask),
23470                        DAG.getIntPtrConstant(0, dl));
23471   }
23472 }
23473 
23474 /// Return (and \p Op, \p Mask) for compare instructions or
23475 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
23476 /// necessary casting or extending for \p Mask when lowering masking intrinsics
getVectorMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)23477 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
23478                   SDValue PreservedSrc,
23479                   const X86Subtarget &Subtarget,
23480                   SelectionDAG &DAG) {
23481   MVT VT = Op.getSimpleValueType();
23482   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
23483   unsigned OpcodeSelect = ISD::VSELECT;
23484   SDLoc dl(Op);
23485 
23486   if (isAllOnesConstant(Mask))
23487     return Op;
23488 
23489   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23490 
23491   if (PreservedSrc.isUndef())
23492     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
23493   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
23494 }
23495 
23496 /// Creates an SDNode for a predicated scalar operation.
23497 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
23498 /// The mask is coming as MVT::i8 and it should be transformed
23499 /// to MVT::v1i1 while lowering masking intrinsics.
23500 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
23501 /// "X86select" instead of "vselect". We just can't create the "vselect" node
23502 /// for a scalar instruction.
getScalarMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)23503 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
23504                                     SDValue PreservedSrc,
23505                                     const X86Subtarget &Subtarget,
23506                                     SelectionDAG &DAG) {
23507 
23508   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
23509     if (MaskConst->getZExtValue() & 0x1)
23510       return Op;
23511 
23512   MVT VT = Op.getSimpleValueType();
23513   SDLoc dl(Op);
23514 
23515   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
23516   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
23517                               DAG.getBitcast(MVT::v8i1, Mask),
23518                               DAG.getIntPtrConstant(0, dl));
23519   if (Op.getOpcode() == X86ISD::FSETCCM ||
23520       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
23521       Op.getOpcode() == X86ISD::VFPCLASSS)
23522     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
23523 
23524   if (PreservedSrc.isUndef())
23525     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
23526   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
23527 }
23528 
getSEHRegistrationNodeSize(const Function * Fn)23529 static int getSEHRegistrationNodeSize(const Function *Fn) {
23530   if (!Fn->hasPersonalityFn())
23531     report_fatal_error(
23532         "querying registration node size for function without personality");
23533   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
23534   // WinEHStatePass for the full struct definition.
23535   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
23536   case EHPersonality::MSVC_X86SEH: return 24;
23537   case EHPersonality::MSVC_CXX: return 16;
23538   default: break;
23539   }
23540   report_fatal_error(
23541       "can only recover FP for 32-bit MSVC EH personality functions");
23542 }
23543 
23544 /// When the MSVC runtime transfers control to us, either to an outlined
23545 /// function or when returning to a parent frame after catching an exception, we
23546 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
23547 /// Here's the math:
23548 ///   RegNodeBase = EntryEBP - RegNodeSize
23549 ///   ParentFP = RegNodeBase - ParentFrameOffset
23550 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
23551 /// subtracting the offset (negative on x86) takes us back to the parent FP.
recoverFramePointer(SelectionDAG & DAG,const Function * Fn,SDValue EntryEBP)23552 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
23553                                    SDValue EntryEBP) {
23554   MachineFunction &MF = DAG.getMachineFunction();
23555   SDLoc dl;
23556 
23557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23558   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23559 
23560   // It's possible that the parent function no longer has a personality function
23561   // if the exceptional code was optimized away, in which case we just return
23562   // the incoming EBP.
23563   if (!Fn->hasPersonalityFn())
23564     return EntryEBP;
23565 
23566   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
23567   // registration, or the .set_setframe offset.
23568   MCSymbol *OffsetSym =
23569       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
23570           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
23571   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
23572   SDValue ParentFrameOffset =
23573       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
23574 
23575   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
23576   // prologue to RBP in the parent function.
23577   const X86Subtarget &Subtarget =
23578       static_cast<const X86Subtarget &>(DAG.getSubtarget());
23579   if (Subtarget.is64Bit())
23580     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
23581 
23582   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
23583   // RegNodeBase = EntryEBP - RegNodeSize
23584   // ParentFP = RegNodeBase - ParentFrameOffset
23585   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
23586                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
23587   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
23588 }
23589 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const23590 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
23591                                                    SelectionDAG &DAG) const {
23592   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
23593   auto isRoundModeCurDirection = [](SDValue Rnd) {
23594     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
23595       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
23596 
23597     return false;
23598   };
23599   auto isRoundModeSAE = [](SDValue Rnd) {
23600     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
23601       unsigned RC = C->getZExtValue();
23602       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
23603         // Clear the NO_EXC bit and check remaining bits.
23604         RC ^= X86::STATIC_ROUNDING::NO_EXC;
23605         // As a convenience we allow no other bits or explicitly
23606         // current direction.
23607         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
23608       }
23609     }
23610 
23611     return false;
23612   };
23613   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
23614     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
23615       RC = C->getZExtValue();
23616       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
23617         // Clear the NO_EXC bit and check remaining bits.
23618         RC ^= X86::STATIC_ROUNDING::NO_EXC;
23619         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
23620                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
23621                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
23622                RC == X86::STATIC_ROUNDING::TO_ZERO;
23623       }
23624     }
23625 
23626     return false;
23627   };
23628 
23629   SDLoc dl(Op);
23630   unsigned IntNo = Op.getConstantOperandVal(0);
23631   MVT VT = Op.getSimpleValueType();
23632   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
23633 
23634   if (IntrData) {
23635     switch(IntrData->Type) {
23636     case INTR_TYPE_1OP: {
23637       // We specify 2 possible opcodes for intrinsics with rounding modes.
23638       // First, we check if the intrinsic may have non-default rounding mode,
23639       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
23640       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
23641       if (IntrWithRoundingModeOpcode != 0) {
23642         SDValue Rnd = Op.getOperand(2);
23643         unsigned RC = 0;
23644         if (isRoundModeSAEToX(Rnd, RC))
23645           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
23646                              Op.getOperand(1),
23647                              DAG.getTargetConstant(RC, dl, MVT::i32));
23648         if (!isRoundModeCurDirection(Rnd))
23649           return SDValue();
23650       }
23651       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
23652                          Op.getOperand(1));
23653     }
23654     case INTR_TYPE_1OP_SAE: {
23655       SDValue Sae = Op.getOperand(2);
23656 
23657       unsigned Opc;
23658       if (isRoundModeCurDirection(Sae))
23659         Opc = IntrData->Opc0;
23660       else if (isRoundModeSAE(Sae))
23661         Opc = IntrData->Opc1;
23662       else
23663         return SDValue();
23664 
23665       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
23666     }
23667     case INTR_TYPE_2OP: {
23668       SDValue Src2 = Op.getOperand(2);
23669 
23670       // We specify 2 possible opcodes for intrinsics with rounding modes.
23671       // First, we check if the intrinsic may have non-default rounding mode,
23672       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
23673       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
23674       if (IntrWithRoundingModeOpcode != 0) {
23675         SDValue Rnd = Op.getOperand(3);
23676         unsigned RC = 0;
23677         if (isRoundModeSAEToX(Rnd, RC))
23678           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
23679                              Op.getOperand(1), Src2,
23680                              DAG.getTargetConstant(RC, dl, MVT::i32));
23681         if (!isRoundModeCurDirection(Rnd))
23682           return SDValue();
23683       }
23684 
23685       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
23686                          Op.getOperand(1), Src2);
23687     }
23688     case INTR_TYPE_2OP_SAE: {
23689       SDValue Sae = Op.getOperand(3);
23690 
23691       unsigned Opc;
23692       if (isRoundModeCurDirection(Sae))
23693         Opc = IntrData->Opc0;
23694       else if (isRoundModeSAE(Sae))
23695         Opc = IntrData->Opc1;
23696       else
23697         return SDValue();
23698 
23699       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
23700                          Op.getOperand(2));
23701     }
23702     case INTR_TYPE_3OP:
23703     case INTR_TYPE_3OP_IMM8: {
23704       SDValue Src1 = Op.getOperand(1);
23705       SDValue Src2 = Op.getOperand(2);
23706       SDValue Src3 = Op.getOperand(3);
23707 
23708       // We specify 2 possible opcodes for intrinsics with rounding modes.
23709       // First, we check if the intrinsic may have non-default rounding mode,
23710       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
23711       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
23712       if (IntrWithRoundingModeOpcode != 0) {
23713         SDValue Rnd = Op.getOperand(4);
23714         unsigned RC = 0;
23715         if (isRoundModeSAEToX(Rnd, RC))
23716           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
23717                              Src1, Src2, Src3,
23718                              DAG.getTargetConstant(RC, dl, MVT::i32));
23719         if (!isRoundModeCurDirection(Rnd))
23720           return SDValue();
23721       }
23722 
23723       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
23724                          {Src1, Src2, Src3});
23725     }
23726     case INTR_TYPE_4OP:
23727       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
23728         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
23729     case INTR_TYPE_1OP_MASK: {
23730       SDValue Src = Op.getOperand(1);
23731       SDValue PassThru = Op.getOperand(2);
23732       SDValue Mask = Op.getOperand(3);
23733       // We add rounding mode to the Node when
23734       //   - RC Opcode is specified and
23735       //   - RC is not "current direction".
23736       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
23737       if (IntrWithRoundingModeOpcode != 0) {
23738         SDValue Rnd = Op.getOperand(4);
23739         unsigned RC = 0;
23740         if (isRoundModeSAEToX(Rnd, RC))
23741           return getVectorMaskingNode(
23742               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
23743                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
23744               Mask, PassThru, Subtarget, DAG);
23745         if (!isRoundModeCurDirection(Rnd))
23746           return SDValue();
23747       }
23748       return getVectorMaskingNode(
23749           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
23750           Subtarget, DAG);
23751     }
23752     case INTR_TYPE_1OP_MASK_SAE: {
23753       SDValue Src = Op.getOperand(1);
23754       SDValue PassThru = Op.getOperand(2);
23755       SDValue Mask = Op.getOperand(3);
23756       SDValue Rnd = Op.getOperand(4);
23757 
23758       unsigned Opc;
23759       if (isRoundModeCurDirection(Rnd))
23760         Opc = IntrData->Opc0;
23761       else if (isRoundModeSAE(Rnd))
23762         Opc = IntrData->Opc1;
23763       else
23764         return SDValue();
23765 
23766       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
23767                                   Subtarget, DAG);
23768     }
23769     case INTR_TYPE_SCALAR_MASK: {
23770       SDValue Src1 = Op.getOperand(1);
23771       SDValue Src2 = Op.getOperand(2);
23772       SDValue passThru = Op.getOperand(3);
23773       SDValue Mask = Op.getOperand(4);
23774       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
23775       // There are 2 kinds of intrinsics in this group:
23776       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
23777       // (2) With rounding mode and sae - 7 operands.
23778       bool HasRounding = IntrWithRoundingModeOpcode != 0;
23779       if (Op.getNumOperands() == (5U + HasRounding)) {
23780         if (HasRounding) {
23781           SDValue Rnd = Op.getOperand(5);
23782           unsigned RC = 0;
23783           if (isRoundModeSAEToX(Rnd, RC))
23784             return getScalarMaskingNode(
23785                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
23786                             DAG.getTargetConstant(RC, dl, MVT::i32)),
23787                 Mask, passThru, Subtarget, DAG);
23788           if (!isRoundModeCurDirection(Rnd))
23789             return SDValue();
23790         }
23791         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
23792                                                 Src2),
23793                                     Mask, passThru, Subtarget, DAG);
23794       }
23795 
23796       assert(Op.getNumOperands() == (6U + HasRounding) &&
23797              "Unexpected intrinsic form");
23798       SDValue RoundingMode = Op.getOperand(5);
23799       unsigned Opc = IntrData->Opc0;
23800       if (HasRounding) {
23801         SDValue Sae = Op.getOperand(6);
23802         if (isRoundModeSAE(Sae))
23803           Opc = IntrWithRoundingModeOpcode;
23804         else if (!isRoundModeCurDirection(Sae))
23805           return SDValue();
23806       }
23807       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
23808                                               Src2, RoundingMode),
23809                                   Mask, passThru, Subtarget, DAG);
23810     }
23811     case INTR_TYPE_SCALAR_MASK_RND: {
23812       SDValue Src1 = Op.getOperand(1);
23813       SDValue Src2 = Op.getOperand(2);
23814       SDValue passThru = Op.getOperand(3);
23815       SDValue Mask = Op.getOperand(4);
23816       SDValue Rnd = Op.getOperand(5);
23817 
23818       SDValue NewOp;
23819       unsigned RC = 0;
23820       if (isRoundModeCurDirection(Rnd))
23821         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
23822       else if (isRoundModeSAEToX(Rnd, RC))
23823         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
23824                             DAG.getTargetConstant(RC, dl, MVT::i32));
23825       else
23826         return SDValue();
23827 
23828       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
23829     }
23830     case INTR_TYPE_SCALAR_MASK_SAE: {
23831       SDValue Src1 = Op.getOperand(1);
23832       SDValue Src2 = Op.getOperand(2);
23833       SDValue passThru = Op.getOperand(3);
23834       SDValue Mask = Op.getOperand(4);
23835       SDValue Sae = Op.getOperand(5);
23836       unsigned Opc;
23837       if (isRoundModeCurDirection(Sae))
23838         Opc = IntrData->Opc0;
23839       else if (isRoundModeSAE(Sae))
23840         Opc = IntrData->Opc1;
23841       else
23842         return SDValue();
23843 
23844       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
23845                                   Mask, passThru, Subtarget, DAG);
23846     }
23847     case INTR_TYPE_2OP_MASK: {
23848       SDValue Src1 = Op.getOperand(1);
23849       SDValue Src2 = Op.getOperand(2);
23850       SDValue PassThru = Op.getOperand(3);
23851       SDValue Mask = Op.getOperand(4);
23852       SDValue NewOp;
23853       if (IntrData->Opc1 != 0) {
23854         SDValue Rnd = Op.getOperand(5);
23855         unsigned RC = 0;
23856         if (isRoundModeSAEToX(Rnd, RC))
23857           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
23858                               DAG.getTargetConstant(RC, dl, MVT::i32));
23859         else if (!isRoundModeCurDirection(Rnd))
23860           return SDValue();
23861       }
23862       if (!NewOp)
23863         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
23864       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
23865     }
23866     case INTR_TYPE_2OP_MASK_SAE: {
23867       SDValue Src1 = Op.getOperand(1);
23868       SDValue Src2 = Op.getOperand(2);
23869       SDValue PassThru = Op.getOperand(3);
23870       SDValue Mask = Op.getOperand(4);
23871 
23872       unsigned Opc = IntrData->Opc0;
23873       if (IntrData->Opc1 != 0) {
23874         SDValue Sae = Op.getOperand(5);
23875         if (isRoundModeSAE(Sae))
23876           Opc = IntrData->Opc1;
23877         else if (!isRoundModeCurDirection(Sae))
23878           return SDValue();
23879       }
23880 
23881       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
23882                                   Mask, PassThru, Subtarget, DAG);
23883     }
23884     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
23885       SDValue Src1 = Op.getOperand(1);
23886       SDValue Src2 = Op.getOperand(2);
23887       SDValue Src3 = Op.getOperand(3);
23888       SDValue PassThru = Op.getOperand(4);
23889       SDValue Mask = Op.getOperand(5);
23890       SDValue Sae = Op.getOperand(6);
23891       unsigned Opc;
23892       if (isRoundModeCurDirection(Sae))
23893         Opc = IntrData->Opc0;
23894       else if (isRoundModeSAE(Sae))
23895         Opc = IntrData->Opc1;
23896       else
23897         return SDValue();
23898 
23899       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
23900                                   Mask, PassThru, Subtarget, DAG);
23901     }
23902     case INTR_TYPE_3OP_MASK_SAE: {
23903       SDValue Src1 = Op.getOperand(1);
23904       SDValue Src2 = Op.getOperand(2);
23905       SDValue Src3 = Op.getOperand(3);
23906       SDValue PassThru = Op.getOperand(4);
23907       SDValue Mask = Op.getOperand(5);
23908 
23909       unsigned Opc = IntrData->Opc0;
23910       if (IntrData->Opc1 != 0) {
23911         SDValue Sae = Op.getOperand(6);
23912         if (isRoundModeSAE(Sae))
23913           Opc = IntrData->Opc1;
23914         else if (!isRoundModeCurDirection(Sae))
23915           return SDValue();
23916       }
23917       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
23918                                   Mask, PassThru, Subtarget, DAG);
23919     }
23920     case BLENDV: {
23921       SDValue Src1 = Op.getOperand(1);
23922       SDValue Src2 = Op.getOperand(2);
23923       SDValue Src3 = Op.getOperand(3);
23924 
23925       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
23926       Src3 = DAG.getBitcast(MaskVT, Src3);
23927 
23928       // Reverse the operands to match VSELECT order.
23929       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
23930     }
23931     case VPERM_2OP : {
23932       SDValue Src1 = Op.getOperand(1);
23933       SDValue Src2 = Op.getOperand(2);
23934 
23935       // Swap Src1 and Src2 in the node creation
23936       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
23937     }
23938     case IFMA_OP:
23939       // NOTE: We need to swizzle the operands to pass the multiply operands
23940       // first.
23941       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
23942                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
23943     case FPCLASSS: {
23944       SDValue Src1 = Op.getOperand(1);
23945       SDValue Imm = Op.getOperand(2);
23946       SDValue Mask = Op.getOperand(3);
23947       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
23948       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
23949                                                  Subtarget, DAG);
23950       // Need to fill with zeros to ensure the bitcast will produce zeroes
23951       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
23952       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
23953                                 DAG.getConstant(0, dl, MVT::v8i1),
23954                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
23955       return DAG.getBitcast(MVT::i8, Ins);
23956     }
23957 
23958     case CMP_MASK_CC: {
23959       MVT MaskVT = Op.getSimpleValueType();
23960       SDValue CC = Op.getOperand(3);
23961       // We specify 2 possible opcodes for intrinsics with rounding modes.
23962       // First, we check if the intrinsic may have non-default rounding mode,
23963       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
23964       if (IntrData->Opc1 != 0) {
23965         SDValue Sae = Op.getOperand(4);
23966         if (isRoundModeSAE(Sae))
23967           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
23968                              Op.getOperand(2), CC, Sae);
23969         if (!isRoundModeCurDirection(Sae))
23970           return SDValue();
23971       }
23972       //default rounding mode
23973       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
23974                          {Op.getOperand(1), Op.getOperand(2), CC});
23975     }
23976     case CMP_MASK_SCALAR_CC: {
23977       SDValue Src1 = Op.getOperand(1);
23978       SDValue Src2 = Op.getOperand(2);
23979       SDValue CC = Op.getOperand(3);
23980       SDValue Mask = Op.getOperand(4);
23981 
23982       SDValue Cmp;
23983       if (IntrData->Opc1 != 0) {
23984         SDValue Sae = Op.getOperand(5);
23985         if (isRoundModeSAE(Sae))
23986           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
23987         else if (!isRoundModeCurDirection(Sae))
23988           return SDValue();
23989       }
23990       //default rounding mode
23991       if (!Cmp.getNode())
23992         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
23993 
23994       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
23995                                              Subtarget, DAG);
23996       // Need to fill with zeros to ensure the bitcast will produce zeroes
23997       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
23998       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
23999                                 DAG.getConstant(0, dl, MVT::v8i1),
24000                                 CmpMask, DAG.getIntPtrConstant(0, dl));
24001       return DAG.getBitcast(MVT::i8, Ins);
24002     }
24003     case COMI: { // Comparison intrinsics
24004       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
24005       SDValue LHS = Op.getOperand(1);
24006       SDValue RHS = Op.getOperand(2);
24007       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
24008       SDValue InvComi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, RHS, LHS);
24009       SDValue SetCC;
24010       switch (CC) {
24011       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
24012         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
24013         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
24014         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
24015         break;
24016       }
24017       case ISD::SETNE: { // (ZF = 1 or PF = 1)
24018         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
24019         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
24020         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
24021         break;
24022       }
24023       case ISD::SETGT: // (CF = 0 and ZF = 0)
24024         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
24025         break;
24026       case ISD::SETLT: { // The condition is opposite to GT. Swap the operands.
24027         SetCC = getSETCC(X86::COND_A, InvComi, dl, DAG);
24028         break;
24029       }
24030       case ISD::SETGE: // CF = 0
24031         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
24032         break;
24033       case ISD::SETLE: // The condition is opposite to GE. Swap the operands.
24034         SetCC = getSETCC(X86::COND_AE, InvComi, dl, DAG);
24035         break;
24036       default:
24037         llvm_unreachable("Unexpected illegal condition!");
24038       }
24039       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
24040     }
24041     case COMI_RM: { // Comparison intrinsics with Sae
24042       SDValue LHS = Op.getOperand(1);
24043       SDValue RHS = Op.getOperand(2);
24044       unsigned CondVal = Op.getConstantOperandVal(3);
24045       SDValue Sae = Op.getOperand(4);
24046 
24047       SDValue FCmp;
24048       if (isRoundModeCurDirection(Sae))
24049         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
24050                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
24051       else if (isRoundModeSAE(Sae))
24052         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
24053                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
24054       else
24055         return SDValue();
24056       // Need to fill with zeros to ensure the bitcast will produce zeroes
24057       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
24058       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
24059                                 DAG.getConstant(0, dl, MVT::v16i1),
24060                                 FCmp, DAG.getIntPtrConstant(0, dl));
24061       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
24062                          DAG.getBitcast(MVT::i16, Ins));
24063     }
24064     case VSHIFT:
24065       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
24066                                  Op.getOperand(1), Op.getOperand(2), Subtarget,
24067                                  DAG);
24068     case COMPRESS_EXPAND_IN_REG: {
24069       SDValue Mask = Op.getOperand(3);
24070       SDValue DataToCompress = Op.getOperand(1);
24071       SDValue PassThru = Op.getOperand(2);
24072       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
24073         return Op.getOperand(1);
24074 
24075       // Avoid false dependency.
24076       if (PassThru.isUndef())
24077         PassThru = DAG.getConstant(0, dl, VT);
24078 
24079       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
24080                          Mask);
24081     }
24082     case FIXUPIMM:
24083     case FIXUPIMM_MASKZ: {
24084       SDValue Src1 = Op.getOperand(1);
24085       SDValue Src2 = Op.getOperand(2);
24086       SDValue Src3 = Op.getOperand(3);
24087       SDValue Imm = Op.getOperand(4);
24088       SDValue Mask = Op.getOperand(5);
24089       SDValue Passthru = (IntrData->Type == FIXUPIMM)
24090                              ? Src1
24091                              : getZeroVector(VT, Subtarget, DAG, dl);
24092 
24093       unsigned Opc = IntrData->Opc0;
24094       if (IntrData->Opc1 != 0) {
24095         SDValue Sae = Op.getOperand(6);
24096         if (isRoundModeSAE(Sae))
24097           Opc = IntrData->Opc1;
24098         else if (!isRoundModeCurDirection(Sae))
24099           return SDValue();
24100       }
24101 
24102       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
24103 
24104       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
24105         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
24106 
24107       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
24108     }
24109     case ROUNDP: {
24110       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
24111       // Clear the upper bits of the rounding immediate so that the legacy
24112       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
24113       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
24114       SDValue RoundingMode =
24115           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
24116       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24117                          Op.getOperand(1), RoundingMode);
24118     }
24119     case ROUNDS: {
24120       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
24121       // Clear the upper bits of the rounding immediate so that the legacy
24122       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
24123       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
24124       SDValue RoundingMode =
24125           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
24126       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24127                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
24128     }
24129     case BEXTRI: {
24130       assert(IntrData->Opc0 == X86ISD::BEXTR && "Unexpected opcode");
24131 
24132       // The control is a TargetConstant, but we need to convert it to a
24133       // ConstantSDNode.
24134       uint64_t Imm = Op.getConstantOperandVal(2);
24135       SDValue Control = DAG.getConstant(Imm, dl, Op.getValueType());
24136       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24137                          Op.getOperand(1), Control);
24138     }
24139     // ADC/ADCX/SBB
24140     case ADX: {
24141       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
24142       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
24143 
24144       SDValue Res;
24145       // If the carry in is zero, then we should just use ADD/SUB instead of
24146       // ADC/SBB.
24147       if (isNullConstant(Op.getOperand(1))) {
24148         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
24149                           Op.getOperand(3));
24150       } else {
24151         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
24152                                     DAG.getConstant(-1, dl, MVT::i8));
24153         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
24154                           Op.getOperand(3), GenCF.getValue(1));
24155       }
24156       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
24157       SDValue Results[] = { SetCC, Res };
24158       return DAG.getMergeValues(Results, dl);
24159     }
24160     case CVTPD2PS_MASK:
24161     case CVTPD2DQ_MASK:
24162     case CVTQQ2PS_MASK:
24163     case TRUNCATE_TO_REG: {
24164       SDValue Src = Op.getOperand(1);
24165       SDValue PassThru = Op.getOperand(2);
24166       SDValue Mask = Op.getOperand(3);
24167 
24168       if (isAllOnesConstant(Mask))
24169         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
24170 
24171       MVT SrcVT = Src.getSimpleValueType();
24172       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
24173       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24174       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
24175                          {Src, PassThru, Mask});
24176     }
24177     case CVTPS2PH_MASK: {
24178       SDValue Src = Op.getOperand(1);
24179       SDValue Rnd = Op.getOperand(2);
24180       SDValue PassThru = Op.getOperand(3);
24181       SDValue Mask = Op.getOperand(4);
24182 
24183       if (isAllOnesConstant(Mask))
24184         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
24185 
24186       MVT SrcVT = Src.getSimpleValueType();
24187       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
24188       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24189       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
24190                          PassThru, Mask);
24191 
24192     }
24193     case CVTNEPS2BF16_MASK: {
24194       SDValue Src = Op.getOperand(1);
24195       SDValue PassThru = Op.getOperand(2);
24196       SDValue Mask = Op.getOperand(3);
24197 
24198       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
24199         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
24200 
24201       // Break false dependency.
24202       if (PassThru.isUndef())
24203         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
24204 
24205       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
24206                          Mask);
24207     }
24208     default:
24209       break;
24210     }
24211   }
24212 
24213   switch (IntNo) {
24214   default: return SDValue();    // Don't custom lower most intrinsics.
24215 
24216   // ptest and testp intrinsics. The intrinsic these come from are designed to
24217   // return an integer value, not just an instruction so lower it to the ptest
24218   // or testp pattern and a setcc for the result.
24219   case Intrinsic::x86_avx512_ktestc_b:
24220   case Intrinsic::x86_avx512_ktestc_w:
24221   case Intrinsic::x86_avx512_ktestc_d:
24222   case Intrinsic::x86_avx512_ktestc_q:
24223   case Intrinsic::x86_avx512_ktestz_b:
24224   case Intrinsic::x86_avx512_ktestz_w:
24225   case Intrinsic::x86_avx512_ktestz_d:
24226   case Intrinsic::x86_avx512_ktestz_q:
24227   case Intrinsic::x86_sse41_ptestz:
24228   case Intrinsic::x86_sse41_ptestc:
24229   case Intrinsic::x86_sse41_ptestnzc:
24230   case Intrinsic::x86_avx_ptestz_256:
24231   case Intrinsic::x86_avx_ptestc_256:
24232   case Intrinsic::x86_avx_ptestnzc_256:
24233   case Intrinsic::x86_avx_vtestz_ps:
24234   case Intrinsic::x86_avx_vtestc_ps:
24235   case Intrinsic::x86_avx_vtestnzc_ps:
24236   case Intrinsic::x86_avx_vtestz_pd:
24237   case Intrinsic::x86_avx_vtestc_pd:
24238   case Intrinsic::x86_avx_vtestnzc_pd:
24239   case Intrinsic::x86_avx_vtestz_ps_256:
24240   case Intrinsic::x86_avx_vtestc_ps_256:
24241   case Intrinsic::x86_avx_vtestnzc_ps_256:
24242   case Intrinsic::x86_avx_vtestz_pd_256:
24243   case Intrinsic::x86_avx_vtestc_pd_256:
24244   case Intrinsic::x86_avx_vtestnzc_pd_256: {
24245     unsigned TestOpc = X86ISD::PTEST;
24246     X86::CondCode X86CC;
24247     switch (IntNo) {
24248     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
24249     case Intrinsic::x86_avx512_ktestc_b:
24250     case Intrinsic::x86_avx512_ktestc_w:
24251     case Intrinsic::x86_avx512_ktestc_d:
24252     case Intrinsic::x86_avx512_ktestc_q:
24253       // CF = 1
24254       TestOpc = X86ISD::KTEST;
24255       X86CC = X86::COND_B;
24256       break;
24257     case Intrinsic::x86_avx512_ktestz_b:
24258     case Intrinsic::x86_avx512_ktestz_w:
24259     case Intrinsic::x86_avx512_ktestz_d:
24260     case Intrinsic::x86_avx512_ktestz_q:
24261       TestOpc = X86ISD::KTEST;
24262       X86CC = X86::COND_E;
24263       break;
24264     case Intrinsic::x86_avx_vtestz_ps:
24265     case Intrinsic::x86_avx_vtestz_pd:
24266     case Intrinsic::x86_avx_vtestz_ps_256:
24267     case Intrinsic::x86_avx_vtestz_pd_256:
24268       TestOpc = X86ISD::TESTP;
24269       LLVM_FALLTHROUGH;
24270     case Intrinsic::x86_sse41_ptestz:
24271     case Intrinsic::x86_avx_ptestz_256:
24272       // ZF = 1
24273       X86CC = X86::COND_E;
24274       break;
24275     case Intrinsic::x86_avx_vtestc_ps:
24276     case Intrinsic::x86_avx_vtestc_pd:
24277     case Intrinsic::x86_avx_vtestc_ps_256:
24278     case Intrinsic::x86_avx_vtestc_pd_256:
24279       TestOpc = X86ISD::TESTP;
24280       LLVM_FALLTHROUGH;
24281     case Intrinsic::x86_sse41_ptestc:
24282     case Intrinsic::x86_avx_ptestc_256:
24283       // CF = 1
24284       X86CC = X86::COND_B;
24285       break;
24286     case Intrinsic::x86_avx_vtestnzc_ps:
24287     case Intrinsic::x86_avx_vtestnzc_pd:
24288     case Intrinsic::x86_avx_vtestnzc_ps_256:
24289     case Intrinsic::x86_avx_vtestnzc_pd_256:
24290       TestOpc = X86ISD::TESTP;
24291       LLVM_FALLTHROUGH;
24292     case Intrinsic::x86_sse41_ptestnzc:
24293     case Intrinsic::x86_avx_ptestnzc_256:
24294       // ZF and CF = 0
24295       X86CC = X86::COND_A;
24296       break;
24297     }
24298 
24299     SDValue LHS = Op.getOperand(1);
24300     SDValue RHS = Op.getOperand(2);
24301     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
24302     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
24303     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
24304   }
24305 
24306   case Intrinsic::x86_sse42_pcmpistria128:
24307   case Intrinsic::x86_sse42_pcmpestria128:
24308   case Intrinsic::x86_sse42_pcmpistric128:
24309   case Intrinsic::x86_sse42_pcmpestric128:
24310   case Intrinsic::x86_sse42_pcmpistrio128:
24311   case Intrinsic::x86_sse42_pcmpestrio128:
24312   case Intrinsic::x86_sse42_pcmpistris128:
24313   case Intrinsic::x86_sse42_pcmpestris128:
24314   case Intrinsic::x86_sse42_pcmpistriz128:
24315   case Intrinsic::x86_sse42_pcmpestriz128: {
24316     unsigned Opcode;
24317     X86::CondCode X86CC;
24318     switch (IntNo) {
24319     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
24320     case Intrinsic::x86_sse42_pcmpistria128:
24321       Opcode = X86ISD::PCMPISTR;
24322       X86CC = X86::COND_A;
24323       break;
24324     case Intrinsic::x86_sse42_pcmpestria128:
24325       Opcode = X86ISD::PCMPESTR;
24326       X86CC = X86::COND_A;
24327       break;
24328     case Intrinsic::x86_sse42_pcmpistric128:
24329       Opcode = X86ISD::PCMPISTR;
24330       X86CC = X86::COND_B;
24331       break;
24332     case Intrinsic::x86_sse42_pcmpestric128:
24333       Opcode = X86ISD::PCMPESTR;
24334       X86CC = X86::COND_B;
24335       break;
24336     case Intrinsic::x86_sse42_pcmpistrio128:
24337       Opcode = X86ISD::PCMPISTR;
24338       X86CC = X86::COND_O;
24339       break;
24340     case Intrinsic::x86_sse42_pcmpestrio128:
24341       Opcode = X86ISD::PCMPESTR;
24342       X86CC = X86::COND_O;
24343       break;
24344     case Intrinsic::x86_sse42_pcmpistris128:
24345       Opcode = X86ISD::PCMPISTR;
24346       X86CC = X86::COND_S;
24347       break;
24348     case Intrinsic::x86_sse42_pcmpestris128:
24349       Opcode = X86ISD::PCMPESTR;
24350       X86CC = X86::COND_S;
24351       break;
24352     case Intrinsic::x86_sse42_pcmpistriz128:
24353       Opcode = X86ISD::PCMPISTR;
24354       X86CC = X86::COND_E;
24355       break;
24356     case Intrinsic::x86_sse42_pcmpestriz128:
24357       Opcode = X86ISD::PCMPESTR;
24358       X86CC = X86::COND_E;
24359       break;
24360     }
24361     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
24362     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
24363     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
24364     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
24365     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
24366   }
24367 
24368   case Intrinsic::x86_sse42_pcmpistri128:
24369   case Intrinsic::x86_sse42_pcmpestri128: {
24370     unsigned Opcode;
24371     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
24372       Opcode = X86ISD::PCMPISTR;
24373     else
24374       Opcode = X86ISD::PCMPESTR;
24375 
24376     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
24377     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
24378     return DAG.getNode(Opcode, dl, VTs, NewOps);
24379   }
24380 
24381   case Intrinsic::x86_sse42_pcmpistrm128:
24382   case Intrinsic::x86_sse42_pcmpestrm128: {
24383     unsigned Opcode;
24384     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
24385       Opcode = X86ISD::PCMPISTR;
24386     else
24387       Opcode = X86ISD::PCMPESTR;
24388 
24389     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
24390     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
24391     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
24392   }
24393 
24394   case Intrinsic::eh_sjlj_lsda: {
24395     MachineFunction &MF = DAG.getMachineFunction();
24396     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24397     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24398     auto &Context = MF.getMMI().getContext();
24399     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
24400                                             Twine(MF.getFunctionNumber()));
24401     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
24402                        DAG.getMCSymbol(S, PtrVT));
24403   }
24404 
24405   case Intrinsic::x86_seh_lsda: {
24406     // Compute the symbol for the LSDA. We know it'll get emitted later.
24407     MachineFunction &MF = DAG.getMachineFunction();
24408     SDValue Op1 = Op.getOperand(1);
24409     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
24410     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
24411         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
24412 
24413     // Generate a simple absolute symbol reference. This intrinsic is only
24414     // supported on 32-bit Windows, which isn't PIC.
24415     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
24416     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
24417   }
24418 
24419   case Intrinsic::eh_recoverfp: {
24420     SDValue FnOp = Op.getOperand(1);
24421     SDValue IncomingFPOp = Op.getOperand(2);
24422     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
24423     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
24424     if (!Fn)
24425       report_fatal_error(
24426           "llvm.eh.recoverfp must take a function as the first argument");
24427     return recoverFramePointer(DAG, Fn, IncomingFPOp);
24428   }
24429 
24430   case Intrinsic::localaddress: {
24431     // Returns one of the stack, base, or frame pointer registers, depending on
24432     // which is used to reference local variables.
24433     MachineFunction &MF = DAG.getMachineFunction();
24434     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
24435     unsigned Reg;
24436     if (RegInfo->hasBasePointer(MF))
24437       Reg = RegInfo->getBaseRegister();
24438     else { // Handles the SP or FP case.
24439       bool CantUseFP = RegInfo->needsStackRealignment(MF);
24440       if (CantUseFP)
24441         Reg = RegInfo->getPtrSizedStackRegister(MF);
24442       else
24443         Reg = RegInfo->getPtrSizedFrameRegister(MF);
24444     }
24445     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
24446   }
24447 
24448   case Intrinsic::x86_avx512_vp2intersect_q_512:
24449   case Intrinsic::x86_avx512_vp2intersect_q_256:
24450   case Intrinsic::x86_avx512_vp2intersect_q_128:
24451   case Intrinsic::x86_avx512_vp2intersect_d_512:
24452   case Intrinsic::x86_avx512_vp2intersect_d_256:
24453   case Intrinsic::x86_avx512_vp2intersect_d_128: {
24454     MVT MaskVT = Op.getSimpleValueType();
24455 
24456     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
24457     SDLoc DL(Op);
24458 
24459     SDValue Operation =
24460         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
24461                     Op->getOperand(1), Op->getOperand(2));
24462 
24463     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
24464                                                  MaskVT, Operation);
24465     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
24466                                                  MaskVT, Operation);
24467     return DAG.getMergeValues({Result0, Result1}, DL);
24468   }
24469   case Intrinsic::x86_mmx_pslli_w:
24470   case Intrinsic::x86_mmx_pslli_d:
24471   case Intrinsic::x86_mmx_pslli_q:
24472   case Intrinsic::x86_mmx_psrli_w:
24473   case Intrinsic::x86_mmx_psrli_d:
24474   case Intrinsic::x86_mmx_psrli_q:
24475   case Intrinsic::x86_mmx_psrai_w:
24476   case Intrinsic::x86_mmx_psrai_d: {
24477     SDLoc DL(Op);
24478     SDValue ShAmt = Op.getOperand(2);
24479     // If the argument is a constant, convert it to a target constant.
24480     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
24481       // Clamp out of bounds shift amounts since they will otherwise be masked
24482       // to 8-bits which may make it no longer out of bounds.
24483       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
24484       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
24485                          Op.getOperand(0), Op.getOperand(1),
24486                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
24487     }
24488 
24489     unsigned NewIntrinsic;
24490     switch (IntNo) {
24491     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
24492     case Intrinsic::x86_mmx_pslli_w:
24493       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
24494       break;
24495     case Intrinsic::x86_mmx_pslli_d:
24496       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
24497       break;
24498     case Intrinsic::x86_mmx_pslli_q:
24499       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
24500       break;
24501     case Intrinsic::x86_mmx_psrli_w:
24502       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
24503       break;
24504     case Intrinsic::x86_mmx_psrli_d:
24505       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
24506       break;
24507     case Intrinsic::x86_mmx_psrli_q:
24508       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
24509       break;
24510     case Intrinsic::x86_mmx_psrai_w:
24511       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
24512       break;
24513     case Intrinsic::x86_mmx_psrai_d:
24514       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
24515       break;
24516     }
24517 
24518     // The vector shift intrinsics with scalars uses 32b shift amounts but
24519     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
24520     // MMX register.
24521     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
24522     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
24523                        DAG.getConstant(NewIntrinsic, DL, MVT::i32),
24524                        Op.getOperand(1), ShAmt);
24525 
24526   }
24527   }
24528 }
24529 
getAVX2GatherNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)24530 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
24531                                  SDValue Src, SDValue Mask, SDValue Base,
24532                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
24533                                  const X86Subtarget &Subtarget) {
24534   SDLoc dl(Op);
24535   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
24536   // Scale must be constant.
24537   if (!C)
24538     return SDValue();
24539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24540   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
24541                                         TLI.getPointerTy(DAG.getDataLayout()));
24542   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
24543   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
24544   // If source is undef or we know it won't be used, use a zero vector
24545   // to break register dependency.
24546   // TODO: use undef instead and let BreakFalseDeps deal with it?
24547   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
24548     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
24549 
24550   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
24551 
24552   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
24553   SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
24554     VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
24555   return DAG.getMergeValues({ Res, Res.getValue(2) }, dl);
24556 }
24557 
getGatherNode(SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)24558 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
24559                              SDValue Src, SDValue Mask, SDValue Base,
24560                              SDValue Index, SDValue ScaleOp, SDValue Chain,
24561                              const X86Subtarget &Subtarget) {
24562   MVT VT = Op.getSimpleValueType();
24563   SDLoc dl(Op);
24564   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
24565   // Scale must be constant.
24566   if (!C)
24567     return SDValue();
24568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24569   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
24570                                         TLI.getPointerTy(DAG.getDataLayout()));
24571   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
24572                               VT.getVectorNumElements());
24573   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
24574 
24575   // We support two versions of the gather intrinsics. One with scalar mask and
24576   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
24577   if (Mask.getValueType() != MaskVT)
24578     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24579 
24580   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
24581   // If source is undef or we know it won't be used, use a zero vector
24582   // to break register dependency.
24583   // TODO: use undef instead and let BreakFalseDeps deal with it?
24584   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
24585     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
24586 
24587   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
24588 
24589   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
24590   SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
24591     VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
24592   return DAG.getMergeValues({ Res, Res.getValue(2) }, dl);
24593 }
24594 
getScatterNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)24595 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
24596                                SDValue Src, SDValue Mask, SDValue Base,
24597                                SDValue Index, SDValue ScaleOp, SDValue Chain,
24598                                const X86Subtarget &Subtarget) {
24599   SDLoc dl(Op);
24600   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
24601   // Scale must be constant.
24602   if (!C)
24603     return SDValue();
24604   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24605   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
24606                                         TLI.getPointerTy(DAG.getDataLayout()));
24607   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
24608                               Src.getSimpleValueType().getVectorNumElements());
24609   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
24610 
24611   // We support two versions of the scatter intrinsics. One with scalar mask and
24612   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
24613   if (Mask.getValueType() != MaskVT)
24614     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24615 
24616   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
24617 
24618   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
24619   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
24620   SDValue Res = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
24621       VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
24622   return Res.getValue(1);
24623 }
24624 
getPrefetchNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)24625 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
24626                                SDValue Mask, SDValue Base, SDValue Index,
24627                                SDValue ScaleOp, SDValue Chain,
24628                                const X86Subtarget &Subtarget) {
24629   SDLoc dl(Op);
24630   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
24631   // Scale must be constant.
24632   if (!C)
24633     return SDValue();
24634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24635   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
24636                                         TLI.getPointerTy(DAG.getDataLayout()));
24637   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
24638   SDValue Segment = DAG.getRegister(0, MVT::i32);
24639   MVT MaskVT =
24640     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
24641   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24642   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
24643   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
24644   return SDValue(Res, 0);
24645 }
24646 
24647 /// Handles the lowering of builtin intrinsics with chain that return their
24648 /// value into registers EDX:EAX.
24649 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
24650 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
24651 /// TargetOpcode.
24652 /// Returns a Glue value which can be used to add extra copy-from-reg if the
24653 /// expanded intrinsics implicitly defines extra registers (i.e. not just
24654 /// EDX:EAX).
expandIntrinsicWChainHelper(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,unsigned TargetOpcode,unsigned SrcReg,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)24655 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
24656                                         SelectionDAG &DAG,
24657                                         unsigned TargetOpcode,
24658                                         unsigned SrcReg,
24659                                         const X86Subtarget &Subtarget,
24660                                         SmallVectorImpl<SDValue> &Results) {
24661   SDValue Chain = N->getOperand(0);
24662   SDValue Glue;
24663 
24664   if (SrcReg) {
24665     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
24666     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
24667     Glue = Chain.getValue(1);
24668   }
24669 
24670   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
24671   SDValue N1Ops[] = {Chain, Glue};
24672   SDNode *N1 = DAG.getMachineNode(
24673       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
24674   Chain = SDValue(N1, 0);
24675 
24676   // Reads the content of XCR and returns it in registers EDX:EAX.
24677   SDValue LO, HI;
24678   if (Subtarget.is64Bit()) {
24679     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
24680     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
24681                             LO.getValue(2));
24682   } else {
24683     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
24684     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
24685                             LO.getValue(2));
24686   }
24687   Chain = HI.getValue(1);
24688   Glue = HI.getValue(2);
24689 
24690   if (Subtarget.is64Bit()) {
24691     // Merge the two 32-bit values into a 64-bit one.
24692     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
24693                               DAG.getConstant(32, DL, MVT::i8));
24694     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
24695     Results.push_back(Chain);
24696     return Glue;
24697   }
24698 
24699   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
24700   SDValue Ops[] = { LO, HI };
24701   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
24702   Results.push_back(Pair);
24703   Results.push_back(Chain);
24704   return Glue;
24705 }
24706 
24707 /// Handles the lowering of builtin intrinsics that read the time stamp counter
24708 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
24709 /// READCYCLECOUNTER nodes.
getReadTimeStampCounter(SDNode * N,const SDLoc & DL,unsigned Opcode,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)24710 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
24711                                     SelectionDAG &DAG,
24712                                     const X86Subtarget &Subtarget,
24713                                     SmallVectorImpl<SDValue> &Results) {
24714   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
24715   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
24716   // and the EAX register is loaded with the low-order 32 bits.
24717   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
24718                                              /* NoRegister */0, Subtarget,
24719                                              Results);
24720   if (Opcode != X86::RDTSCP)
24721     return;
24722 
24723   SDValue Chain = Results[1];
24724   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
24725   // the ECX register. Add 'ecx' explicitly to the chain.
24726   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
24727   Results[1] = ecx;
24728   Results.push_back(ecx.getValue(1));
24729 }
24730 
LowerREADCYCLECOUNTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24731 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
24732                                      SelectionDAG &DAG) {
24733   SmallVector<SDValue, 3> Results;
24734   SDLoc DL(Op);
24735   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
24736                           Results);
24737   return DAG.getMergeValues(Results, DL);
24738 }
24739 
MarkEHRegistrationNode(SDValue Op,SelectionDAG & DAG)24740 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
24741   MachineFunction &MF = DAG.getMachineFunction();
24742   SDValue Chain = Op.getOperand(0);
24743   SDValue RegNode = Op.getOperand(2);
24744   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
24745   if (!EHInfo)
24746     report_fatal_error("EH registrations only live in functions using WinEH");
24747 
24748   // Cast the operand to an alloca, and remember the frame index.
24749   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
24750   if (!FINode)
24751     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
24752   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
24753 
24754   // Return the chain operand without making any DAG nodes.
24755   return Chain;
24756 }
24757 
MarkEHGuard(SDValue Op,SelectionDAG & DAG)24758 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
24759   MachineFunction &MF = DAG.getMachineFunction();
24760   SDValue Chain = Op.getOperand(0);
24761   SDValue EHGuard = Op.getOperand(2);
24762   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
24763   if (!EHInfo)
24764     report_fatal_error("EHGuard only live in functions using WinEH");
24765 
24766   // Cast the operand to an alloca, and remember the frame index.
24767   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
24768   if (!FINode)
24769     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
24770   EHInfo->EHGuardFrameIndex = FINode->getIndex();
24771 
24772   // Return the chain operand without making any DAG nodes.
24773   return Chain;
24774 }
24775 
24776 /// Emit Truncating Store with signed or unsigned saturation.
24777 static SDValue
EmitTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)24778 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
24779                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
24780                 SelectionDAG &DAG) {
24781 
24782   SDVTList VTs = DAG.getVTList(MVT::Other);
24783   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
24784   SDValue Ops[] = { Chain, Val, Ptr, Undef };
24785   return SignedSat ?
24786     DAG.getTargetMemSDNode<TruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
24787     DAG.getTargetMemSDNode<TruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
24788 }
24789 
24790 /// Emit Masked Truncating Store with signed or unsigned saturation.
24791 static SDValue
EmitMaskedTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,SDValue Mask,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)24792 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
24793                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
24794                       MachineMemOperand *MMO, SelectionDAG &DAG) {
24795 
24796   SDVTList VTs = DAG.getVTList(MVT::Other);
24797   SDValue Ops[] = { Chain, Val, Ptr, Mask };
24798   return SignedSat ?
24799     DAG.getTargetMemSDNode<MaskedTruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
24800     DAG.getTargetMemSDNode<MaskedTruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
24801 }
24802 
LowerINTRINSIC_W_CHAIN(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24803 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
24804                                       SelectionDAG &DAG) {
24805   unsigned IntNo = Op.getConstantOperandVal(1);
24806   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
24807   if (!IntrData) {
24808     switch (IntNo) {
24809     case llvm::Intrinsic::x86_seh_ehregnode:
24810       return MarkEHRegistrationNode(Op, DAG);
24811     case llvm::Intrinsic::x86_seh_ehguard:
24812       return MarkEHGuard(Op, DAG);
24813     case llvm::Intrinsic::x86_rdpkru: {
24814       SDLoc dl(Op);
24815       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
24816       // Create a RDPKRU node and pass 0 to the ECX parameter.
24817       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
24818                          DAG.getConstant(0, dl, MVT::i32));
24819     }
24820     case llvm::Intrinsic::x86_wrpkru: {
24821       SDLoc dl(Op);
24822       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
24823       // to the EDX and ECX parameters.
24824       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
24825                          Op.getOperand(0), Op.getOperand(2),
24826                          DAG.getConstant(0, dl, MVT::i32),
24827                          DAG.getConstant(0, dl, MVT::i32));
24828     }
24829     case llvm::Intrinsic::x86_flags_read_u32:
24830     case llvm::Intrinsic::x86_flags_read_u64:
24831     case llvm::Intrinsic::x86_flags_write_u32:
24832     case llvm::Intrinsic::x86_flags_write_u64: {
24833       // We need a frame pointer because this will get lowered to a PUSH/POP
24834       // sequence.
24835       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
24836       MFI.setHasCopyImplyingStackAdjustment(true);
24837       // Don't do anything here, we will expand these intrinsics out later
24838       // during FinalizeISel in EmitInstrWithCustomInserter.
24839       return Op;
24840     }
24841     case Intrinsic::x86_lwpins32:
24842     case Intrinsic::x86_lwpins64:
24843     case Intrinsic::x86_umwait:
24844     case Intrinsic::x86_tpause: {
24845       SDLoc dl(Op);
24846       SDValue Chain = Op->getOperand(0);
24847       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
24848       unsigned Opcode;
24849 
24850       switch (IntNo) {
24851       default: llvm_unreachable("Impossible intrinsic");
24852       case Intrinsic::x86_umwait:
24853         Opcode = X86ISD::UMWAIT;
24854         break;
24855       case Intrinsic::x86_tpause:
24856         Opcode = X86ISD::TPAUSE;
24857         break;
24858       case Intrinsic::x86_lwpins32:
24859       case Intrinsic::x86_lwpins64:
24860         Opcode = X86ISD::LWPINS;
24861         break;
24862       }
24863 
24864       SDValue Operation =
24865           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
24866                       Op->getOperand(3), Op->getOperand(4));
24867       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
24868       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
24869                          Operation.getValue(1));
24870     }
24871     case Intrinsic::x86_enqcmd:
24872     case Intrinsic::x86_enqcmds: {
24873       SDLoc dl(Op);
24874       SDValue Chain = Op.getOperand(0);
24875       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
24876       unsigned Opcode;
24877       switch (IntNo) {
24878       default: llvm_unreachable("Impossible intrinsic!");
24879       case Intrinsic::x86_enqcmd:
24880         Opcode = X86ISD::ENQCMD;
24881         break;
24882       case Intrinsic::x86_enqcmds:
24883         Opcode = X86ISD::ENQCMDS;
24884         break;
24885       }
24886       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
24887                                       Op.getOperand(3));
24888       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
24889       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
24890                          Operation.getValue(1));
24891     }
24892     }
24893     return SDValue();
24894   }
24895 
24896   SDLoc dl(Op);
24897   switch(IntrData->Type) {
24898   default: llvm_unreachable("Unknown Intrinsic Type");
24899   case RDSEED:
24900   case RDRAND: {
24901     // Emit the node with the right value type.
24902     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
24903     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
24904 
24905     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
24906     // Otherwise return the value from Rand, which is always 0, casted to i32.
24907     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
24908                      DAG.getConstant(1, dl, Op->getValueType(1)),
24909                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
24910                      SDValue(Result.getNode(), 1)};
24911     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
24912 
24913     // Return { result, isValid, chain }.
24914     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
24915                        SDValue(Result.getNode(), 2));
24916   }
24917   case GATHER_AVX2: {
24918     SDValue Chain = Op.getOperand(0);
24919     SDValue Src   = Op.getOperand(2);
24920     SDValue Base  = Op.getOperand(3);
24921     SDValue Index = Op.getOperand(4);
24922     SDValue Mask  = Op.getOperand(5);
24923     SDValue Scale = Op.getOperand(6);
24924     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
24925                              Scale, Chain, Subtarget);
24926   }
24927   case GATHER: {
24928   //gather(v1, mask, index, base, scale);
24929     SDValue Chain = Op.getOperand(0);
24930     SDValue Src   = Op.getOperand(2);
24931     SDValue Base  = Op.getOperand(3);
24932     SDValue Index = Op.getOperand(4);
24933     SDValue Mask  = Op.getOperand(5);
24934     SDValue Scale = Op.getOperand(6);
24935     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
24936                          Chain, Subtarget);
24937   }
24938   case SCATTER: {
24939   //scatter(base, mask, index, v1, scale);
24940     SDValue Chain = Op.getOperand(0);
24941     SDValue Base  = Op.getOperand(2);
24942     SDValue Mask  = Op.getOperand(3);
24943     SDValue Index = Op.getOperand(4);
24944     SDValue Src   = Op.getOperand(5);
24945     SDValue Scale = Op.getOperand(6);
24946     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
24947                           Scale, Chain, Subtarget);
24948   }
24949   case PREFETCH: {
24950     const APInt &HintVal = Op.getConstantOperandAPInt(6);
24951     assert((HintVal == 2 || HintVal == 3) &&
24952            "Wrong prefetch hint in intrinsic: should be 2 or 3");
24953     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
24954     SDValue Chain = Op.getOperand(0);
24955     SDValue Mask  = Op.getOperand(2);
24956     SDValue Index = Op.getOperand(3);
24957     SDValue Base  = Op.getOperand(4);
24958     SDValue Scale = Op.getOperand(5);
24959     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
24960                            Subtarget);
24961   }
24962   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
24963   case RDTSC: {
24964     SmallVector<SDValue, 2> Results;
24965     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
24966                             Results);
24967     return DAG.getMergeValues(Results, dl);
24968   }
24969   // Read Performance Monitoring Counters.
24970   case RDPMC:
24971   // GetExtended Control Register.
24972   case XGETBV: {
24973     SmallVector<SDValue, 2> Results;
24974 
24975     // RDPMC uses ECX to select the index of the performance counter to read.
24976     // XGETBV uses ECX to select the index of the XCR register to return.
24977     // The result is stored into registers EDX:EAX.
24978     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
24979                                 Subtarget, Results);
24980     return DAG.getMergeValues(Results, dl);
24981   }
24982   // XTEST intrinsics.
24983   case XTEST: {
24984     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
24985     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
24986 
24987     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
24988     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
24989     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
24990                        Ret, SDValue(InTrans.getNode(), 1));
24991   }
24992   case TRUNCATE_TO_MEM_VI8:
24993   case TRUNCATE_TO_MEM_VI16:
24994   case TRUNCATE_TO_MEM_VI32: {
24995     SDValue Mask = Op.getOperand(4);
24996     SDValue DataToTruncate = Op.getOperand(3);
24997     SDValue Addr = Op.getOperand(2);
24998     SDValue Chain = Op.getOperand(0);
24999 
25000     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
25001     assert(MemIntr && "Expected MemIntrinsicSDNode!");
25002 
25003     EVT MemVT  = MemIntr->getMemoryVT();
25004 
25005     uint16_t TruncationOp = IntrData->Opc0;
25006     switch (TruncationOp) {
25007     case X86ISD::VTRUNC: {
25008       if (isAllOnesConstant(Mask)) // return just a truncate store
25009         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
25010                                  MemIntr->getMemOperand());
25011 
25012       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
25013       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25014       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
25015 
25016       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
25017                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
25018                                 true /* truncating */);
25019     }
25020     case X86ISD::VTRUNCUS:
25021     case X86ISD::VTRUNCS: {
25022       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
25023       if (isAllOnesConstant(Mask))
25024         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
25025                                MemIntr->getMemOperand(), DAG);
25026 
25027       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
25028       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25029 
25030       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
25031                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
25032     }
25033     default:
25034       llvm_unreachable("Unsupported truncstore intrinsic");
25035     }
25036   }
25037   }
25038 }
25039 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const25040 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
25041                                            SelectionDAG &DAG) const {
25042   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
25043   MFI.setReturnAddressIsTaken(true);
25044 
25045   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
25046     return SDValue();
25047 
25048   unsigned Depth = Op.getConstantOperandVal(0);
25049   SDLoc dl(Op);
25050   EVT PtrVT = getPointerTy(DAG.getDataLayout());
25051 
25052   if (Depth > 0) {
25053     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
25054     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25055     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
25056     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
25057                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
25058                        MachinePointerInfo());
25059   }
25060 
25061   // Just load the return address.
25062   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
25063   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
25064                      MachinePointerInfo());
25065 }
25066 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const25067 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
25068                                                  SelectionDAG &DAG) const {
25069   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
25070   return getReturnAddressFrameIndex(DAG);
25071 }
25072 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const25073 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
25074   MachineFunction &MF = DAG.getMachineFunction();
25075   MachineFrameInfo &MFI = MF.getFrameInfo();
25076   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
25077   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25078   EVT VT = Op.getValueType();
25079 
25080   MFI.setFrameAddressIsTaken(true);
25081 
25082   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
25083     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
25084     // is not possible to crawl up the stack without looking at the unwind codes
25085     // simultaneously.
25086     int FrameAddrIndex = FuncInfo->getFAIndex();
25087     if (!FrameAddrIndex) {
25088       // Set up a frame object for the return address.
25089       unsigned SlotSize = RegInfo->getSlotSize();
25090       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
25091           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
25092       FuncInfo->setFAIndex(FrameAddrIndex);
25093     }
25094     return DAG.getFrameIndex(FrameAddrIndex, VT);
25095   }
25096 
25097   unsigned FrameReg =
25098       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
25099   SDLoc dl(Op);  // FIXME probably not meaningful
25100   unsigned Depth = Op.getConstantOperandVal(0);
25101   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
25102           (FrameReg == X86::EBP && VT == MVT::i32)) &&
25103          "Invalid Frame Register!");
25104   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
25105   while (Depth--)
25106     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
25107                             MachinePointerInfo());
25108   return FrameAddr;
25109 }
25110 
25111 // FIXME? Maybe this could be a TableGen attribute on some registers and
25112 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const25113 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
25114                                               const MachineFunction &MF) const {
25115   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25116 
25117   Register Reg = StringSwitch<unsigned>(RegName)
25118                        .Case("esp", X86::ESP)
25119                        .Case("rsp", X86::RSP)
25120                        .Case("ebp", X86::EBP)
25121                        .Case("rbp", X86::RBP)
25122                        .Default(0);
25123 
25124   if (Reg == X86::EBP || Reg == X86::RBP) {
25125     if (!TFI.hasFP(MF))
25126       report_fatal_error("register " + StringRef(RegName) +
25127                          " is allocatable: function has no frame pointer");
25128 #ifndef NDEBUG
25129     else {
25130       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25131       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
25132       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
25133              "Invalid Frame Register!");
25134     }
25135 #endif
25136   }
25137 
25138   if (Reg)
25139     return Reg;
25140 
25141   report_fatal_error("Invalid register name global variable");
25142 }
25143 
LowerFRAME_TO_ARGS_OFFSET(SDValue Op,SelectionDAG & DAG) const25144 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
25145                                                      SelectionDAG &DAG) const {
25146   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25147   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
25148 }
25149 
getExceptionPointerRegister(const Constant * PersonalityFn) const25150 unsigned X86TargetLowering::getExceptionPointerRegister(
25151     const Constant *PersonalityFn) const {
25152   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
25153     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
25154 
25155   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
25156 }
25157 
getExceptionSelectorRegister(const Constant * PersonalityFn) const25158 unsigned X86TargetLowering::getExceptionSelectorRegister(
25159     const Constant *PersonalityFn) const {
25160   // Funclet personalities don't use selectors (the runtime does the selection).
25161   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
25162   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
25163 }
25164 
needsFixedCatchObjects() const25165 bool X86TargetLowering::needsFixedCatchObjects() const {
25166   return Subtarget.isTargetWin64();
25167 }
25168 
LowerEH_RETURN(SDValue Op,SelectionDAG & DAG) const25169 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
25170   SDValue Chain     = Op.getOperand(0);
25171   SDValue Offset    = Op.getOperand(1);
25172   SDValue Handler   = Op.getOperand(2);
25173   SDLoc dl      (Op);
25174 
25175   EVT PtrVT = getPointerTy(DAG.getDataLayout());
25176   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25177   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
25178   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
25179           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
25180          "Invalid Frame Register!");
25181   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
25182   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
25183 
25184   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
25185                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
25186                                                        dl));
25187   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
25188   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
25189   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
25190 
25191   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
25192                      DAG.getRegister(StoreAddrReg, PtrVT));
25193 }
25194 
lowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const25195 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
25196                                                SelectionDAG &DAG) const {
25197   SDLoc DL(Op);
25198   // If the subtarget is not 64bit, we may need the global base reg
25199   // after isel expand pseudo, i.e., after CGBR pass ran.
25200   // Therefore, ask for the GlobalBaseReg now, so that the pass
25201   // inserts the code for us in case we need it.
25202   // Otherwise, we will end up in a situation where we will
25203   // reference a virtual register that is not defined!
25204   if (!Subtarget.is64Bit()) {
25205     const X86InstrInfo *TII = Subtarget.getInstrInfo();
25206     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
25207   }
25208   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
25209                      DAG.getVTList(MVT::i32, MVT::Other),
25210                      Op.getOperand(0), Op.getOperand(1));
25211 }
25212 
lowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const25213 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
25214                                                 SelectionDAG &DAG) const {
25215   SDLoc DL(Op);
25216   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
25217                      Op.getOperand(0), Op.getOperand(1));
25218 }
25219 
lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const25220 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
25221                                                        SelectionDAG &DAG) const {
25222   SDLoc DL(Op);
25223   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
25224                      Op.getOperand(0));
25225 }
25226 
LowerADJUST_TRAMPOLINE(SDValue Op,SelectionDAG & DAG)25227 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
25228   return Op.getOperand(0);
25229 }
25230 
LowerINIT_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const25231 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
25232                                                 SelectionDAG &DAG) const {
25233   SDValue Root = Op.getOperand(0);
25234   SDValue Trmp = Op.getOperand(1); // trampoline
25235   SDValue FPtr = Op.getOperand(2); // nested function
25236   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
25237   SDLoc dl (Op);
25238 
25239   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
25240   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
25241 
25242   if (Subtarget.is64Bit()) {
25243     SDValue OutChains[6];
25244 
25245     // Large code-model.
25246     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
25247     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
25248 
25249     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
25250     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
25251 
25252     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
25253 
25254     // Load the pointer to the nested function into R11.
25255     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
25256     SDValue Addr = Trmp;
25257     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
25258                                 Addr, MachinePointerInfo(TrmpAddr));
25259 
25260     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
25261                        DAG.getConstant(2, dl, MVT::i64));
25262     OutChains[1] =
25263         DAG.getStore(Root, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 2),
25264                      /* Alignment = */ 2);
25265 
25266     // Load the 'nest' parameter value into R10.
25267     // R10 is specified in X86CallingConv.td
25268     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
25269     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
25270                        DAG.getConstant(10, dl, MVT::i64));
25271     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
25272                                 Addr, MachinePointerInfo(TrmpAddr, 10));
25273 
25274     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
25275                        DAG.getConstant(12, dl, MVT::i64));
25276     OutChains[3] =
25277         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12),
25278                      /* Alignment = */ 2);
25279 
25280     // Jump to the nested function.
25281     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
25282     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
25283                        DAG.getConstant(20, dl, MVT::i64));
25284     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
25285                                 Addr, MachinePointerInfo(TrmpAddr, 20));
25286 
25287     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
25288     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
25289                        DAG.getConstant(22, dl, MVT::i64));
25290     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
25291                                 Addr, MachinePointerInfo(TrmpAddr, 22));
25292 
25293     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
25294   } else {
25295     const Function *Func =
25296       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
25297     CallingConv::ID CC = Func->getCallingConv();
25298     unsigned NestReg;
25299 
25300     switch (CC) {
25301     default:
25302       llvm_unreachable("Unsupported calling convention");
25303     case CallingConv::C:
25304     case CallingConv::X86_StdCall: {
25305       // Pass 'nest' parameter in ECX.
25306       // Must be kept in sync with X86CallingConv.td
25307       NestReg = X86::ECX;
25308 
25309       // Check that ECX wasn't needed by an 'inreg' parameter.
25310       FunctionType *FTy = Func->getFunctionType();
25311       const AttributeList &Attrs = Func->getAttributes();
25312 
25313       if (!Attrs.isEmpty() && !Func->isVarArg()) {
25314         unsigned InRegCount = 0;
25315         unsigned Idx = 1;
25316 
25317         for (FunctionType::param_iterator I = FTy->param_begin(),
25318              E = FTy->param_end(); I != E; ++I, ++Idx)
25319           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
25320             auto &DL = DAG.getDataLayout();
25321             // FIXME: should only count parameters that are lowered to integers.
25322             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
25323           }
25324 
25325         if (InRegCount > 2) {
25326           report_fatal_error("Nest register in use - reduce number of inreg"
25327                              " parameters!");
25328         }
25329       }
25330       break;
25331     }
25332     case CallingConv::X86_FastCall:
25333     case CallingConv::X86_ThisCall:
25334     case CallingConv::Fast:
25335     case CallingConv::Tail:
25336       // Pass 'nest' parameter in EAX.
25337       // Must be kept in sync with X86CallingConv.td
25338       NestReg = X86::EAX;
25339       break;
25340     }
25341 
25342     SDValue OutChains[4];
25343     SDValue Addr, Disp;
25344 
25345     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
25346                        DAG.getConstant(10, dl, MVT::i32));
25347     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
25348 
25349     // This is storing the opcode for MOV32ri.
25350     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
25351     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
25352     OutChains[0] =
25353         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
25354                      Trmp, MachinePointerInfo(TrmpAddr));
25355 
25356     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
25357                        DAG.getConstant(1, dl, MVT::i32));
25358     OutChains[1] =
25359         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 1),
25360                      /* Alignment = */ 1);
25361 
25362     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
25363     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
25364                        DAG.getConstant(5, dl, MVT::i32));
25365     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
25366                                 Addr, MachinePointerInfo(TrmpAddr, 5),
25367                                 /* Alignment = */ 1);
25368 
25369     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
25370                        DAG.getConstant(6, dl, MVT::i32));
25371     OutChains[3] =
25372         DAG.getStore(Root, dl, Disp, Addr, MachinePointerInfo(TrmpAddr, 6),
25373                      /* Alignment = */ 1);
25374 
25375     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
25376   }
25377 }
25378 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const25379 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
25380                                             SelectionDAG &DAG) const {
25381   /*
25382    The rounding mode is in bits 11:10 of FPSR, and has the following
25383    settings:
25384      00 Round to nearest
25385      01 Round to -inf
25386      10 Round to +inf
25387      11 Round to 0
25388 
25389   FLT_ROUNDS, on the other hand, expects the following:
25390     -1 Undefined
25391      0 Round to 0
25392      1 Round to nearest
25393      2 Round to +inf
25394      3 Round to -inf
25395 
25396   To perform the conversion, we do:
25397     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
25398   */
25399 
25400   MachineFunction &MF = DAG.getMachineFunction();
25401   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25402   const Align StackAlignment(TFI.getStackAlignment());
25403   MVT VT = Op.getSimpleValueType();
25404   SDLoc DL(Op);
25405 
25406   // Save FP Control Word to stack slot
25407   int SSFI =
25408       MF.getFrameInfo().CreateStackObject(2, StackAlignment.value(), false);
25409   SDValue StackSlot =
25410       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
25411 
25412   MachineMemOperand *MMO =
25413       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
25414                               MachineMemOperand::MOStore, 2, 2);
25415 
25416   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
25417   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
25418                                           DAG.getVTList(MVT::Other),
25419                                           Ops, MVT::i16, MMO);
25420 
25421   // Load FP Control Word from stack slot
25422   SDValue CWD =
25423       DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MachinePointerInfo());
25424 
25425   // Transform as necessary
25426   SDValue CWD1 =
25427     DAG.getNode(ISD::SRL, DL, MVT::i16,
25428                 DAG.getNode(ISD::AND, DL, MVT::i16,
25429                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
25430                 DAG.getConstant(11, DL, MVT::i8));
25431   SDValue CWD2 =
25432     DAG.getNode(ISD::SRL, DL, MVT::i16,
25433                 DAG.getNode(ISD::AND, DL, MVT::i16,
25434                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
25435                 DAG.getConstant(9, DL, MVT::i8));
25436 
25437   SDValue RetVal =
25438     DAG.getNode(ISD::AND, DL, MVT::i16,
25439                 DAG.getNode(ISD::ADD, DL, MVT::i16,
25440                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
25441                             DAG.getConstant(1, DL, MVT::i16)),
25442                 DAG.getConstant(3, DL, MVT::i16));
25443 
25444   return DAG.getNode((VT.getSizeInBits() < 16 ?
25445                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
25446 }
25447 
25448 // Split an unary integer op into 2 half sized ops.
LowerVectorIntUnary(SDValue Op,SelectionDAG & DAG)25449 static SDValue LowerVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
25450   MVT VT = Op.getSimpleValueType();
25451   unsigned NumElems = VT.getVectorNumElements();
25452   unsigned SizeInBits = VT.getSizeInBits();
25453   MVT EltVT = VT.getVectorElementType();
25454   SDValue Src = Op.getOperand(0);
25455   assert(EltVT == Src.getSimpleValueType().getVectorElementType() &&
25456          "Src and Op should have the same element type!");
25457 
25458   // Extract the Lo/Hi vectors
25459   SDLoc dl(Op);
25460   SDValue Lo = extractSubVector(Src, 0, DAG, dl, SizeInBits / 2);
25461   SDValue Hi = extractSubVector(Src, NumElems / 2, DAG, dl, SizeInBits / 2);
25462 
25463   MVT NewVT = MVT::getVectorVT(EltVT, NumElems / 2);
25464   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
25465                      DAG.getNode(Op.getOpcode(), dl, NewVT, Lo),
25466                      DAG.getNode(Op.getOpcode(), dl, NewVT, Hi));
25467 }
25468 
25469 // Decompose 256-bit ops into smaller 128-bit ops.
Lower256IntUnary(SDValue Op,SelectionDAG & DAG)25470 static SDValue Lower256IntUnary(SDValue Op, SelectionDAG &DAG) {
25471   assert(Op.getSimpleValueType().is256BitVector() &&
25472          Op.getSimpleValueType().isInteger() &&
25473          "Only handle AVX 256-bit vector integer operation");
25474   return LowerVectorIntUnary(Op, DAG);
25475 }
25476 
25477 // Decompose 512-bit ops into smaller 256-bit ops.
Lower512IntUnary(SDValue Op,SelectionDAG & DAG)25478 static SDValue Lower512IntUnary(SDValue Op, SelectionDAG &DAG) {
25479   assert(Op.getSimpleValueType().is512BitVector() &&
25480          Op.getSimpleValueType().isInteger() &&
25481          "Only handle AVX 512-bit vector integer operation");
25482   return LowerVectorIntUnary(Op, DAG);
25483 }
25484 
25485 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
25486 //
25487 // i8/i16 vector implemented using dword LZCNT vector instruction
25488 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
25489 // split the vector, perform operation on it's Lo a Hi part and
25490 // concatenate the results.
LowerVectorCTLZ_AVX512CDI(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)25491 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
25492                                          const X86Subtarget &Subtarget) {
25493   assert(Op.getOpcode() == ISD::CTLZ);
25494   SDLoc dl(Op);
25495   MVT VT = Op.getSimpleValueType();
25496   MVT EltVT = VT.getVectorElementType();
25497   unsigned NumElems = VT.getVectorNumElements();
25498 
25499   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
25500           "Unsupported element type");
25501 
25502   // Split vector, it's Lo and Hi parts will be handled in next iteration.
25503   if (NumElems > 16 ||
25504       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
25505     return LowerVectorIntUnary(Op, DAG);
25506 
25507   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
25508   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
25509           "Unsupported value type for operation");
25510 
25511   // Use native supported vector instruction vplzcntd.
25512   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
25513   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
25514   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
25515   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
25516 
25517   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
25518 }
25519 
25520 // Lower CTLZ using a PSHUFB lookup table implementation.
LowerVectorCTLZInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)25521 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
25522                                        const X86Subtarget &Subtarget,
25523                                        SelectionDAG &DAG) {
25524   MVT VT = Op.getSimpleValueType();
25525   int NumElts = VT.getVectorNumElements();
25526   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
25527   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
25528 
25529   // Per-nibble leading zero PSHUFB lookup table.
25530   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
25531                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
25532                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
25533                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
25534 
25535   SmallVector<SDValue, 64> LUTVec;
25536   for (int i = 0; i < NumBytes; ++i)
25537     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
25538   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
25539 
25540   // Begin by bitcasting the input to byte vector, then split those bytes
25541   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
25542   // If the hi input nibble is zero then we add both results together, otherwise
25543   // we just take the hi result (by masking the lo result to zero before the
25544   // add).
25545   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
25546   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
25547 
25548   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
25549   SDValue Lo = Op0;
25550   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
25551   SDValue HiZ;
25552   if (CurrVT.is512BitVector()) {
25553     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
25554     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
25555     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
25556   } else {
25557     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
25558   }
25559 
25560   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
25561   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
25562   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
25563   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
25564 
25565   // Merge result back from vXi8 back to VT, working on the lo/hi halves
25566   // of the current vector width in the same way we did for the nibbles.
25567   // If the upper half of the input element is zero then add the halves'
25568   // leading zero counts together, otherwise just use the upper half's.
25569   // Double the width of the result until we are at target width.
25570   while (CurrVT != VT) {
25571     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
25572     int CurrNumElts = CurrVT.getVectorNumElements();
25573     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
25574     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
25575     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
25576 
25577     // Check if the upper half of the input element is zero.
25578     if (CurrVT.is512BitVector()) {
25579       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
25580       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
25581                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
25582       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
25583     } else {
25584       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
25585                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
25586     }
25587     HiZ = DAG.getBitcast(NextVT, HiZ);
25588 
25589     // Move the upper/lower halves to the lower bits as we'll be extending to
25590     // NextVT. Mask the lower result to zero if HiZ is true and add the results
25591     // together.
25592     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
25593     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
25594     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
25595     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
25596     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
25597     CurrVT = NextVT;
25598   }
25599 
25600   return Res;
25601 }
25602 
LowerVectorCTLZ(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)25603 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
25604                                const X86Subtarget &Subtarget,
25605                                SelectionDAG &DAG) {
25606   MVT VT = Op.getSimpleValueType();
25607 
25608   if (Subtarget.hasCDI() &&
25609       // vXi8 vectors need to be promoted to 512-bits for vXi32.
25610       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
25611     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
25612 
25613   // Decompose 256-bit ops into smaller 128-bit ops.
25614   if (VT.is256BitVector() && !Subtarget.hasInt256())
25615     return Lower256IntUnary(Op, DAG);
25616 
25617   // Decompose 512-bit ops into smaller 256-bit ops.
25618   if (VT.is512BitVector() && !Subtarget.hasBWI())
25619     return Lower512IntUnary(Op, DAG);
25620 
25621   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
25622   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
25623 }
25624 
LowerCTLZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25625 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
25626                          SelectionDAG &DAG) {
25627   MVT VT = Op.getSimpleValueType();
25628   MVT OpVT = VT;
25629   unsigned NumBits = VT.getSizeInBits();
25630   SDLoc dl(Op);
25631   unsigned Opc = Op.getOpcode();
25632 
25633   if (VT.isVector())
25634     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
25635 
25636   Op = Op.getOperand(0);
25637   if (VT == MVT::i8) {
25638     // Zero extend to i32 since there is not an i8 bsr.
25639     OpVT = MVT::i32;
25640     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
25641   }
25642 
25643   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
25644   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
25645   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
25646 
25647   if (Opc == ISD::CTLZ) {
25648     // If src is zero (i.e. bsr sets ZF), returns NumBits.
25649     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
25650                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
25651                      Op.getValue(1)};
25652     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
25653   }
25654 
25655   // Finally xor with NumBits-1.
25656   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
25657                    DAG.getConstant(NumBits - 1, dl, OpVT));
25658 
25659   if (VT == MVT::i8)
25660     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
25661   return Op;
25662 }
25663 
LowerCTTZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25664 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
25665                          SelectionDAG &DAG) {
25666   MVT VT = Op.getSimpleValueType();
25667   unsigned NumBits = VT.getScalarSizeInBits();
25668   SDValue N0 = Op.getOperand(0);
25669   SDLoc dl(Op);
25670 
25671   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
25672          "Only scalar CTTZ requires custom lowering");
25673 
25674   // Issue a bsf (scan bits forward) which also sets EFLAGS.
25675   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
25676   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
25677 
25678   // If src is zero (i.e. bsf sets ZF), returns NumBits.
25679   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
25680                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
25681                    Op.getValue(1)};
25682   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
25683 }
25684 
25685 /// Break a 256-bit integer operation into two new 128-bit ones and then
25686 /// concatenate the result back.
split256IntArith(SDValue Op,SelectionDAG & DAG)25687 static SDValue split256IntArith(SDValue Op, SelectionDAG &DAG) {
25688   MVT VT = Op.getSimpleValueType();
25689 
25690   assert(VT.is256BitVector() && VT.isInteger() &&
25691          "Unsupported value type for operation");
25692 
25693   unsigned NumElems = VT.getVectorNumElements();
25694   SDLoc dl(Op);
25695 
25696   // Extract the LHS vectors
25697   SDValue LHS = Op.getOperand(0);
25698   SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
25699   SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
25700 
25701   // Extract the RHS vectors
25702   SDValue RHS = Op.getOperand(1);
25703   SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
25704   SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
25705 
25706   MVT EltVT = VT.getVectorElementType();
25707   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
25708 
25709   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
25710                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
25711                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
25712 }
25713 
25714 /// Break a 512-bit integer operation into two new 256-bit ones and then
25715 /// concatenate the result back.
split512IntArith(SDValue Op,SelectionDAG & DAG)25716 static SDValue split512IntArith(SDValue Op, SelectionDAG &DAG) {
25717   MVT VT = Op.getSimpleValueType();
25718 
25719   assert(VT.is512BitVector() && VT.isInteger() &&
25720          "Unsupported value type for operation");
25721 
25722   unsigned NumElems = VT.getVectorNumElements();
25723   SDLoc dl(Op);
25724 
25725   // Extract the LHS vectors
25726   SDValue LHS = Op.getOperand(0);
25727   SDValue LHS1 = extract256BitVector(LHS, 0, DAG, dl);
25728   SDValue LHS2 = extract256BitVector(LHS, NumElems / 2, DAG, dl);
25729 
25730   // Extract the RHS vectors
25731   SDValue RHS = Op.getOperand(1);
25732   SDValue RHS1 = extract256BitVector(RHS, 0, DAG, dl);
25733   SDValue RHS2 = extract256BitVector(RHS, NumElems / 2, DAG, dl);
25734 
25735   MVT EltVT = VT.getVectorElementType();
25736   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
25737 
25738   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
25739                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
25740                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
25741 }
25742 
lowerAddSub(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)25743 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
25744                            const X86Subtarget &Subtarget) {
25745   MVT VT = Op.getSimpleValueType();
25746   if (VT == MVT::i16 || VT == MVT::i32)
25747     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
25748 
25749   if (VT.getScalarType() == MVT::i1)
25750     return DAG.getNode(ISD::XOR, SDLoc(Op), VT,
25751                        Op.getOperand(0), Op.getOperand(1));
25752 
25753   assert(Op.getSimpleValueType().is256BitVector() &&
25754          Op.getSimpleValueType().isInteger() &&
25755          "Only handle AVX 256-bit vector integer operation");
25756   return split256IntArith(Op, DAG);
25757 }
25758 
LowerADDSAT_SUBSAT(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)25759 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
25760                                   const X86Subtarget &Subtarget) {
25761   MVT VT = Op.getSimpleValueType();
25762   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
25763   unsigned Opcode = Op.getOpcode();
25764   if (VT.getScalarType() == MVT::i1) {
25765     SDLoc dl(Op);
25766     switch (Opcode) {
25767     default: llvm_unreachable("Expected saturated arithmetic opcode");
25768     case ISD::UADDSAT:
25769     case ISD::SADDSAT:
25770       // *addsat i1 X, Y --> X | Y
25771       return DAG.getNode(ISD::OR, dl, VT, X, Y);
25772     case ISD::USUBSAT:
25773     case ISD::SSUBSAT:
25774       // *subsat i1 X, Y --> X & ~Y
25775       return DAG.getNode(ISD::AND, dl, VT, X, DAG.getNOT(dl, Y, VT));
25776     }
25777   }
25778 
25779   if (VT.is128BitVector()) {
25780     // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
25781     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25782     EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
25783                                                  *DAG.getContext(), VT);
25784     SDLoc DL(Op);
25785     if (Opcode == ISD::UADDSAT && !TLI.isOperationLegal(ISD::UMIN, VT)) {
25786       // uaddsat X, Y --> (X >u (X + Y)) ? -1 : X + Y
25787       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, X, Y);
25788       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Add, ISD::SETUGT);
25789       return DAG.getSelect(DL, VT, Cmp, DAG.getAllOnesConstant(DL, VT), Add);
25790     }
25791     if (Opcode == ISD::USUBSAT && !TLI.isOperationLegal(ISD::UMAX, VT)) {
25792       // usubsat X, Y --> (X >u Y) ? X - Y : 0
25793       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
25794       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
25795       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
25796     }
25797     // Use default expansion.
25798     return SDValue();
25799   }
25800 
25801   assert(Op.getSimpleValueType().is256BitVector() &&
25802          Op.getSimpleValueType().isInteger() &&
25803          "Only handle AVX 256-bit vector integer operation");
25804   return split256IntArith(Op, DAG);
25805 }
25806 
LowerABS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25807 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
25808                         SelectionDAG &DAG) {
25809   MVT VT = Op.getSimpleValueType();
25810   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
25811     // Since X86 does not have CMOV for 8-bit integer, we don't convert
25812     // 8-bit integer abs to NEG and CMOV.
25813     SDLoc DL(Op);
25814     SDValue N0 = Op.getOperand(0);
25815     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25816                               DAG.getConstant(0, DL, VT), N0);
25817     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_GE, DL, MVT::i8),
25818                      SDValue(Neg.getNode(), 1)};
25819     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
25820   }
25821 
25822   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
25823   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
25824     SDLoc DL(Op);
25825     SDValue Src = Op.getOperand(0);
25826     SDValue Sub =
25827         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
25828     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
25829   }
25830 
25831   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
25832     assert(VT.isInteger() &&
25833            "Only handle AVX 256-bit vector integer operation");
25834     return Lower256IntUnary(Op, DAG);
25835   }
25836 
25837   // Default to expand.
25838   return SDValue();
25839 }
25840 
LowerMINMAX(SDValue Op,SelectionDAG & DAG)25841 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
25842   MVT VT = Op.getSimpleValueType();
25843 
25844   // For AVX1 cases, split to use legal ops (everything but v4i64).
25845   if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
25846     return split256IntArith(Op, DAG);
25847 
25848   SDLoc DL(Op);
25849   unsigned Opcode = Op.getOpcode();
25850   SDValue N0 = Op.getOperand(0);
25851   SDValue N1 = Op.getOperand(1);
25852 
25853   // For pre-SSE41, we can perform UMIN/UMAX v8i16 by flipping the signbit,
25854   // using the SMIN/SMAX instructions and flipping the signbit back.
25855   if (VT == MVT::v8i16) {
25856     assert((Opcode == ISD::UMIN || Opcode == ISD::UMAX) &&
25857            "Unexpected MIN/MAX opcode");
25858     SDValue Sign = DAG.getConstant(APInt::getSignedMinValue(16), DL, VT);
25859     N0 = DAG.getNode(ISD::XOR, DL, VT, N0, Sign);
25860     N1 = DAG.getNode(ISD::XOR, DL, VT, N1, Sign);
25861     Opcode = (Opcode == ISD::UMIN ? ISD::SMIN : ISD::SMAX);
25862     SDValue Result = DAG.getNode(Opcode, DL, VT, N0, N1);
25863     return DAG.getNode(ISD::XOR, DL, VT, Result, Sign);
25864   }
25865 
25866   // Else, expand to a compare/select.
25867   ISD::CondCode CC;
25868   switch (Opcode) {
25869   case ISD::SMIN: CC = ISD::CondCode::SETLT;  break;
25870   case ISD::SMAX: CC = ISD::CondCode::SETGT;  break;
25871   case ISD::UMIN: CC = ISD::CondCode::SETULT; break;
25872   case ISD::UMAX: CC = ISD::CondCode::SETUGT; break;
25873   default: llvm_unreachable("Unknown MINMAX opcode");
25874   }
25875 
25876   SDValue Cond = DAG.getSetCC(DL, VT, N0, N1, CC);
25877   return DAG.getSelect(DL, VT, Cond, N0, N1);
25878 }
25879 
LowerMUL(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25880 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
25881                         SelectionDAG &DAG) {
25882   SDLoc dl(Op);
25883   MVT VT = Op.getSimpleValueType();
25884 
25885   if (VT.getScalarType() == MVT::i1)
25886     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
25887 
25888   // Decompose 256-bit ops into 128-bit ops.
25889   if (VT.is256BitVector() && !Subtarget.hasInt256())
25890     return split256IntArith(Op, DAG);
25891 
25892   SDValue A = Op.getOperand(0);
25893   SDValue B = Op.getOperand(1);
25894 
25895   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
25896   // vector pairs, multiply and truncate.
25897   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
25898     unsigned NumElts = VT.getVectorNumElements();
25899 
25900     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
25901         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
25902       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
25903       return DAG.getNode(
25904           ISD::TRUNCATE, dl, VT,
25905           DAG.getNode(ISD::MUL, dl, ExVT,
25906                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
25907                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
25908     }
25909 
25910     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
25911 
25912     // Extract the lo/hi parts to any extend to i16.
25913     // We're going to mask off the low byte of each result element of the
25914     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
25915     // element.
25916     SDValue Undef = DAG.getUNDEF(VT);
25917     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
25918     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
25919 
25920     SDValue BLo, BHi;
25921     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
25922       // If the LHS is a constant, manually unpackl/unpackh.
25923       SmallVector<SDValue, 16> LoOps, HiOps;
25924       for (unsigned i = 0; i != NumElts; i += 16) {
25925         for (unsigned j = 0; j != 8; ++j) {
25926           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
25927                                                MVT::i16));
25928           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
25929                                                MVT::i16));
25930         }
25931       }
25932 
25933       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
25934       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
25935     } else {
25936       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
25937       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
25938     }
25939 
25940     // Multiply, mask the lower 8bits of the lo/hi results and pack.
25941     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
25942     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
25943     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
25944     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
25945     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
25946   }
25947 
25948   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
25949   if (VT == MVT::v4i32) {
25950     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
25951            "Should not custom lower when pmulld is available!");
25952 
25953     // Extract the odd parts.
25954     static const int UnpackMask[] = { 1, -1, 3, -1 };
25955     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
25956     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
25957 
25958     // Multiply the even parts.
25959     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
25960                                 DAG.getBitcast(MVT::v2i64, A),
25961                                 DAG.getBitcast(MVT::v2i64, B));
25962     // Now multiply odd parts.
25963     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
25964                                DAG.getBitcast(MVT::v2i64, Aodds),
25965                                DAG.getBitcast(MVT::v2i64, Bodds));
25966 
25967     Evens = DAG.getBitcast(VT, Evens);
25968     Odds = DAG.getBitcast(VT, Odds);
25969 
25970     // Merge the two vectors back together with a shuffle. This expands into 2
25971     // shuffles.
25972     static const int ShufMask[] = { 0, 4, 2, 6 };
25973     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
25974   }
25975 
25976   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
25977          "Only know how to lower V2I64/V4I64/V8I64 multiply");
25978   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
25979 
25980   //  Ahi = psrlqi(a, 32);
25981   //  Bhi = psrlqi(b, 32);
25982   //
25983   //  AloBlo = pmuludq(a, b);
25984   //  AloBhi = pmuludq(a, Bhi);
25985   //  AhiBlo = pmuludq(Ahi, b);
25986   //
25987   //  Hi = psllqi(AloBhi + AhiBlo, 32);
25988   //  return AloBlo + Hi;
25989   KnownBits AKnown = DAG.computeKnownBits(A);
25990   KnownBits BKnown = DAG.computeKnownBits(B);
25991 
25992   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
25993   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
25994   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
25995 
25996   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
25997   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
25998   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
25999 
26000   SDValue Zero = DAG.getConstant(0, dl, VT);
26001 
26002   // Only multiply lo/hi halves that aren't known to be zero.
26003   SDValue AloBlo = Zero;
26004   if (!ALoIsZero && !BLoIsZero)
26005     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
26006 
26007   SDValue AloBhi = Zero;
26008   if (!ALoIsZero && !BHiIsZero) {
26009     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
26010     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
26011   }
26012 
26013   SDValue AhiBlo = Zero;
26014   if (!AHiIsZero && !BLoIsZero) {
26015     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
26016     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
26017   }
26018 
26019   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
26020   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
26021 
26022   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
26023 }
26024 
LowerMULH(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26025 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
26026                          SelectionDAG &DAG) {
26027   SDLoc dl(Op);
26028   MVT VT = Op.getSimpleValueType();
26029   bool IsSigned = Op->getOpcode() == ISD::MULHS;
26030   unsigned NumElts = VT.getVectorNumElements();
26031   SDValue A = Op.getOperand(0);
26032   SDValue B = Op.getOperand(1);
26033 
26034   // Decompose 256-bit ops into 128-bit ops.
26035   if (VT.is256BitVector() && !Subtarget.hasInt256())
26036     return split256IntArith(Op, DAG);
26037 
26038   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
26039     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
26040            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
26041            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
26042 
26043     // PMULxD operations multiply each even value (starting at 0) of LHS with
26044     // the related value of RHS and produce a widen result.
26045     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
26046     // => <2 x i64> <ae|cg>
26047     //
26048     // In other word, to have all the results, we need to perform two PMULxD:
26049     // 1. one with the even values.
26050     // 2. one with the odd values.
26051     // To achieve #2, with need to place the odd values at an even position.
26052     //
26053     // Place the odd value at an even position (basically, shift all values 1
26054     // step to the left):
26055     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
26056                         9, -1, 11, -1, 13, -1, 15, -1};
26057     // <a|b|c|d> => <b|undef|d|undef>
26058     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
26059                                         makeArrayRef(&Mask[0], NumElts));
26060     // <e|f|g|h> => <f|undef|h|undef>
26061     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
26062                                         makeArrayRef(&Mask[0], NumElts));
26063 
26064     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
26065     // ints.
26066     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
26067     unsigned Opcode =
26068         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
26069     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
26070     // => <2 x i64> <ae|cg>
26071     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
26072                                                   DAG.getBitcast(MulVT, A),
26073                                                   DAG.getBitcast(MulVT, B)));
26074     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
26075     // => <2 x i64> <bf|dh>
26076     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
26077                                                   DAG.getBitcast(MulVT, Odd0),
26078                                                   DAG.getBitcast(MulVT, Odd1)));
26079 
26080     // Shuffle it back into the right order.
26081     SmallVector<int, 16> ShufMask(NumElts);
26082     for (int i = 0; i != (int)NumElts; ++i)
26083       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
26084 
26085     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
26086 
26087     // If we have a signed multiply but no PMULDQ fix up the result of an
26088     // unsigned multiply.
26089     if (IsSigned && !Subtarget.hasSSE41()) {
26090       SDValue Zero = DAG.getConstant(0, dl, VT);
26091       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
26092                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
26093       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
26094                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
26095 
26096       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
26097       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
26098     }
26099 
26100     return Res;
26101   }
26102 
26103   // Only i8 vectors should need custom lowering after this.
26104   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
26105          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
26106          "Unsupported vector type");
26107 
26108   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
26109   // logical shift down the upper half and pack back to i8.
26110 
26111   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
26112   // and then ashr/lshr the upper bits down to the lower bits before multiply.
26113   unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
26114 
26115   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
26116       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
26117     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
26118     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
26119     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
26120     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
26121     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
26122     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
26123   }
26124 
26125   // For signed 512-bit vectors, split into 256-bit vectors to allow the
26126   // sign-extension to occur.
26127   if (VT == MVT::v64i8 && IsSigned)
26128     return split512IntArith(Op, DAG);
26129 
26130   // Signed AVX2 implementation - extend xmm subvectors to ymm.
26131   if (VT == MVT::v32i8 && IsSigned) {
26132     MVT ExVT = MVT::v16i16;
26133     SDValue ALo = extract128BitVector(A, 0, DAG, dl);
26134     SDValue BLo = extract128BitVector(B, 0, DAG, dl);
26135     SDValue AHi = extract128BitVector(A, NumElts / 2, DAG, dl);
26136     SDValue BHi = extract128BitVector(B, NumElts / 2, DAG, dl);
26137     ALo = DAG.getNode(ExAVX, dl, ExVT, ALo);
26138     BLo = DAG.getNode(ExAVX, dl, ExVT, BLo);
26139     AHi = DAG.getNode(ExAVX, dl, ExVT, AHi);
26140     BHi = DAG.getNode(ExAVX, dl, ExVT, BHi);
26141     SDValue Lo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
26142     SDValue Hi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
26143     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Lo, 8, DAG);
26144     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Hi, 8, DAG);
26145 
26146     // Bitcast back to VT and then pack all the even elements from Lo and Hi.
26147     // Shuffle lowering should turn this into PACKUS+PERMQ
26148     Lo = DAG.getBitcast(VT, Lo);
26149     Hi = DAG.getBitcast(VT, Hi);
26150     return DAG.getVectorShuffle(VT, dl, Lo, Hi,
26151                                 { 0,  2,  4,  6,  8, 10, 12, 14,
26152                                  16, 18, 20, 22, 24, 26, 28, 30,
26153                                  32, 34, 36, 38, 40, 42, 44, 46,
26154                                  48, 50, 52, 54, 56, 58, 60, 62});
26155   }
26156 
26157   // For signed v16i8 and all unsigned vXi8 we will unpack the low and high
26158   // half of each 128 bit lane to widen to a vXi16 type. Do the multiplies,
26159   // shift the results and pack the half lane results back together.
26160 
26161   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
26162 
26163   static const int PSHUFDMask[] = { 8,  9, 10, 11, 12, 13, 14, 15,
26164                                    -1, -1, -1, -1, -1, -1, -1, -1};
26165 
26166   // Extract the lo parts and zero/sign extend to i16.
26167   // Only use SSE4.1 instructions for signed v16i8 where using unpack requires
26168   // shifts to sign extend. Using unpack for unsigned only requires an xor to
26169   // create zeros and a copy due to tied registers contraints pre-avx. But using
26170   // zero_extend_vector_inreg would require an additional pshufd for the high
26171   // part.
26172 
26173   SDValue ALo, AHi;
26174   if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
26175     ALo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, A);
26176 
26177     AHi = DAG.getVectorShuffle(VT, dl, A, A, PSHUFDMask);
26178     AHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, AHi);
26179   } else if (IsSigned) {
26180     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), A));
26181     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), A));
26182 
26183     ALo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, ALo, 8, DAG);
26184     AHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, AHi, 8, DAG);
26185   } else {
26186     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A,
26187                                           DAG.getConstant(0, dl, VT)));
26188     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A,
26189                                           DAG.getConstant(0, dl, VT)));
26190   }
26191 
26192   SDValue BLo, BHi;
26193   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
26194     // If the LHS is a constant, manually unpackl/unpackh and extend.
26195     SmallVector<SDValue, 16> LoOps, HiOps;
26196     for (unsigned i = 0; i != NumElts; i += 16) {
26197       for (unsigned j = 0; j != 8; ++j) {
26198         SDValue LoOp = B.getOperand(i + j);
26199         SDValue HiOp = B.getOperand(i + j + 8);
26200 
26201         if (IsSigned) {
26202           LoOp = DAG.getSExtOrTrunc(LoOp, dl, MVT::i16);
26203           HiOp = DAG.getSExtOrTrunc(HiOp, dl, MVT::i16);
26204         } else {
26205           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
26206           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
26207         }
26208 
26209         LoOps.push_back(LoOp);
26210         HiOps.push_back(HiOp);
26211       }
26212     }
26213 
26214     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
26215     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
26216   } else if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
26217     BLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, B);
26218 
26219     BHi = DAG.getVectorShuffle(VT, dl, B, B, PSHUFDMask);
26220     BHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, BHi);
26221   } else if (IsSigned) {
26222     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), B));
26223     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), B));
26224 
26225     BLo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BLo, 8, DAG);
26226     BHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BHi, 8, DAG);
26227   } else {
26228     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B,
26229                                           DAG.getConstant(0, dl, VT)));
26230     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B,
26231                                           DAG.getConstant(0, dl, VT)));
26232   }
26233 
26234   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
26235   // pack back to vXi8.
26236   SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
26237   SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
26238   RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
26239   RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
26240 
26241   // Bitcast back to VT and then pack all the even elements from Lo and Hi.
26242   return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
26243 }
26244 
LowerWin64_i128OP(SDValue Op,SelectionDAG & DAG) const26245 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
26246   assert(Subtarget.isTargetWin64() && "Unexpected target");
26247   EVT VT = Op.getValueType();
26248   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
26249          "Unexpected return type for lowering");
26250 
26251   RTLIB::Libcall LC;
26252   bool isSigned;
26253   switch (Op->getOpcode()) {
26254   default: llvm_unreachable("Unexpected request for libcall!");
26255   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
26256   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
26257   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
26258   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
26259   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
26260   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
26261   }
26262 
26263   SDLoc dl(Op);
26264   SDValue InChain = DAG.getEntryNode();
26265 
26266   TargetLowering::ArgListTy Args;
26267   TargetLowering::ArgListEntry Entry;
26268   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
26269     EVT ArgVT = Op->getOperand(i).getValueType();
26270     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
26271            "Unexpected argument type for lowering");
26272     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
26273     Entry.Node = StackPtr;
26274     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr,
26275                            MachinePointerInfo(), /* Alignment = */ 16);
26276     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
26277     Entry.Ty = PointerType::get(ArgTy,0);
26278     Entry.IsSExt = false;
26279     Entry.IsZExt = false;
26280     Args.push_back(Entry);
26281   }
26282 
26283   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
26284                                          getPointerTy(DAG.getDataLayout()));
26285 
26286   TargetLowering::CallLoweringInfo CLI(DAG);
26287   CLI.setDebugLoc(dl)
26288       .setChain(InChain)
26289       .setLibCallee(
26290           getLibcallCallingConv(LC),
26291           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
26292           std::move(Args))
26293       .setInRegister()
26294       .setSExtResult(isSigned)
26295       .setZExtResult(!isSigned);
26296 
26297   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
26298   return DAG.getBitcast(VT, CallInfo.first);
26299 }
26300 
26301 // Return true if the required (according to Opcode) shift-imm form is natively
26302 // supported by the Subtarget
SupportedVectorShiftWithImm(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26303 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
26304                                         unsigned Opcode) {
26305   if (VT.getScalarSizeInBits() < 16)
26306     return false;
26307 
26308   if (VT.is512BitVector() && Subtarget.hasAVX512() &&
26309       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
26310     return true;
26311 
26312   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
26313                 (VT.is256BitVector() && Subtarget.hasInt256());
26314 
26315   bool AShift = LShift && (Subtarget.hasAVX512() ||
26316                            (VT != MVT::v2i64 && VT != MVT::v4i64));
26317   return (Opcode == ISD::SRA) ? AShift : LShift;
26318 }
26319 
26320 // The shift amount is a variable, but it is the same for all vector lanes.
26321 // These instructions are defined together with shift-immediate.
26322 static
SupportedVectorShiftWithBaseAmnt(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26323 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
26324                                       unsigned Opcode) {
26325   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
26326 }
26327 
26328 // Return true if the required (according to Opcode) variable-shift form is
26329 // natively supported by the Subtarget
SupportedVectorVarShift(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26330 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
26331                                     unsigned Opcode) {
26332 
26333   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
26334     return false;
26335 
26336   // vXi16 supported only on AVX-512, BWI
26337   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
26338     return false;
26339 
26340   if (Subtarget.hasAVX512())
26341     return true;
26342 
26343   bool LShift = VT.is128BitVector() || VT.is256BitVector();
26344   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
26345   return (Opcode == ISD::SRA) ? AShift : LShift;
26346 }
26347 
LowerScalarImmediateShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26348 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
26349                                          const X86Subtarget &Subtarget) {
26350   MVT VT = Op.getSimpleValueType();
26351   SDLoc dl(Op);
26352   SDValue R = Op.getOperand(0);
26353   SDValue Amt = Op.getOperand(1);
26354   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
26355 
26356   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
26357     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
26358     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
26359     SDValue Ex = DAG.getBitcast(ExVT, R);
26360 
26361     // ashr(R, 63) === cmp_slt(R, 0)
26362     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
26363       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
26364              "Unsupported PCMPGT op");
26365       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
26366     }
26367 
26368     if (ShiftAmt >= 32) {
26369       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
26370       SDValue Upper =
26371           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
26372       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
26373                                                  ShiftAmt - 32, DAG);
26374       if (VT == MVT::v2i64)
26375         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
26376       if (VT == MVT::v4i64)
26377         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
26378                                   {9, 1, 11, 3, 13, 5, 15, 7});
26379     } else {
26380       // SRA upper i32, SRL whole i64 and select lower i32.
26381       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
26382                                                  ShiftAmt, DAG);
26383       SDValue Lower =
26384           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
26385       Lower = DAG.getBitcast(ExVT, Lower);
26386       if (VT == MVT::v2i64)
26387         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
26388       if (VT == MVT::v4i64)
26389         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
26390                                   {8, 1, 10, 3, 12, 5, 14, 7});
26391     }
26392     return DAG.getBitcast(VT, Ex);
26393   };
26394 
26395   // Optimize shl/srl/sra with constant shift amount.
26396   APInt APIntShiftAmt;
26397   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
26398     return SDValue();
26399 
26400   // If the shift amount is out of range, return undef.
26401   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
26402     return DAG.getUNDEF(VT);
26403 
26404   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
26405 
26406   if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
26407     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
26408 
26409   // i64 SRA needs to be performed as partial shifts.
26410   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
26411        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
26412       Op.getOpcode() == ISD::SRA)
26413     return ArithmeticShiftRight64(ShiftAmt);
26414 
26415   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
26416       VT == MVT::v64i8) {
26417     unsigned NumElts = VT.getVectorNumElements();
26418     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
26419 
26420     // Simple i8 add case
26421     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
26422       return DAG.getNode(ISD::ADD, dl, VT, R, R);
26423 
26424     // ashr(R, 7)  === cmp_slt(R, 0)
26425     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
26426       SDValue Zeros = DAG.getConstant(0, dl, VT);
26427       if (VT.is512BitVector()) {
26428         assert(VT == MVT::v64i8 && "Unexpected element type!");
26429         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
26430         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
26431       }
26432       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
26433     }
26434 
26435     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
26436     if (VT == MVT::v16i8 && Subtarget.hasXOP())
26437       return SDValue();
26438 
26439     if (Op.getOpcode() == ISD::SHL) {
26440       // Make a large shift.
26441       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
26442                                                ShiftAmt, DAG);
26443       SHL = DAG.getBitcast(VT, SHL);
26444       // Zero out the rightmost bits.
26445       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
26446       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
26447     }
26448     if (Op.getOpcode() == ISD::SRL) {
26449       // Make a large shift.
26450       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
26451                                                ShiftAmt, DAG);
26452       SRL = DAG.getBitcast(VT, SRL);
26453       // Zero out the leftmost bits.
26454       return DAG.getNode(ISD::AND, dl, VT, SRL,
26455                          DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
26456     }
26457     if (Op.getOpcode() == ISD::SRA) {
26458       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
26459       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
26460 
26461       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
26462       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
26463       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
26464       return Res;
26465     }
26466     llvm_unreachable("Unknown shift opcode.");
26467   }
26468 
26469   return SDValue();
26470 }
26471 
LowerScalarVariableShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26472 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
26473                                         const X86Subtarget &Subtarget) {
26474   MVT VT = Op.getSimpleValueType();
26475   SDLoc dl(Op);
26476   SDValue R = Op.getOperand(0);
26477   SDValue Amt = Op.getOperand(1);
26478   unsigned Opcode = Op.getOpcode();
26479   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
26480   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
26481 
26482   if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
26483     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
26484       MVT EltVT = VT.getVectorElementType();
26485       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
26486       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
26487         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
26488       else if (EltVT.bitsLT(MVT::i32))
26489         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
26490 
26491       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
26492     }
26493 
26494     // vXi8 shifts - shift as v8i16 + mask result.
26495     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
26496          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
26497          VT == MVT::v64i8) &&
26498         !Subtarget.hasXOP()) {
26499       unsigned NumElts = VT.getVectorNumElements();
26500       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
26501       if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
26502         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
26503         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
26504         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
26505 
26506         // Create the mask using vXi16 shifts. For shift-rights we need to move
26507         // the upper byte down before splatting the vXi8 mask.
26508         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
26509         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
26510                                       BaseShAmt, Subtarget, DAG);
26511         if (Opcode != ISD::SHL)
26512           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
26513                                                8, DAG);
26514         BitMask = DAG.getBitcast(VT, BitMask);
26515         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
26516                                        SmallVector<int, 64>(NumElts, 0));
26517 
26518         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
26519                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
26520                                           Subtarget, DAG);
26521         Res = DAG.getBitcast(VT, Res);
26522         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
26523 
26524         if (Opcode == ISD::SRA) {
26525           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
26526           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
26527           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
26528           SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
26529                                          BaseShAmt, Subtarget, DAG);
26530           SignMask = DAG.getBitcast(VT, SignMask);
26531           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
26532           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
26533         }
26534         return Res;
26535       }
26536     }
26537   }
26538 
26539   // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
26540   if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
26541       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
26542     Amt = Amt.getOperand(0);
26543     unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
26544     std::vector<SDValue> Vals(Ratio);
26545     for (unsigned i = 0; i != Ratio; ++i)
26546       Vals[i] = Amt.getOperand(i);
26547     for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
26548       for (unsigned j = 0; j != Ratio; ++j)
26549         if (Vals[j] != Amt.getOperand(i + j))
26550           return SDValue();
26551     }
26552 
26553     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
26554       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
26555   }
26556   return SDValue();
26557 }
26558 
26559 // Convert a shift/rotate left amount to a multiplication scale factor.
convertShiftLeftToScale(SDValue Amt,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)26560 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
26561                                        const X86Subtarget &Subtarget,
26562                                        SelectionDAG &DAG) {
26563   MVT VT = Amt.getSimpleValueType();
26564   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
26565         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
26566         (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
26567     return SDValue();
26568 
26569   if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
26570     SmallVector<SDValue, 8> Elts;
26571     MVT SVT = VT.getVectorElementType();
26572     unsigned SVTBits = SVT.getSizeInBits();
26573     APInt One(SVTBits, 1);
26574     unsigned NumElems = VT.getVectorNumElements();
26575 
26576     for (unsigned i = 0; i != NumElems; ++i) {
26577       SDValue Op = Amt->getOperand(i);
26578       if (Op->isUndef()) {
26579         Elts.push_back(Op);
26580         continue;
26581       }
26582 
26583       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
26584       APInt C(SVTBits, ND->getZExtValue());
26585       uint64_t ShAmt = C.getZExtValue();
26586       if (ShAmt >= SVTBits) {
26587         Elts.push_back(DAG.getUNDEF(SVT));
26588         continue;
26589       }
26590       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
26591     }
26592     return DAG.getBuildVector(VT, dl, Elts);
26593   }
26594 
26595   // If the target doesn't support variable shifts, use either FP conversion
26596   // or integer multiplication to avoid shifting each element individually.
26597   if (VT == MVT::v4i32) {
26598     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
26599     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
26600                       DAG.getConstant(0x3f800000U, dl, VT));
26601     Amt = DAG.getBitcast(MVT::v4f32, Amt);
26602     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
26603   }
26604 
26605   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
26606   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
26607     SDValue Z = DAG.getConstant(0, dl, VT);
26608     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
26609     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
26610     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
26611     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
26612     if (Subtarget.hasSSE41())
26613       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
26614 
26615     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
26616                                         DAG.getBitcast(VT, Hi),
26617                                         {0, 2, 4, 6, 8, 10, 12, 14});
26618   }
26619 
26620   return SDValue();
26621 }
26622 
LowerShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26623 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
26624                           SelectionDAG &DAG) {
26625   MVT VT = Op.getSimpleValueType();
26626   SDLoc dl(Op);
26627   SDValue R = Op.getOperand(0);
26628   SDValue Amt = Op.getOperand(1);
26629   unsigned EltSizeInBits = VT.getScalarSizeInBits();
26630   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
26631 
26632   unsigned Opc = Op.getOpcode();
26633   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
26634   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
26635 
26636   assert(VT.isVector() && "Custom lowering only for vector shifts!");
26637   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
26638 
26639   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
26640     return V;
26641 
26642   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
26643     return V;
26644 
26645   if (SupportedVectorVarShift(VT, Subtarget, Opc))
26646     return Op;
26647 
26648   // XOP has 128-bit variable logical/arithmetic shifts.
26649   // +ve/-ve Amt = shift left/right.
26650   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
26651                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
26652     if (Opc == ISD::SRL || Opc == ISD::SRA) {
26653       SDValue Zero = DAG.getConstant(0, dl, VT);
26654       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
26655     }
26656     if (Opc == ISD::SHL || Opc == ISD::SRL)
26657       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
26658     if (Opc == ISD::SRA)
26659       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
26660   }
26661 
26662   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
26663   // shifts per-lane and then shuffle the partial results back together.
26664   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
26665     // Splat the shift amounts so the scalar shifts above will catch it.
26666     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
26667     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
26668     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
26669     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
26670     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
26671   }
26672 
26673   // i64 vector arithmetic shift can be emulated with the transform:
26674   // M = lshr(SIGN_MASK, Amt)
26675   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
26676   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
26677       Opc == ISD::SRA) {
26678     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
26679     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
26680     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
26681     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
26682     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
26683     return R;
26684   }
26685 
26686   // If possible, lower this shift as a sequence of two shifts by
26687   // constant plus a BLENDing shuffle instead of scalarizing it.
26688   // Example:
26689   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
26690   //
26691   // Could be rewritten as:
26692   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
26693   //
26694   // The advantage is that the two shifts from the example would be
26695   // lowered as X86ISD::VSRLI nodes in parallel before blending.
26696   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
26697                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
26698     SDValue Amt1, Amt2;
26699     unsigned NumElts = VT.getVectorNumElements();
26700     SmallVector<int, 8> ShuffleMask;
26701     for (unsigned i = 0; i != NumElts; ++i) {
26702       SDValue A = Amt->getOperand(i);
26703       if (A.isUndef()) {
26704         ShuffleMask.push_back(SM_SentinelUndef);
26705         continue;
26706       }
26707       if (!Amt1 || Amt1 == A) {
26708         ShuffleMask.push_back(i);
26709         Amt1 = A;
26710         continue;
26711       }
26712       if (!Amt2 || Amt2 == A) {
26713         ShuffleMask.push_back(i + NumElts);
26714         Amt2 = A;
26715         continue;
26716       }
26717       break;
26718     }
26719 
26720     // Only perform this blend if we can perform it without loading a mask.
26721     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
26722         (VT != MVT::v16i16 ||
26723          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
26724         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
26725          canWidenShuffleElements(ShuffleMask))) {
26726       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
26727       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
26728       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
26729           Cst2->getAPIntValue().ult(EltSizeInBits)) {
26730         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
26731                                                     Cst1->getZExtValue(), DAG);
26732         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
26733                                                     Cst2->getZExtValue(), DAG);
26734         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
26735       }
26736     }
26737   }
26738 
26739   // If possible, lower this packed shift into a vector multiply instead of
26740   // expanding it into a sequence of scalar shifts.
26741   if (Opc == ISD::SHL)
26742     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
26743       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
26744 
26745   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
26746   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
26747   if (Opc == ISD::SRL && ConstantAmt &&
26748       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
26749     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
26750     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
26751     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
26752       SDValue Zero = DAG.getConstant(0, dl, VT);
26753       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
26754       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
26755       return DAG.getSelect(dl, VT, ZAmt, R, Res);
26756     }
26757   }
26758 
26759   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
26760   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
26761   // TODO: Special case handling for shift by 0/1, really we can afford either
26762   // of these cases in pre-SSE41/XOP/AVX512 but not both.
26763   if (Opc == ISD::SRA && ConstantAmt &&
26764       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
26765       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
26766         !Subtarget.hasAVX512()) ||
26767        DAG.isKnownNeverZero(Amt))) {
26768     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
26769     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
26770     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
26771       SDValue Amt0 =
26772           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
26773       SDValue Amt1 =
26774           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
26775       SDValue Sra1 =
26776           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
26777       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
26778       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
26779       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
26780     }
26781   }
26782 
26783   // v4i32 Non Uniform Shifts.
26784   // If the shift amount is constant we can shift each lane using the SSE2
26785   // immediate shifts, else we need to zero-extend each lane to the lower i64
26786   // and shift using the SSE2 variable shifts.
26787   // The separate results can then be blended together.
26788   if (VT == MVT::v4i32) {
26789     SDValue Amt0, Amt1, Amt2, Amt3;
26790     if (ConstantAmt) {
26791       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
26792       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
26793       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
26794       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
26795     } else {
26796       // The SSE2 shifts use the lower i64 as the same shift amount for
26797       // all lanes and the upper i64 is ignored. On AVX we're better off
26798       // just zero-extending, but for SSE just duplicating the top 16-bits is
26799       // cheaper and has the same effect for out of range values.
26800       if (Subtarget.hasAVX()) {
26801         SDValue Z = DAG.getConstant(0, dl, VT);
26802         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
26803         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
26804         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
26805         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
26806       } else {
26807         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
26808         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
26809                                              {4, 5, 6, 7, -1, -1, -1, -1});
26810         Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
26811                                     {0, 1, 1, 1, -1, -1, -1, -1});
26812         Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
26813                                     {2, 3, 3, 3, -1, -1, -1, -1});
26814         Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
26815                                     {0, 1, 1, 1, -1, -1, -1, -1});
26816         Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
26817                                     {2, 3, 3, 3, -1, -1, -1, -1});
26818       }
26819     }
26820 
26821     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
26822     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
26823     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
26824     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
26825     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
26826 
26827     // Merge the shifted lane results optimally with/without PBLENDW.
26828     // TODO - ideally shuffle combining would handle this.
26829     if (Subtarget.hasSSE41()) {
26830       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
26831       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
26832       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
26833     }
26834     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
26835     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
26836     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
26837   }
26838 
26839   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
26840   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
26841   // make the existing SSE solution better.
26842   // NOTE: We honor prefered vector width before promoting to 512-bits.
26843   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
26844       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
26845       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
26846       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
26847       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
26848     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
26849            "Unexpected vector type");
26850     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
26851     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
26852     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
26853     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
26854     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
26855     return DAG.getNode(ISD::TRUNCATE, dl, VT,
26856                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
26857   }
26858 
26859   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
26860   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
26861   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
26862       (VT == MVT::v16i8 || VT == MVT::v64i8 ||
26863        (VT == MVT::v32i8 && Subtarget.hasInt256())) &&
26864       !Subtarget.hasXOP()) {
26865     int NumElts = VT.getVectorNumElements();
26866     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
26867 
26868     // Extend constant shift amount to vXi16 (it doesn't matter if the type
26869     // isn't legal).
26870     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
26871     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
26872     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
26873     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
26874     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
26875            "Constant build vector expected");
26876 
26877     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
26878       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
26879                           : DAG.getZExtOrTrunc(R, dl, ExVT);
26880       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
26881       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
26882       return DAG.getZExtOrTrunc(R, dl, VT);
26883     }
26884 
26885     SmallVector<SDValue, 16> LoAmt, HiAmt;
26886     for (int i = 0; i != NumElts; i += 16) {
26887       for (int j = 0; j != 8; ++j) {
26888         LoAmt.push_back(Amt.getOperand(i + j));
26889         HiAmt.push_back(Amt.getOperand(i + j + 8));
26890       }
26891     }
26892 
26893     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
26894     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
26895     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
26896 
26897     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
26898     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
26899     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
26900     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
26901     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
26902     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
26903     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
26904     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
26905     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
26906   }
26907 
26908   if (VT == MVT::v16i8 ||
26909       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
26910       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
26911     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
26912 
26913     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
26914       if (VT.is512BitVector()) {
26915         // On AVX512BW targets we make use of the fact that VSELECT lowers
26916         // to a masked blend which selects bytes based just on the sign bit
26917         // extracted to a mask.
26918         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
26919         V0 = DAG.getBitcast(VT, V0);
26920         V1 = DAG.getBitcast(VT, V1);
26921         Sel = DAG.getBitcast(VT, Sel);
26922         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
26923                            ISD::SETGT);
26924         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
26925       } else if (Subtarget.hasSSE41()) {
26926         // On SSE41 targets we make use of the fact that VSELECT lowers
26927         // to PBLENDVB which selects bytes based just on the sign bit.
26928         V0 = DAG.getBitcast(VT, V0);
26929         V1 = DAG.getBitcast(VT, V1);
26930         Sel = DAG.getBitcast(VT, Sel);
26931         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
26932       }
26933       // On pre-SSE41 targets we test for the sign bit by comparing to
26934       // zero - a negative value will set all bits of the lanes to true
26935       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
26936       SDValue Z = DAG.getConstant(0, dl, SelVT);
26937       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
26938       return DAG.getSelect(dl, SelVT, C, V0, V1);
26939     };
26940 
26941     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
26942     // We can safely do this using i16 shifts as we're only interested in
26943     // the 3 lower bits of each byte.
26944     Amt = DAG.getBitcast(ExtVT, Amt);
26945     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
26946     Amt = DAG.getBitcast(VT, Amt);
26947 
26948     if (Opc == ISD::SHL || Opc == ISD::SRL) {
26949       // r = VSELECT(r, shift(r, 4), a);
26950       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
26951       R = SignBitSelect(VT, Amt, M, R);
26952 
26953       // a += a
26954       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
26955 
26956       // r = VSELECT(r, shift(r, 2), a);
26957       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
26958       R = SignBitSelect(VT, Amt, M, R);
26959 
26960       // a += a
26961       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
26962 
26963       // return VSELECT(r, shift(r, 1), a);
26964       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
26965       R = SignBitSelect(VT, Amt, M, R);
26966       return R;
26967     }
26968 
26969     if (Opc == ISD::SRA) {
26970       // For SRA we need to unpack each byte to the higher byte of a i16 vector
26971       // so we can correctly sign extend. We don't care what happens to the
26972       // lower byte.
26973       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
26974       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
26975       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
26976       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
26977       ALo = DAG.getBitcast(ExtVT, ALo);
26978       AHi = DAG.getBitcast(ExtVT, AHi);
26979       RLo = DAG.getBitcast(ExtVT, RLo);
26980       RHi = DAG.getBitcast(ExtVT, RHi);
26981 
26982       // r = VSELECT(r, shift(r, 4), a);
26983       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
26984       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
26985       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
26986       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
26987 
26988       // a += a
26989       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
26990       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
26991 
26992       // r = VSELECT(r, shift(r, 2), a);
26993       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
26994       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
26995       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
26996       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
26997 
26998       // a += a
26999       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
27000       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
27001 
27002       // r = VSELECT(r, shift(r, 1), a);
27003       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
27004       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
27005       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
27006       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
27007 
27008       // Logical shift the result back to the lower byte, leaving a zero upper
27009       // byte meaning that we can safely pack with PACKUSWB.
27010       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
27011       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
27012       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27013     }
27014   }
27015 
27016   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
27017     MVT ExtVT = MVT::v8i32;
27018     SDValue Z = DAG.getConstant(0, dl, VT);
27019     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
27020     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
27021     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
27022     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
27023     ALo = DAG.getBitcast(ExtVT, ALo);
27024     AHi = DAG.getBitcast(ExtVT, AHi);
27025     RLo = DAG.getBitcast(ExtVT, RLo);
27026     RHi = DAG.getBitcast(ExtVT, RHi);
27027     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
27028     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
27029     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
27030     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
27031     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
27032   }
27033 
27034   if (VT == MVT::v8i16) {
27035     // If we have a constant shift amount, the non-SSE41 path is best as
27036     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
27037     bool UseSSE41 = Subtarget.hasSSE41() &&
27038                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27039 
27040     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
27041       // On SSE41 targets we make use of the fact that VSELECT lowers
27042       // to PBLENDVB which selects bytes based just on the sign bit.
27043       if (UseSSE41) {
27044         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
27045         V0 = DAG.getBitcast(ExtVT, V0);
27046         V1 = DAG.getBitcast(ExtVT, V1);
27047         Sel = DAG.getBitcast(ExtVT, Sel);
27048         return DAG.getBitcast(VT, DAG.getSelect(dl, ExtVT, Sel, V0, V1));
27049       }
27050       // On pre-SSE41 targets we splat the sign bit - a negative value will
27051       // set all bits of the lanes to true and VSELECT uses that in
27052       // its OR(AND(V0,C),AND(V1,~C)) lowering.
27053       SDValue C =
27054           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
27055       return DAG.getSelect(dl, VT, C, V0, V1);
27056     };
27057 
27058     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
27059     if (UseSSE41) {
27060       // On SSE41 targets we need to replicate the shift mask in both
27061       // bytes for PBLENDVB.
27062       Amt = DAG.getNode(
27063           ISD::OR, dl, VT,
27064           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
27065           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
27066     } else {
27067       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
27068     }
27069 
27070     // r = VSELECT(r, shift(r, 8), a);
27071     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
27072     R = SignBitSelect(Amt, M, R);
27073 
27074     // a += a
27075     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27076 
27077     // r = VSELECT(r, shift(r, 4), a);
27078     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
27079     R = SignBitSelect(Amt, M, R);
27080 
27081     // a += a
27082     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27083 
27084     // r = VSELECT(r, shift(r, 2), a);
27085     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
27086     R = SignBitSelect(Amt, M, R);
27087 
27088     // a += a
27089     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27090 
27091     // return VSELECT(r, shift(r, 1), a);
27092     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
27093     R = SignBitSelect(Amt, M, R);
27094     return R;
27095   }
27096 
27097   // Decompose 256-bit shifts into 128-bit shifts.
27098   if (VT.is256BitVector())
27099     return split256IntArith(Op, DAG);
27100 
27101   return SDValue();
27102 }
27103 
LowerRotate(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27104 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
27105                            SelectionDAG &DAG) {
27106   MVT VT = Op.getSimpleValueType();
27107   assert(VT.isVector() && "Custom lowering only for vector rotates!");
27108 
27109   SDLoc DL(Op);
27110   SDValue R = Op.getOperand(0);
27111   SDValue Amt = Op.getOperand(1);
27112   unsigned Opcode = Op.getOpcode();
27113   unsigned EltSizeInBits = VT.getScalarSizeInBits();
27114   int NumElts = VT.getVectorNumElements();
27115 
27116   // Check for constant splat rotation amount.
27117   APInt UndefElts;
27118   SmallVector<APInt, 32> EltBits;
27119   int CstSplatIndex = -1;
27120   if (getTargetConstantBitsFromNode(Amt, EltSizeInBits, UndefElts, EltBits))
27121     for (int i = 0; i != NumElts; ++i)
27122       if (!UndefElts[i]) {
27123         if (CstSplatIndex < 0 || EltBits[i] == EltBits[CstSplatIndex]) {
27124           CstSplatIndex = i;
27125           continue;
27126         }
27127         CstSplatIndex = -1;
27128         break;
27129       }
27130 
27131   // AVX512 implicitly uses modulo rotation amounts.
27132   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
27133     // Attempt to rotate by immediate.
27134     if (0 <= CstSplatIndex) {
27135       unsigned Op = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
27136       uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
27137       return DAG.getNode(Op, DL, VT, R,
27138                          DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
27139     }
27140 
27141     // Else, fall-back on VPROLV/VPRORV.
27142     return Op;
27143   }
27144 
27145   assert((Opcode == ISD::ROTL) && "Only ROTL supported");
27146 
27147   // XOP has 128-bit vector variable + immediate rotates.
27148   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
27149   // XOP implicitly uses modulo rotation amounts.
27150   if (Subtarget.hasXOP()) {
27151     if (VT.is256BitVector())
27152       return split256IntArith(Op, DAG);
27153     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
27154 
27155     // Attempt to rotate by immediate.
27156     if (0 <= CstSplatIndex) {
27157       uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
27158       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
27159                          DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
27160     }
27161 
27162     // Use general rotate by variable (per-element).
27163     return Op;
27164   }
27165 
27166   // Split 256-bit integers on pre-AVX2 targets.
27167   if (VT.is256BitVector() && !Subtarget.hasAVX2())
27168     return split256IntArith(Op, DAG);
27169 
27170   assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
27171           ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
27172            Subtarget.hasAVX2())) &&
27173          "Only vXi32/vXi16/vXi8 vector rotates supported");
27174 
27175   // Rotate by an uniform constant - expand back to shifts.
27176   if (0 <= CstSplatIndex)
27177     return SDValue();
27178 
27179   bool IsSplatAmt = DAG.isSplatValue(Amt);
27180 
27181   // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
27182   // the amount bit.
27183   if (EltSizeInBits == 8 && !IsSplatAmt) {
27184     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
27185       return SDValue();
27186 
27187     // We don't need ModuloAmt here as we just peek at individual bits.
27188     MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27189 
27190     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
27191       if (Subtarget.hasSSE41()) {
27192         // On SSE41 targets we make use of the fact that VSELECT lowers
27193         // to PBLENDVB which selects bytes based just on the sign bit.
27194         V0 = DAG.getBitcast(VT, V0);
27195         V1 = DAG.getBitcast(VT, V1);
27196         Sel = DAG.getBitcast(VT, Sel);
27197         return DAG.getBitcast(SelVT, DAG.getSelect(DL, VT, Sel, V0, V1));
27198       }
27199       // On pre-SSE41 targets we test for the sign bit by comparing to
27200       // zero - a negative value will set all bits of the lanes to true
27201       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
27202       SDValue Z = DAG.getConstant(0, DL, SelVT);
27203       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
27204       return DAG.getSelect(DL, SelVT, C, V0, V1);
27205     };
27206 
27207     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
27208     // We can safely do this using i16 shifts as we're only interested in
27209     // the 3 lower bits of each byte.
27210     Amt = DAG.getBitcast(ExtVT, Amt);
27211     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
27212     Amt = DAG.getBitcast(VT, Amt);
27213 
27214     // r = VSELECT(r, rot(r, 4), a);
27215     SDValue M;
27216     M = DAG.getNode(
27217         ISD::OR, DL, VT,
27218         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
27219         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
27220     R = SignBitSelect(VT, Amt, M, R);
27221 
27222     // a += a
27223     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
27224 
27225     // r = VSELECT(r, rot(r, 2), a);
27226     M = DAG.getNode(
27227         ISD::OR, DL, VT,
27228         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
27229         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
27230     R = SignBitSelect(VT, Amt, M, R);
27231 
27232     // a += a
27233     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
27234 
27235     // return VSELECT(r, rot(r, 1), a);
27236     M = DAG.getNode(
27237         ISD::OR, DL, VT,
27238         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
27239         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
27240     return SignBitSelect(VT, Amt, M, R);
27241   }
27242 
27243   // ISD::ROT* uses modulo rotate amounts.
27244   Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
27245                     DAG.getConstant(EltSizeInBits - 1, DL, VT));
27246 
27247   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27248   bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
27249                         SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
27250 
27251   // Fallback for splats + all supported variable shifts.
27252   // Fallback for non-constants AVX2 vXi16 as well.
27253   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
27254     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
27255     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
27256     SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
27257     SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
27258     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
27259   }
27260 
27261   // As with shifts, convert the rotation amount to a multiplication factor.
27262   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
27263   assert(Scale && "Failed to convert ROTL amount to scale");
27264 
27265   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
27266   if (EltSizeInBits == 16) {
27267     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
27268     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
27269     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
27270   }
27271 
27272   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
27273   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
27274   // that can then be OR'd with the lower 32-bits.
27275   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
27276   static const int OddMask[] = {1, -1, 3, -1};
27277   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
27278   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
27279 
27280   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
27281                               DAG.getBitcast(MVT::v2i64, R),
27282                               DAG.getBitcast(MVT::v2i64, Scale));
27283   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
27284                               DAG.getBitcast(MVT::v2i64, R13),
27285                               DAG.getBitcast(MVT::v2i64, Scale13));
27286   Res02 = DAG.getBitcast(VT, Res02);
27287   Res13 = DAG.getBitcast(VT, Res13);
27288 
27289   return DAG.getNode(ISD::OR, DL, VT,
27290                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
27291                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
27292 }
27293 
27294 /// Returns true if the operand type is exactly twice the native width, and
27295 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
27296 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
27297 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
needsCmpXchgNb(Type * MemType) const27298 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
27299   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
27300 
27301   if (OpWidth == 64)
27302     return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
27303   if (OpWidth == 128)
27304     return Subtarget.hasCmpxchg16b();
27305 
27306   return false;
27307 }
27308 
27309 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
27310 // TODO: In 32-bit mode, use FISTP when X87 is available?
shouldExpandAtomicStoreInIR(StoreInst * SI) const27311 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
27312   Type *MemType = SI->getValueOperand()->getType();
27313 
27314   bool NoImplicitFloatOps =
27315       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
27316   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
27317       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2())
27318     return false;
27319 
27320   return needsCmpXchgNb(MemType);
27321 }
27322 
27323 // Note: this turns large loads into lock cmpxchg8b/16b.
27324 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
27325 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const27326 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
27327   Type *MemType = LI->getType();
27328 
27329   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
27330   // can use movq to do the load. If we have X87 we can load into an 80-bit
27331   // X87 register and store it to a stack temporary.
27332   bool NoImplicitFloatOps =
27333       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
27334   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
27335       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
27336       (Subtarget.hasSSE2() || Subtarget.hasX87()))
27337     return AtomicExpansionKind::None;
27338 
27339   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
27340                                  : AtomicExpansionKind::None;
27341 }
27342 
27343 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const27344 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
27345   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
27346   Type *MemType = AI->getType();
27347 
27348   // If the operand is too big, we must see if cmpxchg8/16b is available
27349   // and default to library calls otherwise.
27350   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
27351     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
27352                                    : AtomicExpansionKind::None;
27353   }
27354 
27355   AtomicRMWInst::BinOp Op = AI->getOperation();
27356   switch (Op) {
27357   default:
27358     llvm_unreachable("Unknown atomic operation");
27359   case AtomicRMWInst::Xchg:
27360   case AtomicRMWInst::Add:
27361   case AtomicRMWInst::Sub:
27362     // It's better to use xadd, xsub or xchg for these in all cases.
27363     return AtomicExpansionKind::None;
27364   case AtomicRMWInst::Or:
27365   case AtomicRMWInst::And:
27366   case AtomicRMWInst::Xor:
27367     // If the atomicrmw's result isn't actually used, we can just add a "lock"
27368     // prefix to a normal instruction for these operations.
27369     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
27370                             : AtomicExpansionKind::None;
27371   case AtomicRMWInst::Nand:
27372   case AtomicRMWInst::Max:
27373   case AtomicRMWInst::Min:
27374   case AtomicRMWInst::UMax:
27375   case AtomicRMWInst::UMin:
27376   case AtomicRMWInst::FAdd:
27377   case AtomicRMWInst::FSub:
27378     // These always require a non-trivial set of data operations on x86. We must
27379     // use a cmpxchg loop.
27380     return AtomicExpansionKind::CmpXChg;
27381   }
27382 }
27383 
27384 LoadInst *
lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst * AI) const27385 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
27386   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
27387   Type *MemType = AI->getType();
27388   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
27389   // there is no benefit in turning such RMWs into loads, and it is actually
27390   // harmful as it introduces a mfence.
27391   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
27392     return nullptr;
27393 
27394   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
27395   // lowering available in lowerAtomicArith.
27396   // TODO: push more cases through this path.
27397   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
27398     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
27399         AI->use_empty())
27400       return nullptr;
27401 
27402   auto Builder = IRBuilder<>(AI);
27403   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
27404   auto SSID = AI->getSyncScopeID();
27405   // We must restrict the ordering to avoid generating loads with Release or
27406   // ReleaseAcquire orderings.
27407   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
27408 
27409   // Before the load we need a fence. Here is an example lifted from
27410   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
27411   // is required:
27412   // Thread 0:
27413   //   x.store(1, relaxed);
27414   //   r1 = y.fetch_add(0, release);
27415   // Thread 1:
27416   //   y.fetch_add(42, acquire);
27417   //   r2 = x.load(relaxed);
27418   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
27419   // lowered to just a load without a fence. A mfence flushes the store buffer,
27420   // making the optimization clearly correct.
27421   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
27422   // otherwise, we might be able to be more aggressive on relaxed idempotent
27423   // rmw. In practice, they do not look useful, so we don't try to be
27424   // especially clever.
27425   if (SSID == SyncScope::SingleThread)
27426     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
27427     // the IR level, so we must wrap it in an intrinsic.
27428     return nullptr;
27429 
27430   if (!Subtarget.hasMFence())
27431     // FIXME: it might make sense to use a locked operation here but on a
27432     // different cache-line to prevent cache-line bouncing. In practice it
27433     // is probably a small win, and x86 processors without mfence are rare
27434     // enough that we do not bother.
27435     return nullptr;
27436 
27437   Function *MFence =
27438       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
27439   Builder.CreateCall(MFence, {});
27440 
27441   // Finally we can emit the atomic load.
27442   LoadInst *Loaded =
27443       Builder.CreateAlignedLoad(AI->getType(), AI->getPointerOperand(),
27444                                 AI->getType()->getPrimitiveSizeInBits());
27445   Loaded->setAtomic(Order, SSID);
27446   AI->replaceAllUsesWith(Loaded);
27447   AI->eraseFromParent();
27448   return Loaded;
27449 }
27450 
lowerAtomicStoreAsStoreSDNode(const StoreInst & SI) const27451 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
27452   if (!SI.isUnordered())
27453     return false;
27454   return ExperimentalUnorderedISEL;
27455 }
lowerAtomicLoadAsLoadSDNode(const LoadInst & LI) const27456 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
27457   if (!LI.isUnordered())
27458     return false;
27459   return ExperimentalUnorderedISEL;
27460 }
27461 
27462 
27463 /// Emit a locked operation on a stack location which does not change any
27464 /// memory location, but does involve a lock prefix.  Location is chosen to be
27465 /// a) very likely accessed only by a single thread to minimize cache traffic,
27466 /// and b) definitely dereferenceable.  Returns the new Chain result.
emitLockedStackOp(SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue Chain,SDLoc DL)27467 static SDValue emitLockedStackOp(SelectionDAG &DAG,
27468                                  const X86Subtarget &Subtarget,
27469                                  SDValue Chain, SDLoc DL) {
27470   // Implementation notes:
27471   // 1) LOCK prefix creates a full read/write reordering barrier for memory
27472   // operations issued by the current processor.  As such, the location
27473   // referenced is not relevant for the ordering properties of the instruction.
27474   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
27475   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
27476   // 2) Using an immediate operand appears to be the best encoding choice
27477   // here since it doesn't require an extra register.
27478   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
27479   // is small enough it might just be measurement noise.)
27480   // 4) When choosing offsets, there are several contributing factors:
27481   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
27482   //      line aligned stack object to improve this case.)
27483   //   b) To minimize our chances of introducing a false dependence, we prefer
27484   //      to offset the stack usage from TOS slightly.
27485   //   c) To minimize concerns about cross thread stack usage - in particular,
27486   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
27487   //      captures state in the TOS frame and accesses it from many threads -
27488   //      we want to use an offset such that the offset is in a distinct cache
27489   //      line from the TOS frame.
27490   //
27491   // For a general discussion of the tradeoffs and benchmark results, see:
27492   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
27493 
27494   auto &MF = DAG.getMachineFunction();
27495   auto &TFL = *Subtarget.getFrameLowering();
27496   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
27497 
27498   if (Subtarget.is64Bit()) {
27499     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
27500     SDValue Ops[] = {
27501       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
27502       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
27503       DAG.getRegister(0, MVT::i64),                         // Index
27504       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
27505       DAG.getRegister(0, MVT::i16),                         // Segment.
27506       Zero,
27507       Chain};
27508     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
27509                                      MVT::Other, Ops);
27510     return SDValue(Res, 1);
27511   }
27512 
27513   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
27514   SDValue Ops[] = {
27515     DAG.getRegister(X86::ESP, MVT::i32),            // Base
27516     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
27517     DAG.getRegister(0, MVT::i32),                   // Index
27518     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
27519     DAG.getRegister(0, MVT::i16),                   // Segment.
27520     Zero,
27521     Chain
27522   };
27523   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
27524                                    MVT::Other, Ops);
27525   return SDValue(Res, 1);
27526 }
27527 
LowerATOMIC_FENCE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27528 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
27529                                  SelectionDAG &DAG) {
27530   SDLoc dl(Op);
27531   AtomicOrdering FenceOrdering =
27532       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
27533   SyncScope::ID FenceSSID =
27534       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
27535 
27536   // The only fence that needs an instruction is a sequentially-consistent
27537   // cross-thread fence.
27538   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
27539       FenceSSID == SyncScope::System) {
27540     if (Subtarget.hasMFence())
27541       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
27542 
27543     SDValue Chain = Op.getOperand(0);
27544     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
27545   }
27546 
27547   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
27548   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
27549 }
27550 
LowerCMP_SWAP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27551 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
27552                              SelectionDAG &DAG) {
27553   MVT T = Op.getSimpleValueType();
27554   SDLoc DL(Op);
27555   unsigned Reg = 0;
27556   unsigned size = 0;
27557   switch(T.SimpleTy) {
27558   default: llvm_unreachable("Invalid value type!");
27559   case MVT::i8:  Reg = X86::AL;  size = 1; break;
27560   case MVT::i16: Reg = X86::AX;  size = 2; break;
27561   case MVT::i32: Reg = X86::EAX; size = 4; break;
27562   case MVT::i64:
27563     assert(Subtarget.is64Bit() && "Node not type legal!");
27564     Reg = X86::RAX; size = 8;
27565     break;
27566   }
27567   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
27568                                   Op.getOperand(2), SDValue());
27569   SDValue Ops[] = { cpIn.getValue(0),
27570                     Op.getOperand(1),
27571                     Op.getOperand(3),
27572                     DAG.getTargetConstant(size, DL, MVT::i8),
27573                     cpIn.getValue(1) };
27574   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
27575   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
27576   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
27577                                            Ops, T, MMO);
27578 
27579   SDValue cpOut =
27580     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
27581   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
27582                                       MVT::i32, cpOut.getValue(2));
27583   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
27584 
27585   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27586                      cpOut, Success, EFLAGS.getValue(1));
27587 }
27588 
27589 // Create MOVMSKB, taking into account whether we need to split for AVX1.
getPMOVMSKB(const SDLoc & DL,SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)27590 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
27591                            const X86Subtarget &Subtarget) {
27592   MVT InVT = V.getSimpleValueType();
27593 
27594   if (InVT == MVT::v64i8) {
27595     SDValue Lo, Hi;
27596     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
27597     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
27598     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
27599     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
27600     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
27601     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
27602                      DAG.getConstant(32, DL, MVT::i8));
27603     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
27604   }
27605   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
27606     SDValue Lo, Hi;
27607     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
27608     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
27609     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
27610     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
27611                      DAG.getConstant(16, DL, MVT::i8));
27612     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
27613   }
27614 
27615   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
27616 }
27617 
LowerBITCAST(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27618 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
27619                             SelectionDAG &DAG) {
27620   SDValue Src = Op.getOperand(0);
27621   MVT SrcVT = Src.getSimpleValueType();
27622   MVT DstVT = Op.getSimpleValueType();
27623 
27624   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
27625   // half to v32i1 and concatenating the result.
27626   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
27627     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
27628     assert(Subtarget.hasBWI() && "Expected BWI target");
27629     SDLoc dl(Op);
27630     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
27631                              DAG.getIntPtrConstant(0, dl));
27632     Lo = DAG.getBitcast(MVT::v32i1, Lo);
27633     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
27634                              DAG.getIntPtrConstant(1, dl));
27635     Hi = DAG.getBitcast(MVT::v32i1, Hi);
27636     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
27637   }
27638 
27639   // Custom splitting for BWI types when AVX512F is available but BWI isn't.
27640   if ((SrcVT == MVT::v32i16 || SrcVT == MVT::v64i8) && DstVT.isVector() &&
27641     DAG.getTargetLoweringInfo().isTypeLegal(DstVT)) {
27642     SDLoc dl(Op);
27643     SDValue Lo, Hi;
27644     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
27645     MVT CastVT = DstVT.getHalfNumVectorElementsVT();
27646     Lo = DAG.getBitcast(CastVT, Lo);
27647     Hi = DAG.getBitcast(CastVT, Hi);
27648     return DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
27649   }
27650 
27651   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
27652   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
27653     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
27654     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
27655     SDLoc DL(Op);
27656     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
27657     V = getPMOVMSKB(DL, V, DAG, Subtarget);
27658     return DAG.getZExtOrTrunc(V, DL, DstVT);
27659   }
27660 
27661   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
27662           SrcVT == MVT::i64) && "Unexpected VT!");
27663 
27664   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
27665   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
27666       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
27667     // This conversion needs to be expanded.
27668     return SDValue();
27669 
27670   SDLoc dl(Op);
27671   if (SrcVT.isVector()) {
27672     // Widen the vector in input in the case of MVT::v2i32.
27673     // Example: from MVT::v2i32 to MVT::v4i32.
27674     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
27675                                  SrcVT.getVectorNumElements() * 2);
27676     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
27677                       DAG.getUNDEF(SrcVT));
27678   } else {
27679     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
27680            "Unexpected source type in LowerBITCAST");
27681     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
27682   }
27683 
27684   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
27685   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
27686 
27687   if (DstVT == MVT::x86mmx)
27688     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
27689 
27690   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
27691                      DAG.getIntPtrConstant(0, dl));
27692 }
27693 
27694 /// Compute the horizontal sum of bytes in V for the elements of VT.
27695 ///
27696 /// Requires V to be a byte vector and VT to be an integer vector type with
27697 /// wider elements than V's type. The width of the elements of VT determines
27698 /// how many bytes of V are summed horizontally to produce each element of the
27699 /// result.
LowerHorizontalByteSum(SDValue V,MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG)27700 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
27701                                       const X86Subtarget &Subtarget,
27702                                       SelectionDAG &DAG) {
27703   SDLoc DL(V);
27704   MVT ByteVecVT = V.getSimpleValueType();
27705   MVT EltVT = VT.getVectorElementType();
27706   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
27707          "Expected value to have byte element type.");
27708   assert(EltVT != MVT::i8 &&
27709          "Horizontal byte sum only makes sense for wider elements!");
27710   unsigned VecSize = VT.getSizeInBits();
27711   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
27712 
27713   // PSADBW instruction horizontally add all bytes and leave the result in i64
27714   // chunks, thus directly computes the pop count for v2i64 and v4i64.
27715   if (EltVT == MVT::i64) {
27716     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
27717     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
27718     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
27719     return DAG.getBitcast(VT, V);
27720   }
27721 
27722   if (EltVT == MVT::i32) {
27723     // We unpack the low half and high half into i32s interleaved with zeros so
27724     // that we can use PSADBW to horizontally sum them. The most useful part of
27725     // this is that it lines up the results of two PSADBW instructions to be
27726     // two v2i64 vectors which concatenated are the 4 population counts. We can
27727     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
27728     SDValue Zeros = DAG.getConstant(0, DL, VT);
27729     SDValue V32 = DAG.getBitcast(VT, V);
27730     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
27731     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
27732 
27733     // Do the horizontal sums into two v2i64s.
27734     Zeros = DAG.getConstant(0, DL, ByteVecVT);
27735     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
27736     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
27737                       DAG.getBitcast(ByteVecVT, Low), Zeros);
27738     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
27739                        DAG.getBitcast(ByteVecVT, High), Zeros);
27740 
27741     // Merge them together.
27742     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
27743     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
27744                     DAG.getBitcast(ShortVecVT, Low),
27745                     DAG.getBitcast(ShortVecVT, High));
27746 
27747     return DAG.getBitcast(VT, V);
27748   }
27749 
27750   // The only element type left is i16.
27751   assert(EltVT == MVT::i16 && "Unknown how to handle type");
27752 
27753   // To obtain pop count for each i16 element starting from the pop count for
27754   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
27755   // right by 8. It is important to shift as i16s as i8 vector shift isn't
27756   // directly supported.
27757   SDValue ShifterV = DAG.getConstant(8, DL, VT);
27758   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
27759   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
27760                   DAG.getBitcast(ByteVecVT, V));
27761   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
27762 }
27763 
LowerVectorCTPOPInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)27764 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
27765                                         const X86Subtarget &Subtarget,
27766                                         SelectionDAG &DAG) {
27767   MVT VT = Op.getSimpleValueType();
27768   MVT EltVT = VT.getVectorElementType();
27769   int NumElts = VT.getVectorNumElements();
27770   (void)EltVT;
27771   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
27772 
27773   // Implement a lookup table in register by using an algorithm based on:
27774   // http://wm.ite.pl/articles/sse-popcount.html
27775   //
27776   // The general idea is that every lower byte nibble in the input vector is an
27777   // index into a in-register pre-computed pop count table. We then split up the
27778   // input vector in two new ones: (1) a vector with only the shifted-right
27779   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
27780   // masked out higher ones) for each byte. PSHUFB is used separately with both
27781   // to index the in-register table. Next, both are added and the result is a
27782   // i8 vector where each element contains the pop count for input byte.
27783   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
27784                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
27785                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
27786                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
27787 
27788   SmallVector<SDValue, 64> LUTVec;
27789   for (int i = 0; i < NumElts; ++i)
27790     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
27791   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
27792   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
27793 
27794   // High nibbles
27795   SDValue FourV = DAG.getConstant(4, DL, VT);
27796   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
27797 
27798   // Low nibbles
27799   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
27800 
27801   // The input vector is used as the shuffle mask that index elements into the
27802   // LUT. After counting low and high nibbles, add the vector to obtain the
27803   // final pop count per i8 element.
27804   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
27805   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
27806   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
27807 }
27808 
27809 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
27810 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
LowerVectorCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27811 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
27812                                 SelectionDAG &DAG) {
27813   MVT VT = Op.getSimpleValueType();
27814   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
27815          "Unknown CTPOP type to handle");
27816   SDLoc DL(Op.getNode());
27817   SDValue Op0 = Op.getOperand(0);
27818 
27819   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
27820   if (Subtarget.hasVPOPCNTDQ()) {
27821     unsigned NumElems = VT.getVectorNumElements();
27822     assert((VT.getVectorElementType() == MVT::i8 ||
27823             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
27824     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
27825       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
27826       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
27827       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
27828       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
27829     }
27830   }
27831 
27832   // Decompose 256-bit ops into smaller 128-bit ops.
27833   if (VT.is256BitVector() && !Subtarget.hasInt256())
27834     return Lower256IntUnary(Op, DAG);
27835 
27836   // Decompose 512-bit ops into smaller 256-bit ops.
27837   if (VT.is512BitVector() && !Subtarget.hasBWI())
27838     return Lower512IntUnary(Op, DAG);
27839 
27840   // For element types greater than i8, do vXi8 pop counts and a bytesum.
27841   if (VT.getScalarType() != MVT::i8) {
27842     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
27843     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
27844     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
27845     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
27846   }
27847 
27848   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
27849   if (!Subtarget.hasSSSE3())
27850     return SDValue();
27851 
27852   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
27853 }
27854 
LowerCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27855 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
27856                           SelectionDAG &DAG) {
27857   assert(Op.getSimpleValueType().isVector() &&
27858          "We only do custom lowering for vector population count.");
27859   return LowerVectorCTPOP(Op, Subtarget, DAG);
27860 }
27861 
LowerBITREVERSE_XOP(SDValue Op,SelectionDAG & DAG)27862 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
27863   MVT VT = Op.getSimpleValueType();
27864   SDValue In = Op.getOperand(0);
27865   SDLoc DL(Op);
27866 
27867   // For scalars, its still beneficial to transfer to/from the SIMD unit to
27868   // perform the BITREVERSE.
27869   if (!VT.isVector()) {
27870     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
27871     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
27872     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
27873     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
27874                        DAG.getIntPtrConstant(0, DL));
27875   }
27876 
27877   int NumElts = VT.getVectorNumElements();
27878   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
27879 
27880   // Decompose 256-bit ops into smaller 128-bit ops.
27881   if (VT.is256BitVector())
27882     return Lower256IntUnary(Op, DAG);
27883 
27884   assert(VT.is128BitVector() &&
27885          "Only 128-bit vector bitreverse lowering supported.");
27886 
27887   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
27888   // perform the BSWAP in the shuffle.
27889   // Its best to shuffle using the second operand as this will implicitly allow
27890   // memory folding for multiple vectors.
27891   SmallVector<SDValue, 16> MaskElts;
27892   for (int i = 0; i != NumElts; ++i) {
27893     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
27894       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
27895       int PermuteByte = SourceByte | (2 << 5);
27896       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
27897     }
27898   }
27899 
27900   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
27901   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
27902   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
27903                     Res, Mask);
27904   return DAG.getBitcast(VT, Res);
27905 }
27906 
LowerBITREVERSE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27907 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
27908                                SelectionDAG &DAG) {
27909   MVT VT = Op.getSimpleValueType();
27910 
27911   if (Subtarget.hasXOP() && !VT.is512BitVector())
27912     return LowerBITREVERSE_XOP(Op, DAG);
27913 
27914   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
27915 
27916   SDValue In = Op.getOperand(0);
27917   SDLoc DL(Op);
27918 
27919   // Split v8i64/v16i32 without BWI so that we can still use the PSHUFB
27920   // lowering.
27921   if (VT == MVT::v8i64 || VT == MVT::v16i32) {
27922     assert(!Subtarget.hasBWI() && "BWI should Expand BITREVERSE");
27923     return Lower512IntUnary(Op, DAG);
27924   }
27925 
27926   unsigned NumElts = VT.getVectorNumElements();
27927   assert(VT.getScalarType() == MVT::i8 &&
27928          "Only byte vector BITREVERSE supported");
27929 
27930   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
27931   if (VT.is256BitVector() && !Subtarget.hasInt256())
27932     return Lower256IntUnary(Op, DAG);
27933 
27934   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
27935   // two nibbles and a PSHUFB lookup to find the bitreverse of each
27936   // 0-15 value (moved to the other nibble).
27937   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
27938   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
27939   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
27940 
27941   const int LoLUT[16] = {
27942       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
27943       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
27944       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
27945       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
27946   const int HiLUT[16] = {
27947       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
27948       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
27949       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
27950       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
27951 
27952   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
27953   for (unsigned i = 0; i < NumElts; ++i) {
27954     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
27955     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
27956   }
27957 
27958   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
27959   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
27960   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
27961   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
27962   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
27963 }
27964 
lowerAtomicArithWithLOCK(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)27965 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
27966                                         const X86Subtarget &Subtarget) {
27967   unsigned NewOpc = 0;
27968   switch (N->getOpcode()) {
27969   case ISD::ATOMIC_LOAD_ADD:
27970     NewOpc = X86ISD::LADD;
27971     break;
27972   case ISD::ATOMIC_LOAD_SUB:
27973     NewOpc = X86ISD::LSUB;
27974     break;
27975   case ISD::ATOMIC_LOAD_OR:
27976     NewOpc = X86ISD::LOR;
27977     break;
27978   case ISD::ATOMIC_LOAD_XOR:
27979     NewOpc = X86ISD::LXOR;
27980     break;
27981   case ISD::ATOMIC_LOAD_AND:
27982     NewOpc = X86ISD::LAND;
27983     break;
27984   default:
27985     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
27986   }
27987 
27988   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
27989 
27990   return DAG.getMemIntrinsicNode(
27991       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
27992       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
27993       /*MemVT=*/N->getSimpleValueType(0), MMO);
27994 }
27995 
27996 /// Lower atomic_load_ops into LOCK-prefixed operations.
lowerAtomicArith(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)27997 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
27998                                 const X86Subtarget &Subtarget) {
27999   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
28000   SDValue Chain = N->getOperand(0);
28001   SDValue LHS = N->getOperand(1);
28002   SDValue RHS = N->getOperand(2);
28003   unsigned Opc = N->getOpcode();
28004   MVT VT = N->getSimpleValueType(0);
28005   SDLoc DL(N);
28006 
28007   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
28008   // can only be lowered when the result is unused.  They should have already
28009   // been transformed into a cmpxchg loop in AtomicExpand.
28010   if (N->hasAnyUseOfValue(0)) {
28011     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
28012     // select LXADD if LOCK_SUB can't be selected.
28013     if (Opc == ISD::ATOMIC_LOAD_SUB) {
28014       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
28015       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
28016                            RHS, AN->getMemOperand());
28017     }
28018     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
28019            "Used AtomicRMW ops other than Add should have been expanded!");
28020     return N;
28021   }
28022 
28023   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
28024   // The core idea here is that since the memory location isn't actually
28025   // changing, all we need is a lowering for the *ordering* impacts of the
28026   // atomicrmw.  As such, we can chose a different operation and memory
28027   // location to minimize impact on other code.
28028   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
28029     // On X86, the only ordering which actually requires an instruction is
28030     // seq_cst which isn't SingleThread, everything just needs to be preserved
28031     // during codegen and then dropped. Note that we expect (but don't assume),
28032     // that orderings other than seq_cst and acq_rel have been canonicalized to
28033     // a store or load.
28034     if (AN->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
28035         AN->getSyncScopeID() == SyncScope::System) {
28036       // Prefer a locked operation against a stack location to minimize cache
28037       // traffic.  This assumes that stack locations are very likely to be
28038       // accessed only by the owning thread.
28039       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
28040       assert(!N->hasAnyUseOfValue(0));
28041       // NOTE: The getUNDEF is needed to give something for the unused result 0.
28042       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28043                          DAG.getUNDEF(VT), NewChain);
28044     }
28045     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
28046     SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
28047     assert(!N->hasAnyUseOfValue(0));
28048     // NOTE: The getUNDEF is needed to give something for the unused result 0.
28049     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28050                        DAG.getUNDEF(VT), NewChain);
28051   }
28052 
28053   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
28054   // RAUW the chain, but don't worry about the result, as it's unused.
28055   assert(!N->hasAnyUseOfValue(0));
28056   // NOTE: The getUNDEF is needed to give something for the unused result 0.
28057   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28058                      DAG.getUNDEF(VT), LockOp.getValue(1));
28059 }
28060 
LowerATOMIC_STORE(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)28061 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
28062                                  const X86Subtarget &Subtarget) {
28063   auto *Node = cast<AtomicSDNode>(Op.getNode());
28064   SDLoc dl(Node);
28065   EVT VT = Node->getMemoryVT();
28066 
28067   bool IsSeqCst = Node->getOrdering() == AtomicOrdering::SequentiallyConsistent;
28068   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
28069 
28070   // If this store is not sequentially consistent and the type is legal
28071   // we can just keep it.
28072   if (!IsSeqCst && IsTypeLegal)
28073     return Op;
28074 
28075   if (VT == MVT::i64 && !IsTypeLegal) {
28076     // For illegal i64 atomic_stores, we can try to use MOVQ if SSE2 is enabled.
28077     // FIXME: Use movlps with SSE1.
28078     // FIXME: Use fist with X87.
28079     bool NoImplicitFloatOps =
28080         DAG.getMachineFunction().getFunction().hasFnAttribute(
28081             Attribute::NoImplicitFloat);
28082     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
28083         Subtarget.hasSSE2()) {
28084       SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
28085                                      Node->getOperand(2));
28086       SDVTList Tys = DAG.getVTList(MVT::Other);
28087       SDValue Ops[] = { Node->getChain(), SclToVec, Node->getBasePtr() };
28088       SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys,
28089                                               Ops, MVT::i64,
28090                                               Node->getMemOperand());
28091 
28092       // If this is a sequentially consistent store, also emit an appropriate
28093       // barrier.
28094       if (IsSeqCst)
28095         Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
28096 
28097       return Chain;
28098     }
28099   }
28100 
28101   // Convert seq_cst store -> xchg
28102   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
28103   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
28104   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
28105                                Node->getMemoryVT(),
28106                                Node->getOperand(0),
28107                                Node->getOperand(1), Node->getOperand(2),
28108                                Node->getMemOperand());
28109   return Swap.getValue(1);
28110 }
28111 
LowerADDSUBCARRY(SDValue Op,SelectionDAG & DAG)28112 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
28113   SDNode *N = Op.getNode();
28114   MVT VT = N->getSimpleValueType(0);
28115 
28116   // Let legalize expand this if it isn't a legal type yet.
28117   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
28118     return SDValue();
28119 
28120   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28121   SDLoc DL(N);
28122 
28123   // Set the carry flag.
28124   SDValue Carry = Op.getOperand(2);
28125   EVT CarryVT = Carry.getValueType();
28126   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
28127   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
28128                       Carry, DAG.getConstant(NegOne, DL, CarryVT));
28129 
28130   unsigned Opc = Op.getOpcode() == ISD::ADDCARRY ? X86ISD::ADC : X86ISD::SBB;
28131   SDValue Sum = DAG.getNode(Opc, DL, VTs, Op.getOperand(0),
28132                             Op.getOperand(1), Carry.getValue(1));
28133 
28134   SDValue SetCC = getSETCC(X86::COND_B, Sum.getValue(1), DL, DAG);
28135   if (N->getValueType(1) == MVT::i1)
28136     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
28137 
28138   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
28139 }
28140 
LowerFSINCOS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28141 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
28142                             SelectionDAG &DAG) {
28143   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
28144 
28145   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
28146   // which returns the values as { float, float } (in XMM0) or
28147   // { double, double } (which is returned in XMM0, XMM1).
28148   SDLoc dl(Op);
28149   SDValue Arg = Op.getOperand(0);
28150   EVT ArgVT = Arg.getValueType();
28151   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
28152 
28153   TargetLowering::ArgListTy Args;
28154   TargetLowering::ArgListEntry Entry;
28155 
28156   Entry.Node = Arg;
28157   Entry.Ty = ArgTy;
28158   Entry.IsSExt = false;
28159   Entry.IsZExt = false;
28160   Args.push_back(Entry);
28161 
28162   bool isF64 = ArgVT == MVT::f64;
28163   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
28164   // the small struct {f32, f32} is returned in (eax, edx). For f64,
28165   // the results are returned via SRet in memory.
28166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28167   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
28168   const char *LibcallName = TLI.getLibcallName(LC);
28169   SDValue Callee =
28170       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
28171 
28172   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
28173                       : (Type *)VectorType::get(ArgTy, 4);
28174 
28175   TargetLowering::CallLoweringInfo CLI(DAG);
28176   CLI.setDebugLoc(dl)
28177       .setChain(DAG.getEntryNode())
28178       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
28179 
28180   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
28181 
28182   if (isF64)
28183     // Returned in xmm0 and xmm1.
28184     return CallResult.first;
28185 
28186   // Returned in bits 0:31 and 32:64 xmm0.
28187   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
28188                                CallResult.first, DAG.getIntPtrConstant(0, dl));
28189   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
28190                                CallResult.first, DAG.getIntPtrConstant(1, dl));
28191   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
28192   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
28193 }
28194 
28195 /// Widen a vector input to a vector of NVT.  The
28196 /// input vector must have the same element type as NVT.
ExtendToType(SDValue InOp,MVT NVT,SelectionDAG & DAG,bool FillWithZeroes=false)28197 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
28198                             bool FillWithZeroes = false) {
28199   // Check if InOp already has the right width.
28200   MVT InVT = InOp.getSimpleValueType();
28201   if (InVT == NVT)
28202     return InOp;
28203 
28204   if (InOp.isUndef())
28205     return DAG.getUNDEF(NVT);
28206 
28207   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
28208          "input and widen element type must match");
28209 
28210   unsigned InNumElts = InVT.getVectorNumElements();
28211   unsigned WidenNumElts = NVT.getVectorNumElements();
28212   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
28213          "Unexpected request for vector widening");
28214 
28215   SDLoc dl(InOp);
28216   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
28217       InOp.getNumOperands() == 2) {
28218     SDValue N1 = InOp.getOperand(1);
28219     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
28220         N1.isUndef()) {
28221       InOp = InOp.getOperand(0);
28222       InVT = InOp.getSimpleValueType();
28223       InNumElts = InVT.getVectorNumElements();
28224     }
28225   }
28226   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
28227       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
28228     SmallVector<SDValue, 16> Ops;
28229     for (unsigned i = 0; i < InNumElts; ++i)
28230       Ops.push_back(InOp.getOperand(i));
28231 
28232     EVT EltVT = InOp.getOperand(0).getValueType();
28233 
28234     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
28235       DAG.getUNDEF(EltVT);
28236     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
28237       Ops.push_back(FillVal);
28238     return DAG.getBuildVector(NVT, dl, Ops);
28239   }
28240   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
28241     DAG.getUNDEF(NVT);
28242   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
28243                      InOp, DAG.getIntPtrConstant(0, dl));
28244 }
28245 
LowerMSCATTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28246 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
28247                              SelectionDAG &DAG) {
28248   assert(Subtarget.hasAVX512() &&
28249          "MGATHER/MSCATTER are supported on AVX-512 arch only");
28250 
28251   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
28252   SDValue Src = N->getValue();
28253   MVT VT = Src.getSimpleValueType();
28254   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
28255   SDLoc dl(Op);
28256 
28257   SDValue Scale = N->getScale();
28258   SDValue Index = N->getIndex();
28259   SDValue Mask = N->getMask();
28260   SDValue Chain = N->getChain();
28261   SDValue BasePtr = N->getBasePtr();
28262 
28263   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
28264     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
28265     // If the index is v2i64 and we have VLX we can use xmm for data and index.
28266     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
28267       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28268       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
28269       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
28270       SDVTList VTs = DAG.getVTList(MVT::v2i1, MVT::Other);
28271       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
28272       SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
28273           VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
28274       return SDValue(NewScatter.getNode(), 1);
28275     }
28276     return SDValue();
28277   }
28278 
28279   MVT IndexVT = Index.getSimpleValueType();
28280   MVT MaskVT = Mask.getSimpleValueType();
28281 
28282   // If the index is v2i32, we're being called by type legalization and we
28283   // should just let the default handling take care of it.
28284   if (IndexVT == MVT::v2i32)
28285     return SDValue();
28286 
28287   // If we don't have VLX and neither the passthru or index is 512-bits, we
28288   // need to widen until one is.
28289   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
28290       !Index.getSimpleValueType().is512BitVector()) {
28291     // Determine how much we need to widen by to get a 512-bit type.
28292     unsigned Factor = std::min(512/VT.getSizeInBits(),
28293                                512/IndexVT.getSizeInBits());
28294     unsigned NumElts = VT.getVectorNumElements() * Factor;
28295 
28296     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
28297     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
28298     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
28299 
28300     Src = ExtendToType(Src, VT, DAG);
28301     Index = ExtendToType(Index, IndexVT, DAG);
28302     Mask = ExtendToType(Mask, MaskVT, DAG, true);
28303   }
28304 
28305   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
28306   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
28307   SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
28308       VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
28309   return SDValue(NewScatter.getNode(), 1);
28310 }
28311 
LowerMLOAD(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28312 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
28313                           SelectionDAG &DAG) {
28314 
28315   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
28316   MVT VT = Op.getSimpleValueType();
28317   MVT ScalarVT = VT.getScalarType();
28318   SDValue Mask = N->getMask();
28319   MVT MaskVT = Mask.getSimpleValueType();
28320   SDValue PassThru = N->getPassThru();
28321   SDLoc dl(Op);
28322 
28323   // Handle AVX masked loads which don't support passthru other than 0.
28324   if (MaskVT.getVectorElementType() != MVT::i1) {
28325     // We also allow undef in the isel pattern.
28326     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
28327       return Op;
28328 
28329     SDValue NewLoad = DAG.getMaskedLoad(
28330         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
28331         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
28332         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
28333         N->isExpandingLoad());
28334     // Emit a blend.
28335     SDValue Select = DAG.getNode(ISD::VSELECT, dl, MaskVT, Mask, NewLoad,
28336                                  PassThru);
28337     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
28338   }
28339 
28340   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
28341          "Expanding masked load is supported on AVX-512 target only!");
28342 
28343   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
28344          "Expanding masked load is supported for 32 and 64-bit types only!");
28345 
28346   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
28347          "Cannot lower masked load op.");
28348 
28349   assert((ScalarVT.getSizeInBits() >= 32 ||
28350           (Subtarget.hasBWI() &&
28351               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
28352          "Unsupported masked load op.");
28353 
28354   // This operation is legal for targets with VLX, but without
28355   // VLX the vector should be widened to 512 bit
28356   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
28357   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
28358   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
28359 
28360   // Mask element has to be i1.
28361   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
28362          "Unexpected mask type");
28363 
28364   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
28365 
28366   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
28367   SDValue NewLoad = DAG.getMaskedLoad(
28368       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
28369       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
28370       N->getExtensionType(), N->isExpandingLoad());
28371 
28372   SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
28373                                NewLoad.getValue(0),
28374                                DAG.getIntPtrConstant(0, dl));
28375   SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
28376   return DAG.getMergeValues(RetOps, dl);
28377 }
28378 
LowerMSTORE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28379 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
28380                            SelectionDAG &DAG) {
28381   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
28382   SDValue DataToStore = N->getValue();
28383   MVT VT = DataToStore.getSimpleValueType();
28384   MVT ScalarVT = VT.getScalarType();
28385   SDValue Mask = N->getMask();
28386   SDLoc dl(Op);
28387 
28388   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
28389          "Expanding masked load is supported on AVX-512 target only!");
28390 
28391   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
28392          "Expanding masked load is supported for 32 and 64-bit types only!");
28393 
28394   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
28395          "Cannot lower masked store op.");
28396 
28397   assert((ScalarVT.getSizeInBits() >= 32 ||
28398           (Subtarget.hasBWI() &&
28399               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
28400           "Unsupported masked store op.");
28401 
28402   // This operation is legal for targets with VLX, but without
28403   // VLX the vector should be widened to 512 bit
28404   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
28405   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
28406 
28407   // Mask element has to be i1.
28408   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
28409          "Unexpected mask type");
28410 
28411   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
28412 
28413   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
28414   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
28415   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
28416                             N->getOffset(), Mask, N->getMemoryVT(),
28417                             N->getMemOperand(), N->getAddressingMode(),
28418                             N->isTruncatingStore(), N->isCompressingStore());
28419 }
28420 
LowerMGATHER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28421 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
28422                             SelectionDAG &DAG) {
28423   assert(Subtarget.hasAVX2() &&
28424          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
28425 
28426   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
28427   SDLoc dl(Op);
28428   MVT VT = Op.getSimpleValueType();
28429   SDValue Index = N->getIndex();
28430   SDValue Mask = N->getMask();
28431   SDValue PassThru = N->getPassThru();
28432   MVT IndexVT = Index.getSimpleValueType();
28433   MVT MaskVT = Mask.getSimpleValueType();
28434 
28435   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
28436 
28437   // If the index is v2i32, we're being called by type legalization.
28438   if (IndexVT == MVT::v2i32)
28439     return SDValue();
28440 
28441   // If we don't have VLX and neither the passthru or index is 512-bits, we
28442   // need to widen until one is.
28443   MVT OrigVT = VT;
28444   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
28445       !IndexVT.is512BitVector()) {
28446     // Determine how much we need to widen by to get a 512-bit type.
28447     unsigned Factor = std::min(512/VT.getSizeInBits(),
28448                                512/IndexVT.getSizeInBits());
28449 
28450     unsigned NumElts = VT.getVectorNumElements() * Factor;
28451 
28452     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
28453     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
28454     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
28455 
28456     PassThru = ExtendToType(PassThru, VT, DAG);
28457     Index = ExtendToType(Index, IndexVT, DAG);
28458     Mask = ExtendToType(Mask, MaskVT, DAG, true);
28459   }
28460 
28461   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
28462                     N->getScale() };
28463   SDValue NewGather = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
28464       DAG.getVTList(VT, MaskVT, MVT::Other), Ops, dl, N->getMemoryVT(),
28465       N->getMemOperand());
28466   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
28467                                 NewGather, DAG.getIntPtrConstant(0, dl));
28468   return DAG.getMergeValues({Extract, NewGather.getValue(2)}, dl);
28469 }
28470 
LowerADDRSPACECAST(SDValue Op,SelectionDAG & DAG)28471 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
28472   SDLoc dl(Op);
28473   SDValue Src = Op.getOperand(0);
28474   MVT DstVT = Op.getSimpleValueType();
28475 
28476   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
28477   unsigned SrcAS = N->getSrcAddressSpace();
28478 
28479   assert(SrcAS != N->getDestAddressSpace() &&
28480          "addrspacecast must be between different address spaces");
28481 
28482   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
28483     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
28484   } else if (DstVT == MVT::i64) {
28485     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
28486   } else if (DstVT == MVT::i32) {
28487     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
28488   } else {
28489     report_fatal_error("Bad address space in addrspacecast");
28490   }
28491   return Op;
28492 }
28493 
LowerGC_TRANSITION(SDValue Op,SelectionDAG & DAG) const28494 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
28495                                               SelectionDAG &DAG) const {
28496   // TODO: Eventually, the lowering of these nodes should be informed by or
28497   // deferred to the GC strategy for the function in which they appear. For
28498   // now, however, they must be lowered to something. Since they are logically
28499   // no-ops in the case of a null GC strategy (or a GC strategy which does not
28500   // require special handling for these nodes), lower them as literal NOOPs for
28501   // the time being.
28502   SmallVector<SDValue, 2> Ops;
28503 
28504   Ops.push_back(Op.getOperand(0));
28505   if (Op->getGluedNode())
28506     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
28507 
28508   SDLoc OpDL(Op);
28509   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
28510   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
28511 
28512   return NOOP;
28513 }
28514 
LowerF128Call(SDValue Op,SelectionDAG & DAG,RTLIB::Libcall Call) const28515 SDValue X86TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
28516                                          RTLIB::Libcall Call) const {
28517 
28518   bool IsStrict = Op->isStrictFPOpcode();
28519   unsigned Offset = IsStrict ? 1 : 0;
28520   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
28521 
28522   SDLoc dl(Op);
28523   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
28524   MakeLibCallOptions CallOptions;
28525   std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, Call, MVT::f128, Ops,
28526                                                 CallOptions, dl, Chain);
28527 
28528   if (IsStrict)
28529     return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
28530 
28531   return Tmp.first;
28532 }
28533 
28534 /// Provide custom lowering hooks for some operations.
LowerOperation(SDValue Op,SelectionDAG & DAG) const28535 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
28536   switch (Op.getOpcode()) {
28537   default: llvm_unreachable("Should not custom lower this!");
28538   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
28539   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
28540     return LowerCMP_SWAP(Op, Subtarget, DAG);
28541   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
28542   case ISD::ATOMIC_LOAD_ADD:
28543   case ISD::ATOMIC_LOAD_SUB:
28544   case ISD::ATOMIC_LOAD_OR:
28545   case ISD::ATOMIC_LOAD_XOR:
28546   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
28547   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
28548   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
28549   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
28550   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
28551   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
28552   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
28553   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
28554   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
28555   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
28556   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
28557   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
28558   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
28559   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
28560   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
28561   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
28562   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
28563   case ISD::SHL_PARTS:
28564   case ISD::SRA_PARTS:
28565   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
28566   case ISD::FSHL:
28567   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
28568   case ISD::STRICT_SINT_TO_FP:
28569   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
28570   case ISD::STRICT_UINT_TO_FP:
28571   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
28572   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
28573   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
28574   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
28575   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
28576   case ISD::ZERO_EXTEND_VECTOR_INREG:
28577   case ISD::SIGN_EXTEND_VECTOR_INREG:
28578     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
28579   case ISD::FP_TO_SINT:
28580   case ISD::STRICT_FP_TO_SINT:
28581   case ISD::FP_TO_UINT:
28582   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
28583   case ISD::FP_EXTEND:
28584   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
28585   case ISD::FP_ROUND:
28586   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
28587   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
28588   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
28589   case ISD::FADD:
28590   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
28591   case ISD::FABS:
28592   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
28593   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
28594   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
28595   case ISD::SETCC:
28596   case ISD::STRICT_FSETCC:
28597   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
28598   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
28599   case ISD::SELECT:             return LowerSELECT(Op, DAG);
28600   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
28601   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
28602   case ISD::VASTART:            return LowerVASTART(Op, DAG);
28603   case ISD::VAARG:              return LowerVAARG(Op, DAG);
28604   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
28605   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
28606   case ISD::INTRINSIC_VOID:
28607   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
28608   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
28609   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
28610   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
28611   case ISD::FRAME_TO_ARGS_OFFSET:
28612                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
28613   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
28614   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
28615   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
28616   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
28617   case ISD::EH_SJLJ_SETUP_DISPATCH:
28618     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
28619   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
28620   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
28621   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
28622   case ISD::CTLZ:
28623   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
28624   case ISD::CTTZ:
28625   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
28626   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
28627   case ISD::MULHS:
28628   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
28629   case ISD::ROTL:
28630   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
28631   case ISD::SRA:
28632   case ISD::SRL:
28633   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
28634   case ISD::SADDO:
28635   case ISD::UADDO:
28636   case ISD::SSUBO:
28637   case ISD::USUBO:
28638   case ISD::SMULO:
28639   case ISD::UMULO:              return LowerXALUO(Op, DAG);
28640   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
28641   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
28642   case ISD::ADDCARRY:
28643   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
28644   case ISD::ADD:
28645   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
28646   case ISD::UADDSAT:
28647   case ISD::SADDSAT:
28648   case ISD::USUBSAT:
28649   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
28650   case ISD::SMAX:
28651   case ISD::SMIN:
28652   case ISD::UMAX:
28653   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
28654   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
28655   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
28656   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
28657   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
28658   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
28659   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
28660   case ISD::GC_TRANSITION_START:
28661   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
28662   case ISD::ADDRSPACECAST:
28663     return LowerADDRSPACECAST(Op, DAG);
28664   }
28665 }
28666 
28667 /// Places new result values for the node in Results (their number
28668 /// and types must exactly match those of the original return values of
28669 /// the node), or leaves Results empty, which indicates that the node is not
28670 /// to be custom lowered after all.
LowerOperationWrapper(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const28671 void X86TargetLowering::LowerOperationWrapper(SDNode *N,
28672                                               SmallVectorImpl<SDValue> &Results,
28673                                               SelectionDAG &DAG) const {
28674   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
28675 
28676   if (!Res.getNode())
28677     return;
28678 
28679   // If the original node has one result, take the return value from
28680   // LowerOperation as is. It might not be result number 0.
28681   if (N->getNumValues() == 1) {
28682     Results.push_back(Res);
28683     return;
28684   }
28685 
28686   // If the original node has multiple results, then the return node should
28687   // have the same number of results.
28688   assert((N->getNumValues() == Res->getNumValues()) &&
28689       "Lowering returned the wrong number of results!");
28690 
28691   // Places new result values base on N result number.
28692   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
28693     Results.push_back(Res.getValue(I));
28694 }
28695 
28696 /// Replace a node with an illegal result type with a new node built out of
28697 /// custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const28698 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
28699                                            SmallVectorImpl<SDValue>&Results,
28700                                            SelectionDAG &DAG) const {
28701   SDLoc dl(N);
28702   switch (N->getOpcode()) {
28703   default:
28704 #ifndef NDEBUG
28705     dbgs() << "ReplaceNodeResults: ";
28706     N->dump(&DAG);
28707 #endif
28708     llvm_unreachable("Do not know how to custom type legalize this operation!");
28709   case ISD::CTPOP: {
28710     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
28711     // Use a v2i64 if possible.
28712     bool NoImplicitFloatOps =
28713         DAG.getMachineFunction().getFunction().hasFnAttribute(
28714             Attribute::NoImplicitFloat);
28715     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
28716       SDValue Wide =
28717           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
28718       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
28719       // Bit count should fit in 32-bits, extract it as that and then zero
28720       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
28721       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
28722       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
28723                          DAG.getIntPtrConstant(0, dl));
28724       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
28725       Results.push_back(Wide);
28726     }
28727     return;
28728   }
28729   case ISD::MUL: {
28730     EVT VT = N->getValueType(0);
28731     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
28732            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
28733     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
28734     // elements are needed.
28735     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
28736     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
28737     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
28738     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
28739     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
28740     unsigned NumConcats = 16 / VT.getVectorNumElements();
28741     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
28742     ConcatOps[0] = Res;
28743     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
28744     Results.push_back(Res);
28745     return;
28746   }
28747   case X86ISD::VPMADDWD:
28748   case X86ISD::AVG: {
28749     // Legalize types for X86ISD::AVG/VPMADDWD by widening.
28750     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
28751 
28752     EVT VT = N->getValueType(0);
28753     EVT InVT = N->getOperand(0).getValueType();
28754     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
28755            "Expected a VT that divides into 128 bits.");
28756     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
28757            "Unexpected type action!");
28758     unsigned NumConcat = 128 / InVT.getSizeInBits();
28759 
28760     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
28761                                     InVT.getVectorElementType(),
28762                                     NumConcat * InVT.getVectorNumElements());
28763     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
28764                                   VT.getVectorElementType(),
28765                                   NumConcat * VT.getVectorNumElements());
28766 
28767     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
28768     Ops[0] = N->getOperand(0);
28769     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
28770     Ops[0] = N->getOperand(1);
28771     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
28772 
28773     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
28774     Results.push_back(Res);
28775     return;
28776   }
28777   case ISD::ABS: {
28778     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28779     assert(N->getValueType(0) == MVT::i64 &&
28780            "Unexpected type (!= i64) on ABS.");
28781     MVT HalfT = MVT::i32;
28782     SDValue Lo, Hi, Tmp;
28783     SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
28784 
28785     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
28786                      DAG.getConstant(0, dl, HalfT));
28787     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
28788                      DAG.getConstant(1, dl, HalfT));
28789     Tmp = DAG.getNode(
28790         ISD::SRA, dl, HalfT, Hi,
28791         DAG.getConstant(HalfT.getSizeInBits() - 1, dl,
28792                         TLI.getShiftAmountTy(HalfT, DAG.getDataLayout())));
28793     Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
28794     Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
28795                      SDValue(Lo.getNode(), 1));
28796     Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
28797     Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
28798     Results.push_back(Lo);
28799     Results.push_back(Hi);
28800     return;
28801   }
28802   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
28803   case X86ISD::FMINC:
28804   case X86ISD::FMIN:
28805   case X86ISD::FMAXC:
28806   case X86ISD::FMAX: {
28807     EVT VT = N->getValueType(0);
28808     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
28809     SDValue UNDEF = DAG.getUNDEF(VT);
28810     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
28811                               N->getOperand(0), UNDEF);
28812     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
28813                               N->getOperand(1), UNDEF);
28814     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
28815     return;
28816   }
28817   case ISD::SDIV:
28818   case ISD::UDIV:
28819   case ISD::SREM:
28820   case ISD::UREM: {
28821     EVT VT = N->getValueType(0);
28822     if (VT.isVector()) {
28823       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
28824              "Unexpected type action!");
28825       // If this RHS is a constant splat vector we can widen this and let
28826       // division/remainder by constant optimize it.
28827       // TODO: Can we do something for non-splat?
28828       APInt SplatVal;
28829       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
28830         unsigned NumConcats = 128 / VT.getSizeInBits();
28831         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
28832         Ops0[0] = N->getOperand(0);
28833         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
28834         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
28835         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
28836         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
28837         Results.push_back(Res);
28838       }
28839       return;
28840     }
28841 
28842     LLVM_FALLTHROUGH;
28843   }
28844   case ISD::SDIVREM:
28845   case ISD::UDIVREM: {
28846     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
28847     Results.push_back(V);
28848     return;
28849   }
28850   case ISD::TRUNCATE: {
28851     MVT VT = N->getSimpleValueType(0);
28852     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
28853       return;
28854 
28855     // The generic legalizer will try to widen the input type to the same
28856     // number of elements as the widened result type. But this isn't always
28857     // the best thing so do some custom legalization to avoid some cases.
28858     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
28859     SDValue In = N->getOperand(0);
28860     EVT InVT = In.getValueType();
28861 
28862     unsigned InBits = InVT.getSizeInBits();
28863     if (128 % InBits == 0) {
28864       // 128 bit and smaller inputs should avoid truncate all together and
28865       // just use a build_vector that will become a shuffle.
28866       // TODO: Widen and use a shuffle directly?
28867       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
28868       EVT EltVT = VT.getVectorElementType();
28869       unsigned WidenNumElts = WidenVT.getVectorNumElements();
28870       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
28871       // Use the original element count so we don't do more scalar opts than
28872       // necessary.
28873       unsigned MinElts = VT.getVectorNumElements();
28874       for (unsigned i=0; i < MinElts; ++i) {
28875         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
28876                                   DAG.getIntPtrConstant(i, dl));
28877         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
28878       }
28879       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
28880       return;
28881     }
28882     // With AVX512 there are some cases that can use a target specific
28883     // truncate node to go from 256/512 to less than 128 with zeros in the
28884     // upper elements of the 128 bit result.
28885     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
28886       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
28887       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
28888         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
28889         return;
28890       }
28891       // There's one case we can widen to 512 bits and use VTRUNC.
28892       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
28893         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
28894                          DAG.getUNDEF(MVT::v4i64));
28895         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
28896         return;
28897       }
28898     }
28899     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
28900         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
28901         isTypeLegal(MVT::v4i64)) {
28902       // Input needs to be split and output needs to widened. Let's use two
28903       // VTRUNCs, and shuffle their results together into the wider type.
28904       SDValue Lo, Hi;
28905       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
28906 
28907       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
28908       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
28909       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
28910                                          { 0,  1,  2,  3, 16, 17, 18, 19,
28911                                           -1, -1, -1, -1, -1, -1, -1, -1 });
28912       Results.push_back(Res);
28913       return;
28914     }
28915 
28916     return;
28917   }
28918   case ISD::ANY_EXTEND:
28919     // Right now, only MVT::v8i8 has Custom action for an illegal type.
28920     // It's intended to custom handle the input type.
28921     assert(N->getValueType(0) == MVT::v8i8 &&
28922            "Do not know how to legalize this Node");
28923     return;
28924   case ISD::SIGN_EXTEND:
28925   case ISD::ZERO_EXTEND: {
28926     EVT VT = N->getValueType(0);
28927     SDValue In = N->getOperand(0);
28928     EVT InVT = In.getValueType();
28929     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
28930         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
28931       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
28932              "Unexpected type action!");
28933       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
28934       // Custom split this so we can extend i8/i16->i32 invec. This is better
28935       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
28936       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
28937       // we allow the sra from the extend to i32 to be shared by the split.
28938       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
28939 
28940       // Fill a vector with sign bits for each element.
28941       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
28942       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
28943 
28944       // Create an unpackl and unpackh to interleave the sign bits then bitcast
28945       // to v2i64.
28946       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
28947                                         {0, 4, 1, 5});
28948       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
28949       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
28950                                         {2, 6, 3, 7});
28951       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
28952 
28953       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
28954       Results.push_back(Res);
28955       return;
28956     }
28957 
28958     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
28959       if (!InVT.is128BitVector()) {
28960         // Not a 128 bit vector, but maybe type legalization will promote
28961         // it to 128 bits.
28962         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
28963           return;
28964         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
28965         if (!InVT.is128BitVector())
28966           return;
28967 
28968         // Promote the input to 128 bits. Type legalization will turn this into
28969         // zext_inreg/sext_inreg.
28970         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
28971       }
28972 
28973       // Perform custom splitting instead of the two stage extend we would get
28974       // by default.
28975       EVT LoVT, HiVT;
28976       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
28977       assert(isTypeLegal(LoVT) && "Split VT not legal?");
28978 
28979       SDValue Lo = getExtendInVec(N->getOpcode(), dl, LoVT, In, DAG);
28980 
28981       // We need to shift the input over by half the number of elements.
28982       unsigned NumElts = InVT.getVectorNumElements();
28983       unsigned HalfNumElts = NumElts / 2;
28984       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
28985       for (unsigned i = 0; i != HalfNumElts; ++i)
28986         ShufMask[i] = i + HalfNumElts;
28987 
28988       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
28989       Hi = getExtendInVec(N->getOpcode(), dl, HiVT, Hi, DAG);
28990 
28991       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
28992       Results.push_back(Res);
28993     }
28994     return;
28995   }
28996   case ISD::FP_TO_SINT:
28997   case ISD::STRICT_FP_TO_SINT:
28998   case ISD::FP_TO_UINT:
28999   case ISD::STRICT_FP_TO_UINT: {
29000     bool IsStrict = N->isStrictFPOpcode();
29001     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
29002                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
29003     EVT VT = N->getValueType(0);
29004     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29005     EVT SrcVT = Src.getValueType();
29006 
29007     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
29008       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29009              "Unexpected type action!");
29010 
29011       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
29012       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
29013       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
29014                                        VT.getVectorNumElements());
29015       SDValue Res;
29016       SDValue Chain;
29017       if (IsStrict) {
29018         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
29019                           {N->getOperand(0), Src});
29020         Chain = Res.getValue(1);
29021       } else
29022         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
29023 
29024       // Preserve what we know about the size of the original result. Except
29025       // when the result is v2i32 since we can't widen the assert.
29026       if (PromoteVT != MVT::v2i32)
29027         Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext,
29028                           dl, PromoteVT, Res,
29029                           DAG.getValueType(VT.getVectorElementType()));
29030 
29031       // Truncate back to the original width.
29032       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
29033 
29034       // Now widen to 128 bits.
29035       unsigned NumConcats = 128 / VT.getSizeInBits();
29036       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
29037                                       VT.getVectorNumElements() * NumConcats);
29038       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
29039       ConcatOps[0] = Res;
29040       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
29041       Results.push_back(Res);
29042       if (IsStrict)
29043         Results.push_back(Chain);
29044       return;
29045     }
29046 
29047 
29048     if (VT == MVT::v2i32) {
29049       assert((IsSigned || Subtarget.hasAVX512()) &&
29050              "Can only handle signed conversion without AVX512");
29051       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29052       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29053              "Unexpected type action!");
29054       if (Src.getValueType() == MVT::v2f64) {
29055         unsigned Opc;
29056         if (IsStrict)
29057           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
29058         else
29059           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
29060 
29061         // If we have VLX we can emit a target specific FP_TO_UINT node,.
29062         if (!IsSigned && !Subtarget.hasVLX()) {
29063           // Otherwise we can defer to the generic legalizer which will widen
29064           // the input as well. This will be further widened during op
29065           // legalization to v8i32<-v8f64.
29066           // For strict nodes we'll need to widen ourselves.
29067           // FIXME: Fix the type legalizer to safely widen strict nodes?
29068           if (!IsStrict)
29069             return;
29070           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
29071                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
29072           Opc = N->getOpcode();
29073         }
29074         SDValue Res;
29075         SDValue Chain;
29076         if (IsStrict) {
29077           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
29078                             {N->getOperand(0), Src});
29079           Chain = Res.getValue(1);
29080         } else {
29081           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
29082         }
29083         Results.push_back(Res);
29084         if (IsStrict)
29085           Results.push_back(Chain);
29086         return;
29087       }
29088 
29089       // Custom widen strict v2f32->v2i32 by padding with zeros.
29090       // FIXME: Should generic type legalizer do this?
29091       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
29092         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
29093                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
29094         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
29095                                   {N->getOperand(0), Src});
29096         Results.push_back(Res);
29097         Results.push_back(Res.getValue(1));
29098         return;
29099       }
29100 
29101       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
29102       // so early out here.
29103       return;
29104     }
29105 
29106     assert(!VT.isVector() && "Vectors should have been handled above!");
29107 
29108     if (Subtarget.hasDQI() && VT == MVT::i64 &&
29109         (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
29110       assert(!Subtarget.is64Bit() && "i64 should be legal");
29111       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
29112       // If we use a 128-bit result we might need to use a target specific node.
29113       unsigned SrcElts =
29114           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
29115       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
29116       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
29117       unsigned Opc = N->getOpcode();
29118       if (NumElts != SrcElts) {
29119         if (IsStrict)
29120           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
29121         else
29122           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
29123       }
29124 
29125       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
29126       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
29127                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
29128                                 ZeroIdx);
29129       SDValue Chain;
29130       if (IsStrict) {
29131         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
29132         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
29133         Chain = Res.getValue(1);
29134       } else
29135         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
29136       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
29137       Results.push_back(Res);
29138       if (IsStrict)
29139         Results.push_back(Chain);
29140       return;
29141     }
29142 
29143     SDValue Chain;
29144     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
29145       Results.push_back(V);
29146       if (IsStrict)
29147         Results.push_back(Chain);
29148     }
29149     return;
29150   }
29151   case ISD::SINT_TO_FP:
29152   case ISD::STRICT_SINT_TO_FP:
29153   case ISD::UINT_TO_FP:
29154   case ISD::STRICT_UINT_TO_FP: {
29155     bool IsStrict = N->isStrictFPOpcode();
29156     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
29157                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
29158     EVT VT = N->getValueType(0);
29159     if (VT != MVT::v2f32)
29160       return;
29161     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29162     EVT SrcVT = Src.getValueType();
29163     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
29164       if (IsStrict) {
29165         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
29166                                 : X86ISD::STRICT_CVTUI2P;
29167         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
29168                                   {N->getOperand(0), Src});
29169         Results.push_back(Res);
29170         Results.push_back(Res.getValue(1));
29171       } else {
29172         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
29173         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
29174       }
29175       return;
29176     }
29177     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
29178         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
29179       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
29180       SDValue One  = DAG.getConstant(1, dl, SrcVT);
29181       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
29182                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
29183                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
29184       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
29185       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
29186       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
29187       for (int i = 0; i != 2; ++i) {
29188         SDValue Src = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
29189                                   SignSrc, DAG.getIntPtrConstant(i, dl));
29190         if (IsStrict)
29191           SignCvts[i] =
29192               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
29193                           {N->getOperand(0), Src});
29194         else
29195           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Src);
29196       };
29197       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
29198       SDValue Slow, Chain;
29199       if (IsStrict) {
29200         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
29201                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
29202         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
29203                            {Chain, SignCvt, SignCvt});
29204         Chain = Slow.getValue(1);
29205       } else {
29206         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
29207       }
29208       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
29209       IsNeg =
29210           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
29211       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
29212       Results.push_back(Cvt);
29213       if (IsStrict)
29214         Results.push_back(Chain);
29215       return;
29216     }
29217 
29218     if (SrcVT != MVT::v2i32)
29219       return;
29220 
29221     if (IsSigned || Subtarget.hasAVX512()) {
29222       if (!IsStrict)
29223         return;
29224 
29225       // Custom widen strict v2i32->v2f32 to avoid scalarization.
29226       // FIXME: Should generic type legalizer do this?
29227       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
29228                         DAG.getConstant(0, dl, MVT::v2i32));
29229       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
29230                                 {N->getOperand(0), Src});
29231       Results.push_back(Res);
29232       Results.push_back(Res.getValue(1));
29233       return;
29234     }
29235 
29236     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29237     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
29238     SDValue VBias =
29239         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
29240     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
29241                              DAG.getBitcast(MVT::v2i64, VBias));
29242     Or = DAG.getBitcast(MVT::v2f64, Or);
29243     if (IsStrict) {
29244       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
29245                                 {N->getOperand(0), Or, VBias});
29246       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
29247                                 {MVT::v4f32, MVT::Other},
29248                                 {Sub.getValue(1), Sub});
29249       Results.push_back(Res);
29250       Results.push_back(Res.getValue(1));
29251     } else {
29252       // TODO: Are there any fast-math-flags to propagate here?
29253       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
29254       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
29255     }
29256     return;
29257   }
29258   case ISD::STRICT_FP_ROUND:
29259   case ISD::FP_ROUND: {
29260     bool IsStrict = N->isStrictFPOpcode();
29261     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29262     if (!isTypeLegal(Src.getValueType()))
29263       return;
29264     SDValue V;
29265     if (IsStrict)
29266       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {MVT::v4f32, MVT::Other},
29267                       {N->getOperand(0), N->getOperand(1)});
29268     else
29269       V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
29270     Results.push_back(V);
29271     if (IsStrict)
29272       Results.push_back(V.getValue(1));
29273     return;
29274   }
29275   case ISD::FP_EXTEND: {
29276     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
29277     // No other ValueType for FP_EXTEND should reach this point.
29278     assert(N->getValueType(0) == MVT::v2f32 &&
29279            "Do not know how to legalize this Node");
29280     return;
29281   }
29282   case ISD::INTRINSIC_W_CHAIN: {
29283     unsigned IntNo = N->getConstantOperandVal(1);
29284     switch (IntNo) {
29285     default : llvm_unreachable("Do not know how to custom type "
29286                                "legalize this intrinsic operation!");
29287     case Intrinsic::x86_rdtsc:
29288       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
29289                                      Results);
29290     case Intrinsic::x86_rdtscp:
29291       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
29292                                      Results);
29293     case Intrinsic::x86_rdpmc:
29294       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
29295                                   Results);
29296       return;
29297     case Intrinsic::x86_xgetbv:
29298       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
29299                                   Results);
29300       return;
29301     }
29302   }
29303   case ISD::READCYCLECOUNTER: {
29304     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
29305   }
29306   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
29307     EVT T = N->getValueType(0);
29308     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
29309     bool Regs64bit = T == MVT::i128;
29310     assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&
29311            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
29312     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
29313     SDValue cpInL, cpInH;
29314     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
29315                         DAG.getConstant(0, dl, HalfT));
29316     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
29317                         DAG.getConstant(1, dl, HalfT));
29318     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
29319                              Regs64bit ? X86::RAX : X86::EAX,
29320                              cpInL, SDValue());
29321     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
29322                              Regs64bit ? X86::RDX : X86::EDX,
29323                              cpInH, cpInL.getValue(1));
29324     SDValue swapInL, swapInH;
29325     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
29326                           DAG.getConstant(0, dl, HalfT));
29327     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
29328                           DAG.getConstant(1, dl, HalfT));
29329     swapInH =
29330         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
29331                          swapInH, cpInH.getValue(1));
29332     // If the current function needs the base pointer, RBX,
29333     // we shouldn't use cmpxchg directly.
29334     // Indeed the lowering of that instruction will clobber
29335     // that register and since RBX will be a reserved register
29336     // the register allocator will not make sure its value will
29337     // be properly saved and restored around this live-range.
29338     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
29339     SDValue Result;
29340     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
29341     Register BasePtr = TRI->getBaseRegister();
29342     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
29343     if (TRI->hasBasePointer(DAG.getMachineFunction()) &&
29344         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
29345       // ISel prefers the LCMPXCHG64 variant.
29346       // If that assert breaks, that means it is not the case anymore,
29347       // and we need to teach LCMPXCHG8_SAVE_EBX_DAG how to save RBX,
29348       // not just EBX. This is a matter of accepting i64 input for that
29349       // pseudo, and restoring into the register of the right wide
29350       // in expand pseudo. Everything else should just work.
29351       assert(((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) &&
29352              "Saving only half of the RBX");
29353       unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_SAVE_RBX_DAG
29354                                   : X86ISD::LCMPXCHG8_SAVE_EBX_DAG;
29355       SDValue RBXSave = DAG.getCopyFromReg(swapInH.getValue(0), dl,
29356                                            Regs64bit ? X86::RBX : X86::EBX,
29357                                            HalfT, swapInH.getValue(1));
29358       SDValue Ops[] = {/*Chain*/ RBXSave.getValue(1), N->getOperand(1), swapInL,
29359                        RBXSave,
29360                        /*Glue*/ RBXSave.getValue(2)};
29361       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
29362     } else {
29363       unsigned Opcode =
29364           Regs64bit ? X86ISD::LCMPXCHG16_DAG : X86ISD::LCMPXCHG8_DAG;
29365       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl,
29366                                  Regs64bit ? X86::RBX : X86::EBX, swapInL,
29367                                  swapInH.getValue(1));
29368       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
29369                        swapInL.getValue(1)};
29370       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
29371     }
29372     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
29373                                         Regs64bit ? X86::RAX : X86::EAX,
29374                                         HalfT, Result.getValue(1));
29375     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
29376                                         Regs64bit ? X86::RDX : X86::EDX,
29377                                         HalfT, cpOutL.getValue(2));
29378     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
29379 
29380     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
29381                                         MVT::i32, cpOutH.getValue(2));
29382     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
29383     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
29384 
29385     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
29386     Results.push_back(Success);
29387     Results.push_back(EFLAGS.getValue(1));
29388     return;
29389   }
29390   case ISD::ATOMIC_LOAD: {
29391     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
29392     bool NoImplicitFloatOps =
29393         DAG.getMachineFunction().getFunction().hasFnAttribute(
29394             Attribute::NoImplicitFloat);
29395     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
29396       auto *Node = cast<AtomicSDNode>(N);
29397       if (Subtarget.hasSSE2()) {
29398         // Use a VZEXT_LOAD which will be selected as MOVQ. Then extract the
29399         // lower 64-bits.
29400         SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
29401         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
29402         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
29403                                              MVT::i64, Node->getMemOperand());
29404         SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
29405                                   DAG.getIntPtrConstant(0, dl));
29406         Results.push_back(Res);
29407         Results.push_back(Ld.getValue(1));
29408         return;
29409       }
29410       if (Subtarget.hasX87()) {
29411         // First load this into an 80-bit X87 register. This will put the whole
29412         // integer into the significand.
29413         // FIXME: Do we need to glue? See FIXME comment in BuildFILD.
29414         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other, MVT::Glue);
29415         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
29416         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD_FLAG,
29417                                                  dl, Tys, Ops, MVT::i64,
29418                                                  Node->getMemOperand());
29419         SDValue Chain = Result.getValue(1);
29420         SDValue InFlag = Result.getValue(2);
29421 
29422         // Now store the X87 register to a stack temporary and convert to i64.
29423         // This store is not atomic and doesn't need to be.
29424         // FIXME: We don't need a stack temporary if the result of the load
29425         // is already being stored. We could just directly store there.
29426         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
29427         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29428         MachinePointerInfo MPI =
29429             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29430         SDValue StoreOps[] = { Chain, Result, StackPtr, InFlag };
29431         Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, dl,
29432                                         DAG.getVTList(MVT::Other), StoreOps,
29433                                         MVT::i64, MPI, 0 /*Align*/,
29434                                         MachineMemOperand::MOStore);
29435 
29436         // Finally load the value back from the stack temporary and return it.
29437         // This load is not atomic and doesn't need to be.
29438         // This load will be further type legalized.
29439         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
29440         Results.push_back(Result);
29441         Results.push_back(Result.getValue(1));
29442         return;
29443       }
29444     }
29445     // TODO: Use MOVLPS when SSE1 is available?
29446     // Delegate to generic TypeLegalization. Situations we can really handle
29447     // should have already been dealt with by AtomicExpandPass.cpp.
29448     break;
29449   }
29450   case ISD::ATOMIC_SWAP:
29451   case ISD::ATOMIC_LOAD_ADD:
29452   case ISD::ATOMIC_LOAD_SUB:
29453   case ISD::ATOMIC_LOAD_AND:
29454   case ISD::ATOMIC_LOAD_OR:
29455   case ISD::ATOMIC_LOAD_XOR:
29456   case ISD::ATOMIC_LOAD_NAND:
29457   case ISD::ATOMIC_LOAD_MIN:
29458   case ISD::ATOMIC_LOAD_MAX:
29459   case ISD::ATOMIC_LOAD_UMIN:
29460   case ISD::ATOMIC_LOAD_UMAX:
29461     // Delegate to generic TypeLegalization. Situations we can really handle
29462     // should have already been dealt with by AtomicExpandPass.cpp.
29463     break;
29464 
29465   case ISD::BITCAST: {
29466     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29467     EVT DstVT = N->getValueType(0);
29468     EVT SrcVT = N->getOperand(0).getValueType();
29469 
29470     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
29471     // we can split using the k-register rather than memory.
29472     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
29473       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
29474       SDValue Lo, Hi;
29475       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
29476       Lo = DAG.getBitcast(MVT::i32, Lo);
29477       Hi = DAG.getBitcast(MVT::i32, Hi);
29478       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
29479       Results.push_back(Res);
29480       return;
29481     }
29482 
29483     // Custom splitting for BWI types when AVX512F is available but BWI isn't.
29484     if ((DstVT == MVT::v32i16 || DstVT == MVT::v64i8) &&
29485         SrcVT.isVector() && isTypeLegal(SrcVT)) {
29486       SDValue Lo, Hi;
29487       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
29488       MVT CastVT = (DstVT == MVT::v32i16) ? MVT::v16i16 : MVT::v32i8;
29489       Lo = DAG.getBitcast(CastVT, Lo);
29490       Hi = DAG.getBitcast(CastVT, Hi);
29491       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
29492       Results.push_back(Res);
29493       return;
29494     }
29495 
29496     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
29497       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
29498              "Unexpected type action!");
29499       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
29500       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, WideVT, N->getOperand(0));
29501       Results.push_back(Res);
29502       return;
29503     }
29504 
29505     return;
29506   }
29507   case ISD::MGATHER: {
29508     EVT VT = N->getValueType(0);
29509     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
29510         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
29511       auto *Gather = cast<MaskedGatherSDNode>(N);
29512       SDValue Index = Gather->getIndex();
29513       if (Index.getValueType() != MVT::v2i64)
29514         return;
29515       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29516              "Unexpected type action!");
29517       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
29518       SDValue Mask = Gather->getMask();
29519       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
29520       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
29521                                      Gather->getPassThru(),
29522                                      DAG.getUNDEF(VT));
29523       if (!Subtarget.hasVLX()) {
29524         // We need to widen the mask, but the instruction will only use 2
29525         // of its elements. So we can use undef.
29526         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
29527                            DAG.getUNDEF(MVT::v2i1));
29528         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
29529       }
29530       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
29531                         Gather->getBasePtr(), Index, Gather->getScale() };
29532       SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
29533         DAG.getVTList(WideVT, Mask.getValueType(), MVT::Other), Ops, dl,
29534         Gather->getMemoryVT(), Gather->getMemOperand());
29535       Results.push_back(Res);
29536       Results.push_back(Res.getValue(2));
29537       return;
29538     }
29539     return;
29540   }
29541   case ISD::LOAD: {
29542     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
29543     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
29544     // cast since type legalization will try to use an i64 load.
29545     MVT VT = N->getSimpleValueType(0);
29546     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
29547     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29548            "Unexpected type action!");
29549     if (!ISD::isNON_EXTLoad(N))
29550       return;
29551     auto *Ld = cast<LoadSDNode>(N);
29552     if (Subtarget.hasSSE2()) {
29553       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
29554       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
29555                                 Ld->getPointerInfo(), Ld->getAlignment(),
29556                                 Ld->getMemOperand()->getFlags());
29557       SDValue Chain = Res.getValue(1);
29558       MVT VecVT = MVT::getVectorVT(LdVT, 2);
29559       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
29560       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
29561       Res = DAG.getBitcast(WideVT, Res);
29562       Results.push_back(Res);
29563       Results.push_back(Chain);
29564       return;
29565     }
29566     assert(Subtarget.hasSSE1() && "Expected SSE");
29567     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
29568     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
29569     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
29570                                           MVT::i64, Ld->getMemOperand());
29571     Results.push_back(Res);
29572     Results.push_back(Res.getValue(1));
29573     return;
29574   }
29575   case ISD::ADDRSPACECAST: {
29576     SDValue Src = N->getOperand(0);
29577     EVT DstVT = N->getValueType(0);
29578     AddrSpaceCastSDNode *CastN = cast<AddrSpaceCastSDNode>(N);
29579     unsigned SrcAS = CastN->getSrcAddressSpace();
29580 
29581     assert(SrcAS != CastN->getDestAddressSpace() &&
29582            "addrspacecast must be between different address spaces");
29583 
29584     SDValue Res;
29585     if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64)
29586       Res = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
29587     else if (DstVT == MVT::i64)
29588       Res = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
29589     else if (DstVT == MVT::i32)
29590       Res = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
29591     else
29592       report_fatal_error("Unrecognized addrspacecast type legalization");
29593 
29594     Results.push_back(Res);
29595     return;
29596   }
29597   }
29598 }
29599 
getTargetNodeName(unsigned Opcode) const29600 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
29601   switch ((X86ISD::NodeType)Opcode) {
29602   case X86ISD::FIRST_NUMBER:       break;
29603   case X86ISD::BSF:                return "X86ISD::BSF";
29604   case X86ISD::BSR:                return "X86ISD::BSR";
29605   case X86ISD::SHLD:               return "X86ISD::SHLD";
29606   case X86ISD::SHRD:               return "X86ISD::SHRD";
29607   case X86ISD::FAND:               return "X86ISD::FAND";
29608   case X86ISD::FANDN:              return "X86ISD::FANDN";
29609   case X86ISD::FOR:                return "X86ISD::FOR";
29610   case X86ISD::FXOR:               return "X86ISD::FXOR";
29611   case X86ISD::FILD:               return "X86ISD::FILD";
29612   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
29613   case X86ISD::FIST:               return "X86ISD::FIST";
29614   case X86ISD::FP_TO_INT_IN_MEM:   return "X86ISD::FP_TO_INT_IN_MEM";
29615   case X86ISD::FLD:                return "X86ISD::FLD";
29616   case X86ISD::FST:                return "X86ISD::FST";
29617   case X86ISD::CALL:               return "X86ISD::CALL";
29618   case X86ISD::BT:                 return "X86ISD::BT";
29619   case X86ISD::CMP:                return "X86ISD::CMP";
29620   case X86ISD::STRICT_FCMP:        return "X86ISD::STRICT_FCMP";
29621   case X86ISD::STRICT_FCMPS:       return "X86ISD::STRICT_FCMPS";
29622   case X86ISD::COMI:               return "X86ISD::COMI";
29623   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
29624   case X86ISD::CMPM:               return "X86ISD::CMPM";
29625   case X86ISD::STRICT_CMPM:        return "X86ISD::STRICT_CMPM";
29626   case X86ISD::CMPM_SAE:           return "X86ISD::CMPM_SAE";
29627   case X86ISD::SETCC:              return "X86ISD::SETCC";
29628   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
29629   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
29630   case X86ISD::FSETCCM:            return "X86ISD::FSETCCM";
29631   case X86ISD::FSETCCM_SAE:        return "X86ISD::FSETCCM_SAE";
29632   case X86ISD::CMOV:               return "X86ISD::CMOV";
29633   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
29634   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
29635   case X86ISD::IRET:               return "X86ISD::IRET";
29636   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
29637   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
29638   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
29639   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
29640   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
29641   case X86ISD::MOVQ2DQ:            return "X86ISD::MOVQ2DQ";
29642   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
29643   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
29644   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
29645   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
29646   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
29647   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
29648   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
29649   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
29650   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
29651   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
29652   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
29653   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
29654   case X86ISD::HADD:               return "X86ISD::HADD";
29655   case X86ISD::HSUB:               return "X86ISD::HSUB";
29656   case X86ISD::FHADD:              return "X86ISD::FHADD";
29657   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
29658   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
29659   case X86ISD::FMAX:               return "X86ISD::FMAX";
29660   case X86ISD::FMAXS:              return "X86ISD::FMAXS";
29661   case X86ISD::FMAX_SAE:           return "X86ISD::FMAX_SAE";
29662   case X86ISD::FMAXS_SAE:          return "X86ISD::FMAXS_SAE";
29663   case X86ISD::FMIN:               return "X86ISD::FMIN";
29664   case X86ISD::FMINS:              return "X86ISD::FMINS";
29665   case X86ISD::FMIN_SAE:           return "X86ISD::FMIN_SAE";
29666   case X86ISD::FMINS_SAE:          return "X86ISD::FMINS_SAE";
29667   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
29668   case X86ISD::FMINC:              return "X86ISD::FMINC";
29669   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
29670   case X86ISD::FRCP:               return "X86ISD::FRCP";
29671   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
29672   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
29673   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
29674   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
29675   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
29676   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
29677   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
29678   case X86ISD::EH_SJLJ_SETUP_DISPATCH:
29679     return "X86ISD::EH_SJLJ_SETUP_DISPATCH";
29680   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
29681   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
29682   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
29683   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
29684   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
29685   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
29686   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
29687   case X86ISD::LCMPXCHG8_SAVE_EBX_DAG:
29688     return "X86ISD::LCMPXCHG8_SAVE_EBX_DAG";
29689   case X86ISD::LCMPXCHG16_SAVE_RBX_DAG:
29690     return "X86ISD::LCMPXCHG16_SAVE_RBX_DAG";
29691   case X86ISD::LADD:               return "X86ISD::LADD";
29692   case X86ISD::LSUB:               return "X86ISD::LSUB";
29693   case X86ISD::LOR:                return "X86ISD::LOR";
29694   case X86ISD::LXOR:               return "X86ISD::LXOR";
29695   case X86ISD::LAND:               return "X86ISD::LAND";
29696   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
29697   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
29698   case X86ISD::VEXTRACT_STORE:     return "X86ISD::VEXTRACT_STORE";
29699   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
29700   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
29701   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
29702   case X86ISD::VMTRUNC:            return "X86ISD::VMTRUNC";
29703   case X86ISD::VMTRUNCS:           return "X86ISD::VMTRUNCS";
29704   case X86ISD::VMTRUNCUS:          return "X86ISD::VMTRUNCUS";
29705   case X86ISD::VTRUNCSTORES:       return "X86ISD::VTRUNCSTORES";
29706   case X86ISD::VTRUNCSTOREUS:      return "X86ISD::VTRUNCSTOREUS";
29707   case X86ISD::VMTRUNCSTORES:      return "X86ISD::VMTRUNCSTORES";
29708   case X86ISD::VMTRUNCSTOREUS:     return "X86ISD::VMTRUNCSTOREUS";
29709   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
29710   case X86ISD::STRICT_VFPEXT:      return "X86ISD::STRICT_VFPEXT";
29711   case X86ISD::VFPEXT_SAE:         return "X86ISD::VFPEXT_SAE";
29712   case X86ISD::VFPEXTS:            return "X86ISD::VFPEXTS";
29713   case X86ISD::VFPEXTS_SAE:        return "X86ISD::VFPEXTS_SAE";
29714   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
29715   case X86ISD::STRICT_VFPROUND:    return "X86ISD::STRICT_VFPROUND";
29716   case X86ISD::VMFPROUND:          return "X86ISD::VMFPROUND";
29717   case X86ISD::VFPROUND_RND:       return "X86ISD::VFPROUND_RND";
29718   case X86ISD::VFPROUNDS:          return "X86ISD::VFPROUNDS";
29719   case X86ISD::VFPROUNDS_RND:      return "X86ISD::VFPROUNDS_RND";
29720   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
29721   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
29722   case X86ISD::VSHL:               return "X86ISD::VSHL";
29723   case X86ISD::VSRL:               return "X86ISD::VSRL";
29724   case X86ISD::VSRA:               return "X86ISD::VSRA";
29725   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
29726   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
29727   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
29728   case X86ISD::VSHLV:              return "X86ISD::VSHLV";
29729   case X86ISD::VSRLV:              return "X86ISD::VSRLV";
29730   case X86ISD::VSRAV:              return "X86ISD::VSRAV";
29731   case X86ISD::VROTLI:             return "X86ISD::VROTLI";
29732   case X86ISD::VROTRI:             return "X86ISD::VROTRI";
29733   case X86ISD::VPPERM:             return "X86ISD::VPPERM";
29734   case X86ISD::CMPP:               return "X86ISD::CMPP";
29735   case X86ISD::STRICT_CMPP:        return "X86ISD::STRICT_CMPP";
29736   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
29737   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
29738   case X86ISD::PHMINPOS:           return "X86ISD::PHMINPOS";
29739   case X86ISD::ADD:                return "X86ISD::ADD";
29740   case X86ISD::SUB:                return "X86ISD::SUB";
29741   case X86ISD::ADC:                return "X86ISD::ADC";
29742   case X86ISD::SBB:                return "X86ISD::SBB";
29743   case X86ISD::SMUL:               return "X86ISD::SMUL";
29744   case X86ISD::UMUL:               return "X86ISD::UMUL";
29745   case X86ISD::OR:                 return "X86ISD::OR";
29746   case X86ISD::XOR:                return "X86ISD::XOR";
29747   case X86ISD::AND:                return "X86ISD::AND";
29748   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
29749   case X86ISD::BZHI:               return "X86ISD::BZHI";
29750   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
29751   case X86ISD::MOVMSK:             return "X86ISD::MOVMSK";
29752   case X86ISD::PTEST:              return "X86ISD::PTEST";
29753   case X86ISD::TESTP:              return "X86ISD::TESTP";
29754   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
29755   case X86ISD::KTEST:              return "X86ISD::KTEST";
29756   case X86ISD::KADD:               return "X86ISD::KADD";
29757   case X86ISD::KSHIFTL:            return "X86ISD::KSHIFTL";
29758   case X86ISD::KSHIFTR:            return "X86ISD::KSHIFTR";
29759   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
29760   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
29761   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
29762   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
29763   case X86ISD::VSHLD:              return "X86ISD::VSHLD";
29764   case X86ISD::VSHRD:              return "X86ISD::VSHRD";
29765   case X86ISD::VSHLDV:             return "X86ISD::VSHLDV";
29766   case X86ISD::VSHRDV:             return "X86ISD::VSHRDV";
29767   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
29768   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
29769   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
29770   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
29771   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
29772   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
29773   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
29774   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
29775   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
29776   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
29777   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
29778   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
29779   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
29780   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
29781   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
29782   case X86ISD::VBROADCAST_LOAD:    return "X86ISD::VBROADCAST_LOAD";
29783   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
29784   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
29785   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
29786   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
29787   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
29788   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
29789   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
29790   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
29791   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
29792   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
29793   case X86ISD::VFIXUPIMM_SAE:      return "X86ISD::VFIXUPIMM_SAE";
29794   case X86ISD::VFIXUPIMMS:         return "X86ISD::VFIXUPIMMS";
29795   case X86ISD::VFIXUPIMMS_SAE:     return "X86ISD::VFIXUPIMMS_SAE";
29796   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
29797   case X86ISD::VRANGE_SAE:         return "X86ISD::VRANGE_SAE";
29798   case X86ISD::VRANGES:            return "X86ISD::VRANGES";
29799   case X86ISD::VRANGES_SAE:        return "X86ISD::VRANGES_SAE";
29800   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
29801   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
29802   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
29803   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
29804   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
29805   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
29806   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
29807   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
29808   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
29809   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
29810   case X86ISD::SAHF:               return "X86ISD::SAHF";
29811   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
29812   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
29813   case X86ISD::RDPKRU:             return "X86ISD::RDPKRU";
29814   case X86ISD::WRPKRU:             return "X86ISD::WRPKRU";
29815   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
29816   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
29817   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
29818   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
29819   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
29820   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
29821   case X86ISD::VPERMIL2:           return "X86ISD::VPERMIL2";
29822   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
29823   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
29824   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
29825   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
29826   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
29827   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
29828   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
29829   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
29830   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
29831   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
29832   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
29833   case X86ISD::VPMADD52H:          return "X86ISD::VPMADD52H";
29834   case X86ISD::VPMADD52L:          return "X86ISD::VPMADD52L";
29835   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
29836   case X86ISD::STRICT_VRNDSCALE:   return "X86ISD::STRICT_VRNDSCALE";
29837   case X86ISD::VRNDSCALE_SAE:      return "X86ISD::VRNDSCALE_SAE";
29838   case X86ISD::VRNDSCALES:         return "X86ISD::VRNDSCALES";
29839   case X86ISD::VRNDSCALES_SAE:     return "X86ISD::VRNDSCALES_SAE";
29840   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
29841   case X86ISD::VREDUCE_SAE:        return "X86ISD::VREDUCE_SAE";
29842   case X86ISD::VREDUCES:           return "X86ISD::VREDUCES";
29843   case X86ISD::VREDUCES_SAE:       return "X86ISD::VREDUCES_SAE";
29844   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
29845   case X86ISD::VGETMANT_SAE:       return "X86ISD::VGETMANT_SAE";
29846   case X86ISD::VGETMANTS:          return "X86ISD::VGETMANTS";
29847   case X86ISD::VGETMANTS_SAE:      return "X86ISD::VGETMANTS_SAE";
29848   case X86ISD::PCMPESTR:           return "X86ISD::PCMPESTR";
29849   case X86ISD::PCMPISTR:           return "X86ISD::PCMPISTR";
29850   case X86ISD::XTEST:              return "X86ISD::XTEST";
29851   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
29852   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
29853   case X86ISD::SELECTS:            return "X86ISD::SELECTS";
29854   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
29855   case X86ISD::RCP14:              return "X86ISD::RCP14";
29856   case X86ISD::RCP14S:             return "X86ISD::RCP14S";
29857   case X86ISD::RCP28:              return "X86ISD::RCP28";
29858   case X86ISD::RCP28_SAE:          return "X86ISD::RCP28_SAE";
29859   case X86ISD::RCP28S:             return "X86ISD::RCP28S";
29860   case X86ISD::RCP28S_SAE:         return "X86ISD::RCP28S_SAE";
29861   case X86ISD::EXP2:               return "X86ISD::EXP2";
29862   case X86ISD::EXP2_SAE:           return "X86ISD::EXP2_SAE";
29863   case X86ISD::RSQRT14:            return "X86ISD::RSQRT14";
29864   case X86ISD::RSQRT14S:           return "X86ISD::RSQRT14S";
29865   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
29866   case X86ISD::RSQRT28_SAE:        return "X86ISD::RSQRT28_SAE";
29867   case X86ISD::RSQRT28S:           return "X86ISD::RSQRT28S";
29868   case X86ISD::RSQRT28S_SAE:       return "X86ISD::RSQRT28S_SAE";
29869   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
29870   case X86ISD::FADDS:              return "X86ISD::FADDS";
29871   case X86ISD::FADDS_RND:          return "X86ISD::FADDS_RND";
29872   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
29873   case X86ISD::FSUBS:              return "X86ISD::FSUBS";
29874   case X86ISD::FSUBS_RND:          return "X86ISD::FSUBS_RND";
29875   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
29876   case X86ISD::FMULS:              return "X86ISD::FMULS";
29877   case X86ISD::FMULS_RND:          return "X86ISD::FMULS_RND";
29878   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
29879   case X86ISD::FDIVS:              return "X86ISD::FDIVS";
29880   case X86ISD::FDIVS_RND:          return "X86ISD::FDIVS_RND";
29881   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
29882   case X86ISD::FSQRTS:             return "X86ISD::FSQRTS";
29883   case X86ISD::FSQRTS_RND:         return "X86ISD::FSQRTS_RND";
29884   case X86ISD::FGETEXP:            return "X86ISD::FGETEXP";
29885   case X86ISD::FGETEXP_SAE:        return "X86ISD::FGETEXP_SAE";
29886   case X86ISD::FGETEXPS:           return "X86ISD::FGETEXPS";
29887   case X86ISD::FGETEXPS_SAE:       return "X86ISD::FGETEXPS_SAE";
29888   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
29889   case X86ISD::SCALEF_RND:         return "X86ISD::SCALEF_RND";
29890   case X86ISD::SCALEFS:            return "X86ISD::SCALEFS";
29891   case X86ISD::SCALEFS_RND:        return "X86ISD::SCALEFS_RND";
29892   case X86ISD::AVG:                return "X86ISD::AVG";
29893   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
29894   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
29895   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
29896   case X86ISD::CVTTP2SI:           return "X86ISD::CVTTP2SI";
29897   case X86ISD::CVTTP2UI:           return "X86ISD::CVTTP2UI";
29898   case X86ISD::STRICT_CVTTP2SI:    return "X86ISD::STRICT_CVTTP2SI";
29899   case X86ISD::STRICT_CVTTP2UI:    return "X86ISD::STRICT_CVTTP2UI";
29900   case X86ISD::MCVTTP2SI:          return "X86ISD::MCVTTP2SI";
29901   case X86ISD::MCVTTP2UI:          return "X86ISD::MCVTTP2UI";
29902   case X86ISD::CVTTP2SI_SAE:       return "X86ISD::CVTTP2SI_SAE";
29903   case X86ISD::CVTTP2UI_SAE:       return "X86ISD::CVTTP2UI_SAE";
29904   case X86ISD::CVTTS2SI:           return "X86ISD::CVTTS2SI";
29905   case X86ISD::CVTTS2UI:           return "X86ISD::CVTTS2UI";
29906   case X86ISD::CVTTS2SI_SAE:       return "X86ISD::CVTTS2SI_SAE";
29907   case X86ISD::CVTTS2UI_SAE:       return "X86ISD::CVTTS2UI_SAE";
29908   case X86ISD::CVTSI2P:            return "X86ISD::CVTSI2P";
29909   case X86ISD::CVTUI2P:            return "X86ISD::CVTUI2P";
29910   case X86ISD::STRICT_CVTSI2P:     return "X86ISD::STRICT_CVTSI2P";
29911   case X86ISD::STRICT_CVTUI2P:     return "X86ISD::STRICT_CVTUI2P";
29912   case X86ISD::MCVTSI2P:           return "X86ISD::MCVTSI2P";
29913   case X86ISD::MCVTUI2P:           return "X86ISD::MCVTUI2P";
29914   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
29915   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
29916   case X86ISD::MULTISHIFT:         return "X86ISD::MULTISHIFT";
29917   case X86ISD::SCALAR_SINT_TO_FP:     return "X86ISD::SCALAR_SINT_TO_FP";
29918   case X86ISD::SCALAR_SINT_TO_FP_RND: return "X86ISD::SCALAR_SINT_TO_FP_RND";
29919   case X86ISD::SCALAR_UINT_TO_FP:     return "X86ISD::SCALAR_UINT_TO_FP";
29920   case X86ISD::SCALAR_UINT_TO_FP_RND: return "X86ISD::SCALAR_UINT_TO_FP_RND";
29921   case X86ISD::CVTPS2PH:           return "X86ISD::CVTPS2PH";
29922   case X86ISD::MCVTPS2PH:          return "X86ISD::MCVTPS2PH";
29923   case X86ISD::CVTPH2PS:           return "X86ISD::CVTPH2PS";
29924   case X86ISD::CVTPH2PS_SAE:       return "X86ISD::CVTPH2PS_SAE";
29925   case X86ISD::CVTP2SI:            return "X86ISD::CVTP2SI";
29926   case X86ISD::CVTP2UI:            return "X86ISD::CVTP2UI";
29927   case X86ISD::MCVTP2SI:           return "X86ISD::MCVTP2SI";
29928   case X86ISD::MCVTP2UI:           return "X86ISD::MCVTP2UI";
29929   case X86ISD::CVTP2SI_RND:        return "X86ISD::CVTP2SI_RND";
29930   case X86ISD::CVTP2UI_RND:        return "X86ISD::CVTP2UI_RND";
29931   case X86ISD::CVTS2SI:            return "X86ISD::CVTS2SI";
29932   case X86ISD::CVTS2UI:            return "X86ISD::CVTS2UI";
29933   case X86ISD::CVTS2SI_RND:        return "X86ISD::CVTS2SI_RND";
29934   case X86ISD::CVTS2UI_RND:        return "X86ISD::CVTS2UI_RND";
29935   case X86ISD::CVTNE2PS2BF16:      return "X86ISD::CVTNE2PS2BF16";
29936   case X86ISD::CVTNEPS2BF16:       return "X86ISD::CVTNEPS2BF16";
29937   case X86ISD::MCVTNEPS2BF16:      return "X86ISD::MCVTNEPS2BF16";
29938   case X86ISD::DPBF16PS:           return "X86ISD::DPBF16PS";
29939   case X86ISD::LWPINS:             return "X86ISD::LWPINS";
29940   case X86ISD::MGATHER:            return "X86ISD::MGATHER";
29941   case X86ISD::MSCATTER:           return "X86ISD::MSCATTER";
29942   case X86ISD::VPDPBUSD:           return "X86ISD::VPDPBUSD";
29943   case X86ISD::VPDPBUSDS:          return "X86ISD::VPDPBUSDS";
29944   case X86ISD::VPDPWSSD:           return "X86ISD::VPDPWSSD";
29945   case X86ISD::VPDPWSSDS:          return "X86ISD::VPDPWSSDS";
29946   case X86ISD::VPSHUFBITQMB:       return "X86ISD::VPSHUFBITQMB";
29947   case X86ISD::GF2P8MULB:          return "X86ISD::GF2P8MULB";
29948   case X86ISD::GF2P8AFFINEQB:      return "X86ISD::GF2P8AFFINEQB";
29949   case X86ISD::GF2P8AFFINEINVQB:   return "X86ISD::GF2P8AFFINEINVQB";
29950   case X86ISD::NT_CALL:            return "X86ISD::NT_CALL";
29951   case X86ISD::NT_BRIND:           return "X86ISD::NT_BRIND";
29952   case X86ISD::UMWAIT:             return "X86ISD::UMWAIT";
29953   case X86ISD::TPAUSE:             return "X86ISD::TPAUSE";
29954   case X86ISD::ENQCMD:             return "X86ISD:ENQCMD";
29955   case X86ISD::ENQCMDS:            return "X86ISD:ENQCMDS";
29956   case X86ISD::VP2INTERSECT:       return "X86ISD::VP2INTERSECT";
29957   }
29958   return nullptr;
29959 }
29960 
29961 /// Return true if the addressing mode represented by AM is legal for this
29962 /// target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const29963 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
29964                                               const AddrMode &AM, Type *Ty,
29965                                               unsigned AS,
29966                                               Instruction *I) const {
29967   // X86 supports extremely general addressing modes.
29968   CodeModel::Model M = getTargetMachine().getCodeModel();
29969 
29970   // X86 allows a sign-extended 32-bit immediate field as a displacement.
29971   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
29972     return false;
29973 
29974   if (AM.BaseGV) {
29975     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
29976 
29977     // If a reference to this global requires an extra load, we can't fold it.
29978     if (isGlobalStubReference(GVFlags))
29979       return false;
29980 
29981     // If BaseGV requires a register for the PIC base, we cannot also have a
29982     // BaseReg specified.
29983     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
29984       return false;
29985 
29986     // If lower 4G is not available, then we must use rip-relative addressing.
29987     if ((M != CodeModel::Small || isPositionIndependent()) &&
29988         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
29989       return false;
29990   }
29991 
29992   switch (AM.Scale) {
29993   case 0:
29994   case 1:
29995   case 2:
29996   case 4:
29997   case 8:
29998     // These scales always work.
29999     break;
30000   case 3:
30001   case 5:
30002   case 9:
30003     // These scales are formed with basereg+scalereg.  Only accept if there is
30004     // no basereg yet.
30005     if (AM.HasBaseReg)
30006       return false;
30007     break;
30008   default:  // Other stuff never works.
30009     return false;
30010   }
30011 
30012   return true;
30013 }
30014 
isVectorShiftByScalarCheap(Type * Ty) const30015 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
30016   unsigned Bits = Ty->getScalarSizeInBits();
30017 
30018   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
30019   // particularly cheaper than those without.
30020   if (Bits == 8)
30021     return false;
30022 
30023   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
30024   if (Subtarget.hasXOP() && Ty->getPrimitiveSizeInBits() == 128 &&
30025       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
30026     return false;
30027 
30028   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
30029   // shifts just as cheap as scalar ones.
30030   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
30031     return false;
30032 
30033   // AVX512BW has shifts such as vpsllvw.
30034   if (Subtarget.hasBWI() && Bits == 16)
30035       return false;
30036 
30037   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
30038   // fully general vector.
30039   return true;
30040 }
30041 
isBinOp(unsigned Opcode) const30042 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
30043   switch (Opcode) {
30044   // These are non-commutative binops.
30045   // TODO: Add more X86ISD opcodes once we have test coverage.
30046   case X86ISD::ANDNP:
30047   case X86ISD::PCMPGT:
30048   case X86ISD::FMAX:
30049   case X86ISD::FMIN:
30050   case X86ISD::FANDN:
30051     return true;
30052   }
30053 
30054   return TargetLoweringBase::isBinOp(Opcode);
30055 }
30056 
isCommutativeBinOp(unsigned Opcode) const30057 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
30058   switch (Opcode) {
30059   // TODO: Add more X86ISD opcodes once we have test coverage.
30060   case X86ISD::PCMPEQ:
30061   case X86ISD::PMULDQ:
30062   case X86ISD::PMULUDQ:
30063   case X86ISD::FMAXC:
30064   case X86ISD::FMINC:
30065   case X86ISD::FAND:
30066   case X86ISD::FOR:
30067   case X86ISD::FXOR:
30068     return true;
30069   }
30070 
30071   return TargetLoweringBase::isCommutativeBinOp(Opcode);
30072 }
30073 
isTruncateFree(Type * Ty1,Type * Ty2) const30074 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
30075   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
30076     return false;
30077   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
30078   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
30079   return NumBits1 > NumBits2;
30080 }
30081 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const30082 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
30083   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
30084     return false;
30085 
30086   if (!isTypeLegal(EVT::getEVT(Ty1)))
30087     return false;
30088 
30089   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
30090 
30091   // Assuming the caller doesn't have a zeroext or signext return parameter,
30092   // truncation all the way down to i1 is valid.
30093   return true;
30094 }
30095 
isLegalICmpImmediate(int64_t Imm) const30096 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
30097   return isInt<32>(Imm);
30098 }
30099 
isLegalAddImmediate(int64_t Imm) const30100 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
30101   // Can also use sub to handle negated immediates.
30102   return isInt<32>(Imm);
30103 }
30104 
isLegalStoreImmediate(int64_t Imm) const30105 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
30106   return isInt<32>(Imm);
30107 }
30108 
isTruncateFree(EVT VT1,EVT VT2) const30109 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
30110   if (!VT1.isInteger() || !VT2.isInteger())
30111     return false;
30112   unsigned NumBits1 = VT1.getSizeInBits();
30113   unsigned NumBits2 = VT2.getSizeInBits();
30114   return NumBits1 > NumBits2;
30115 }
30116 
isZExtFree(Type * Ty1,Type * Ty2) const30117 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
30118   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
30119   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
30120 }
30121 
isZExtFree(EVT VT1,EVT VT2) const30122 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
30123   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
30124   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
30125 }
30126 
isZExtFree(SDValue Val,EVT VT2) const30127 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
30128   EVT VT1 = Val.getValueType();
30129   if (isZExtFree(VT1, VT2))
30130     return true;
30131 
30132   if (Val.getOpcode() != ISD::LOAD)
30133     return false;
30134 
30135   if (!VT1.isSimple() || !VT1.isInteger() ||
30136       !VT2.isSimple() || !VT2.isInteger())
30137     return false;
30138 
30139   switch (VT1.getSimpleVT().SimpleTy) {
30140   default: break;
30141   case MVT::i8:
30142   case MVT::i16:
30143   case MVT::i32:
30144     // X86 has 8, 16, and 32-bit zero-extending loads.
30145     return true;
30146   }
30147 
30148   return false;
30149 }
30150 
isVectorLoadExtDesirable(SDValue ExtVal) const30151 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
30152   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
30153     return false;
30154 
30155   EVT SrcVT = ExtVal.getOperand(0).getValueType();
30156 
30157   // There is no extending load for vXi1.
30158   if (SrcVT.getScalarType() == MVT::i1)
30159     return false;
30160 
30161   return true;
30162 }
30163 
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const30164 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
30165                                                    EVT VT) const {
30166   if (!Subtarget.hasAnyFMA())
30167     return false;
30168 
30169   VT = VT.getScalarType();
30170 
30171   if (!VT.isSimple())
30172     return false;
30173 
30174   switch (VT.getSimpleVT().SimpleTy) {
30175   case MVT::f32:
30176   case MVT::f64:
30177     return true;
30178   default:
30179     break;
30180   }
30181 
30182   return false;
30183 }
30184 
isNarrowingProfitable(EVT VT1,EVT VT2) const30185 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
30186   // i16 instructions are longer (0x66 prefix) and potentially slower.
30187   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
30188 }
30189 
30190 /// Targets can use this to indicate that they only support *some*
30191 /// VECTOR_SHUFFLE operations, those with specific masks.
30192 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
30193 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const30194 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
30195   if (!VT.isSimple())
30196     return false;
30197 
30198   // Not for i1 vectors
30199   if (VT.getSimpleVT().getScalarType() == MVT::i1)
30200     return false;
30201 
30202   // Very little shuffling can be done for 64-bit vectors right now.
30203   if (VT.getSimpleVT().getSizeInBits() == 64)
30204     return false;
30205 
30206   // We only care that the types being shuffled are legal. The lowering can
30207   // handle any possible shuffle mask that results.
30208   return isTypeLegal(VT.getSimpleVT());
30209 }
30210 
isVectorClearMaskLegal(ArrayRef<int> Mask,EVT VT) const30211 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
30212                                                EVT VT) const {
30213   // Don't convert an 'and' into a shuffle that we don't directly support.
30214   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
30215   if (!Subtarget.hasAVX2())
30216     if (VT == MVT::v32i8 || VT == MVT::v16i16)
30217       return false;
30218 
30219   // Just delegate to the generic legality, clear masks aren't special.
30220   return isShuffleMaskLegal(Mask, VT);
30221 }
30222 
areJTsAllowed(const Function * Fn) const30223 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
30224   // If the subtarget is using retpolines, we need to not generate jump tables.
30225   if (Subtarget.useRetpolineIndirectBranches())
30226     return false;
30227 
30228   // Otherwise, fallback on the generic logic.
30229   return TargetLowering::areJTsAllowed(Fn);
30230 }
30231 
30232 //===----------------------------------------------------------------------===//
30233 //                           X86 Scheduler Hooks
30234 //===----------------------------------------------------------------------===//
30235 
30236 /// Utility function to emit xbegin specifying the start of an RTM region.
emitXBegin(MachineInstr & MI,MachineBasicBlock * MBB,const TargetInstrInfo * TII)30237 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
30238                                      const TargetInstrInfo *TII) {
30239   DebugLoc DL = MI.getDebugLoc();
30240 
30241   const BasicBlock *BB = MBB->getBasicBlock();
30242   MachineFunction::iterator I = ++MBB->getIterator();
30243 
30244   // For the v = xbegin(), we generate
30245   //
30246   // thisMBB:
30247   //  xbegin sinkMBB
30248   //
30249   // mainMBB:
30250   //  s0 = -1
30251   //
30252   // fallBB:
30253   //  eax = # XABORT_DEF
30254   //  s1 = eax
30255   //
30256   // sinkMBB:
30257   //  v = phi(s0/mainBB, s1/fallBB)
30258 
30259   MachineBasicBlock *thisMBB = MBB;
30260   MachineFunction *MF = MBB->getParent();
30261   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
30262   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
30263   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
30264   MF->insert(I, mainMBB);
30265   MF->insert(I, fallMBB);
30266   MF->insert(I, sinkMBB);
30267 
30268   // Transfer the remainder of BB and its successor edges to sinkMBB.
30269   sinkMBB->splice(sinkMBB->begin(), MBB,
30270                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
30271   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
30272 
30273   MachineRegisterInfo &MRI = MF->getRegInfo();
30274   Register DstReg = MI.getOperand(0).getReg();
30275   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
30276   Register mainDstReg = MRI.createVirtualRegister(RC);
30277   Register fallDstReg = MRI.createVirtualRegister(RC);
30278 
30279   // thisMBB:
30280   //  xbegin fallMBB
30281   //  # fallthrough to mainMBB
30282   //  # abortion to fallMBB
30283   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
30284   thisMBB->addSuccessor(mainMBB);
30285   thisMBB->addSuccessor(fallMBB);
30286 
30287   // mainMBB:
30288   //  mainDstReg := -1
30289   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
30290   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
30291   mainMBB->addSuccessor(sinkMBB);
30292 
30293   // fallMBB:
30294   //  ; pseudo instruction to model hardware's definition from XABORT
30295   //  EAX := XABORT_DEF
30296   //  fallDstReg := EAX
30297   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
30298   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
30299       .addReg(X86::EAX);
30300   fallMBB->addSuccessor(sinkMBB);
30301 
30302   // sinkMBB:
30303   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
30304   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
30305       .addReg(mainDstReg).addMBB(mainMBB)
30306       .addReg(fallDstReg).addMBB(fallMBB);
30307 
30308   MI.eraseFromParent();
30309   return sinkMBB;
30310 }
30311 
30312 
30313 
30314 MachineBasicBlock *
EmitVAARG64WithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const30315 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr &MI,
30316                                                  MachineBasicBlock *MBB) const {
30317   // Emit va_arg instruction on X86-64.
30318 
30319   // Operands to this pseudo-instruction:
30320   // 0  ) Output        : destination address (reg)
30321   // 1-5) Input         : va_list address (addr, i64mem)
30322   // 6  ) ArgSize       : Size (in bytes) of vararg type
30323   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
30324   // 8  ) Align         : Alignment of type
30325   // 9  ) EFLAGS (implicit-def)
30326 
30327   assert(MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
30328   static_assert(X86::AddrNumOperands == 5,
30329                 "VAARG_64 assumes 5 address operands");
30330 
30331   Register DestReg = MI.getOperand(0).getReg();
30332   MachineOperand &Base = MI.getOperand(1);
30333   MachineOperand &Scale = MI.getOperand(2);
30334   MachineOperand &Index = MI.getOperand(3);
30335   MachineOperand &Disp = MI.getOperand(4);
30336   MachineOperand &Segment = MI.getOperand(5);
30337   unsigned ArgSize = MI.getOperand(6).getImm();
30338   unsigned ArgMode = MI.getOperand(7).getImm();
30339   unsigned Align = MI.getOperand(8).getImm();
30340 
30341   MachineFunction *MF = MBB->getParent();
30342 
30343   // Memory Reference
30344   assert(MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
30345 
30346   MachineMemOperand *OldMMO = MI.memoperands().front();
30347 
30348   // Clone the MMO into two separate MMOs for loading and storing
30349   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
30350       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
30351   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
30352       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
30353 
30354   // Machine Information
30355   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30356   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
30357   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
30358   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
30359   DebugLoc DL = MI.getDebugLoc();
30360 
30361   // struct va_list {
30362   //   i32   gp_offset
30363   //   i32   fp_offset
30364   //   i64   overflow_area (address)
30365   //   i64   reg_save_area (address)
30366   // }
30367   // sizeof(va_list) = 24
30368   // alignment(va_list) = 8
30369 
30370   unsigned TotalNumIntRegs = 6;
30371   unsigned TotalNumXMMRegs = 8;
30372   bool UseGPOffset = (ArgMode == 1);
30373   bool UseFPOffset = (ArgMode == 2);
30374   unsigned MaxOffset = TotalNumIntRegs * 8 +
30375                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
30376 
30377   /* Align ArgSize to a multiple of 8 */
30378   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
30379   bool NeedsAlign = (Align > 8);
30380 
30381   MachineBasicBlock *thisMBB = MBB;
30382   MachineBasicBlock *overflowMBB;
30383   MachineBasicBlock *offsetMBB;
30384   MachineBasicBlock *endMBB;
30385 
30386   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
30387   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
30388   unsigned OffsetReg = 0;
30389 
30390   if (!UseGPOffset && !UseFPOffset) {
30391     // If we only pull from the overflow region, we don't create a branch.
30392     // We don't need to alter control flow.
30393     OffsetDestReg = 0; // unused
30394     OverflowDestReg = DestReg;
30395 
30396     offsetMBB = nullptr;
30397     overflowMBB = thisMBB;
30398     endMBB = thisMBB;
30399   } else {
30400     // First emit code to check if gp_offset (or fp_offset) is below the bound.
30401     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
30402     // If not, pull from overflow_area. (branch to overflowMBB)
30403     //
30404     //       thisMBB
30405     //         |     .
30406     //         |        .
30407     //     offsetMBB   overflowMBB
30408     //         |        .
30409     //         |     .
30410     //        endMBB
30411 
30412     // Registers for the PHI in endMBB
30413     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
30414     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
30415 
30416     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
30417     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
30418     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
30419     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
30420 
30421     MachineFunction::iterator MBBIter = ++MBB->getIterator();
30422 
30423     // Insert the new basic blocks
30424     MF->insert(MBBIter, offsetMBB);
30425     MF->insert(MBBIter, overflowMBB);
30426     MF->insert(MBBIter, endMBB);
30427 
30428     // Transfer the remainder of MBB and its successor edges to endMBB.
30429     endMBB->splice(endMBB->begin(), thisMBB,
30430                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
30431     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
30432 
30433     // Make offsetMBB and overflowMBB successors of thisMBB
30434     thisMBB->addSuccessor(offsetMBB);
30435     thisMBB->addSuccessor(overflowMBB);
30436 
30437     // endMBB is a successor of both offsetMBB and overflowMBB
30438     offsetMBB->addSuccessor(endMBB);
30439     overflowMBB->addSuccessor(endMBB);
30440 
30441     // Load the offset value into a register
30442     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
30443     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
30444         .add(Base)
30445         .add(Scale)
30446         .add(Index)
30447         .addDisp(Disp, UseFPOffset ? 4 : 0)
30448         .add(Segment)
30449         .setMemRefs(LoadOnlyMMO);
30450 
30451     // Check if there is enough room left to pull this argument.
30452     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
30453       .addReg(OffsetReg)
30454       .addImm(MaxOffset + 8 - ArgSizeA8);
30455 
30456     // Branch to "overflowMBB" if offset >= max
30457     // Fall through to "offsetMBB" otherwise
30458     BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
30459       .addMBB(overflowMBB).addImm(X86::COND_AE);
30460   }
30461 
30462   // In offsetMBB, emit code to use the reg_save_area.
30463   if (offsetMBB) {
30464     assert(OffsetReg != 0);
30465 
30466     // Read the reg_save_area address.
30467     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
30468     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
30469         .add(Base)
30470         .add(Scale)
30471         .add(Index)
30472         .addDisp(Disp, 16)
30473         .add(Segment)
30474         .setMemRefs(LoadOnlyMMO);
30475 
30476     // Zero-extend the offset
30477     Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
30478     BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
30479         .addImm(0)
30480         .addReg(OffsetReg)
30481         .addImm(X86::sub_32bit);
30482 
30483     // Add the offset to the reg_save_area to get the final address.
30484     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
30485       .addReg(OffsetReg64)
30486       .addReg(RegSaveReg);
30487 
30488     // Compute the offset for the next argument
30489     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
30490     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
30491       .addReg(OffsetReg)
30492       .addImm(UseFPOffset ? 16 : 8);
30493 
30494     // Store it back into the va_list.
30495     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
30496         .add(Base)
30497         .add(Scale)
30498         .add(Index)
30499         .addDisp(Disp, UseFPOffset ? 4 : 0)
30500         .add(Segment)
30501         .addReg(NextOffsetReg)
30502         .setMemRefs(StoreOnlyMMO);
30503 
30504     // Jump to endMBB
30505     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
30506       .addMBB(endMBB);
30507   }
30508 
30509   //
30510   // Emit code to use overflow area
30511   //
30512 
30513   // Load the overflow_area address into a register.
30514   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
30515   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
30516       .add(Base)
30517       .add(Scale)
30518       .add(Index)
30519       .addDisp(Disp, 8)
30520       .add(Segment)
30521       .setMemRefs(LoadOnlyMMO);
30522 
30523   // If we need to align it, do so. Otherwise, just copy the address
30524   // to OverflowDestReg.
30525   if (NeedsAlign) {
30526     // Align the overflow address
30527     assert(isPowerOf2_32(Align) && "Alignment must be a power of 2");
30528     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
30529 
30530     // aligned_addr = (addr + (align-1)) & ~(align-1)
30531     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
30532       .addReg(OverflowAddrReg)
30533       .addImm(Align-1);
30534 
30535     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
30536       .addReg(TmpReg)
30537       .addImm(~(uint64_t)(Align-1));
30538   } else {
30539     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
30540       .addReg(OverflowAddrReg);
30541   }
30542 
30543   // Compute the next overflow address after this argument.
30544   // (the overflow address should be kept 8-byte aligned)
30545   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
30546   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
30547     .addReg(OverflowDestReg)
30548     .addImm(ArgSizeA8);
30549 
30550   // Store the new overflow address.
30551   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
30552       .add(Base)
30553       .add(Scale)
30554       .add(Index)
30555       .addDisp(Disp, 8)
30556       .add(Segment)
30557       .addReg(NextAddrReg)
30558       .setMemRefs(StoreOnlyMMO);
30559 
30560   // If we branched, emit the PHI to the front of endMBB.
30561   if (offsetMBB) {
30562     BuildMI(*endMBB, endMBB->begin(), DL,
30563             TII->get(X86::PHI), DestReg)
30564       .addReg(OffsetDestReg).addMBB(offsetMBB)
30565       .addReg(OverflowDestReg).addMBB(overflowMBB);
30566   }
30567 
30568   // Erase the pseudo instruction
30569   MI.eraseFromParent();
30570 
30571   return endMBB;
30572 }
30573 
EmitVAStartSaveXMMRegsWithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const30574 MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
30575     MachineInstr &MI, MachineBasicBlock *MBB) const {
30576   // Emit code to save XMM registers to the stack. The ABI says that the
30577   // number of registers to save is given in %al, so it's theoretically
30578   // possible to do an indirect jump trick to avoid saving all of them,
30579   // however this code takes a simpler approach and just executes all
30580   // of the stores if %al is non-zero. It's less code, and it's probably
30581   // easier on the hardware branch predictor, and stores aren't all that
30582   // expensive anyway.
30583 
30584   // Create the new basic blocks. One block contains all the XMM stores,
30585   // and one block is the final destination regardless of whether any
30586   // stores were performed.
30587   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
30588   MachineFunction *F = MBB->getParent();
30589   MachineFunction::iterator MBBIter = ++MBB->getIterator();
30590   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
30591   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
30592   F->insert(MBBIter, XMMSaveMBB);
30593   F->insert(MBBIter, EndMBB);
30594 
30595   // Transfer the remainder of MBB and its successor edges to EndMBB.
30596   EndMBB->splice(EndMBB->begin(), MBB,
30597                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
30598   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
30599 
30600   // The original block will now fall through to the XMM save block.
30601   MBB->addSuccessor(XMMSaveMBB);
30602   // The XMMSaveMBB will fall through to the end block.
30603   XMMSaveMBB->addSuccessor(EndMBB);
30604 
30605   // Now add the instructions.
30606   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30607   DebugLoc DL = MI.getDebugLoc();
30608 
30609   Register CountReg = MI.getOperand(0).getReg();
30610   int64_t RegSaveFrameIndex = MI.getOperand(1).getImm();
30611   int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
30612 
30613   if (!Subtarget.isCallingConvWin64(F->getFunction().getCallingConv())) {
30614     // If %al is 0, branch around the XMM save block.
30615     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
30616     BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(EndMBB).addImm(X86::COND_E);
30617     MBB->addSuccessor(EndMBB);
30618   }
30619 
30620   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
30621   // that was just emitted, but clearly shouldn't be "saved".
30622   assert((MI.getNumOperands() <= 3 ||
30623           !MI.getOperand(MI.getNumOperands() - 1).isReg() ||
30624           MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&
30625          "Expected last argument to be EFLAGS");
30626   unsigned MOVOpc = Subtarget.hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
30627   // In the XMM save block, save all the XMM argument registers.
30628   for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
30629     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
30630     MachineMemOperand *MMO = F->getMachineMemOperand(
30631         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
30632         MachineMemOperand::MOStore,
30633         /*Size=*/16, /*Align=*/16);
30634     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
30635         .addFrameIndex(RegSaveFrameIndex)
30636         .addImm(/*Scale=*/1)
30637         .addReg(/*IndexReg=*/0)
30638         .addImm(/*Disp=*/Offset)
30639         .addReg(/*Segment=*/0)
30640         .addReg(MI.getOperand(i).getReg())
30641         .addMemOperand(MMO);
30642   }
30643 
30644   MI.eraseFromParent(); // The pseudo instruction is gone now.
30645 
30646   return EndMBB;
30647 }
30648 
30649 // The EFLAGS operand of SelectItr might be missing a kill marker
30650 // because there were multiple uses of EFLAGS, and ISel didn't know
30651 // which to mark. Figure out whether SelectItr should have had a
30652 // kill marker, and set it if it should. Returns the correct kill
30653 // marker value.
checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)30654 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
30655                                      MachineBasicBlock* BB,
30656                                      const TargetRegisterInfo* TRI) {
30657   // Scan forward through BB for a use/def of EFLAGS.
30658   MachineBasicBlock::iterator miI(std::next(SelectItr));
30659   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
30660     const MachineInstr& mi = *miI;
30661     if (mi.readsRegister(X86::EFLAGS))
30662       return false;
30663     if (mi.definesRegister(X86::EFLAGS))
30664       break; // Should have kill-flag - update below.
30665   }
30666 
30667   // If we hit the end of the block, check whether EFLAGS is live into a
30668   // successor.
30669   if (miI == BB->end()) {
30670     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
30671                                           sEnd = BB->succ_end();
30672          sItr != sEnd; ++sItr) {
30673       MachineBasicBlock* succ = *sItr;
30674       if (succ->isLiveIn(X86::EFLAGS))
30675         return false;
30676     }
30677   }
30678 
30679   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
30680   // out. SelectMI should have a kill flag on EFLAGS.
30681   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
30682   return true;
30683 }
30684 
30685 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
30686 // together with other CMOV pseudo-opcodes into a single basic-block with
30687 // conditional jump around it.
isCMOVPseudo(MachineInstr & MI)30688 static bool isCMOVPseudo(MachineInstr &MI) {
30689   switch (MI.getOpcode()) {
30690   case X86::CMOV_FR32:
30691   case X86::CMOV_FR32X:
30692   case X86::CMOV_FR64:
30693   case X86::CMOV_FR64X:
30694   case X86::CMOV_GR8:
30695   case X86::CMOV_GR16:
30696   case X86::CMOV_GR32:
30697   case X86::CMOV_RFP32:
30698   case X86::CMOV_RFP64:
30699   case X86::CMOV_RFP80:
30700   case X86::CMOV_VR128:
30701   case X86::CMOV_VR128X:
30702   case X86::CMOV_VR256:
30703   case X86::CMOV_VR256X:
30704   case X86::CMOV_VR512:
30705   case X86::CMOV_VK2:
30706   case X86::CMOV_VK4:
30707   case X86::CMOV_VK8:
30708   case X86::CMOV_VK16:
30709   case X86::CMOV_VK32:
30710   case X86::CMOV_VK64:
30711     return true;
30712 
30713   default:
30714     return false;
30715   }
30716 }
30717 
30718 // Helper function, which inserts PHI functions into SinkMBB:
30719 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
30720 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
30721 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
30722 // the last PHI function inserted.
createPHIsForCMOVsInSinkBB(MachineBasicBlock::iterator MIItBegin,MachineBasicBlock::iterator MIItEnd,MachineBasicBlock * TrueMBB,MachineBasicBlock * FalseMBB,MachineBasicBlock * SinkMBB)30723 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
30724     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
30725     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
30726     MachineBasicBlock *SinkMBB) {
30727   MachineFunction *MF = TrueMBB->getParent();
30728   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
30729   DebugLoc DL = MIItBegin->getDebugLoc();
30730 
30731   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
30732   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
30733 
30734   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
30735 
30736   // As we are creating the PHIs, we have to be careful if there is more than
30737   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
30738   // PHIs have to reference the individual true/false inputs from earlier PHIs.
30739   // That also means that PHI construction must work forward from earlier to
30740   // later, and that the code must maintain a mapping from earlier PHI's
30741   // destination registers, and the registers that went into the PHI.
30742   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
30743   MachineInstrBuilder MIB;
30744 
30745   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
30746     Register DestReg = MIIt->getOperand(0).getReg();
30747     Register Op1Reg = MIIt->getOperand(1).getReg();
30748     Register Op2Reg = MIIt->getOperand(2).getReg();
30749 
30750     // If this CMOV we are generating is the opposite condition from
30751     // the jump we generated, then we have to swap the operands for the
30752     // PHI that is going to be generated.
30753     if (MIIt->getOperand(3).getImm() == OppCC)
30754       std::swap(Op1Reg, Op2Reg);
30755 
30756     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
30757       Op1Reg = RegRewriteTable[Op1Reg].first;
30758 
30759     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
30760       Op2Reg = RegRewriteTable[Op2Reg].second;
30761 
30762     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
30763               .addReg(Op1Reg)
30764               .addMBB(FalseMBB)
30765               .addReg(Op2Reg)
30766               .addMBB(TrueMBB);
30767 
30768     // Add this PHI to the rewrite table.
30769     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
30770   }
30771 
30772   return MIB;
30773 }
30774 
30775 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
30776 MachineBasicBlock *
EmitLoweredCascadedSelect(MachineInstr & FirstCMOV,MachineInstr & SecondCascadedCMOV,MachineBasicBlock * ThisMBB) const30777 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
30778                                              MachineInstr &SecondCascadedCMOV,
30779                                              MachineBasicBlock *ThisMBB) const {
30780   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30781   DebugLoc DL = FirstCMOV.getDebugLoc();
30782 
30783   // We lower cascaded CMOVs such as
30784   //
30785   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
30786   //
30787   // to two successive branches.
30788   //
30789   // Without this, we would add a PHI between the two jumps, which ends up
30790   // creating a few copies all around. For instance, for
30791   //
30792   //    (sitofp (zext (fcmp une)))
30793   //
30794   // we would generate:
30795   //
30796   //         ucomiss %xmm1, %xmm0
30797   //         movss  <1.0f>, %xmm0
30798   //         movaps  %xmm0, %xmm1
30799   //         jne     .LBB5_2
30800   //         xorps   %xmm1, %xmm1
30801   // .LBB5_2:
30802   //         jp      .LBB5_4
30803   //         movaps  %xmm1, %xmm0
30804   // .LBB5_4:
30805   //         retq
30806   //
30807   // because this custom-inserter would have generated:
30808   //
30809   //   A
30810   //   | \
30811   //   |  B
30812   //   | /
30813   //   C
30814   //   | \
30815   //   |  D
30816   //   | /
30817   //   E
30818   //
30819   // A: X = ...; Y = ...
30820   // B: empty
30821   // C: Z = PHI [X, A], [Y, B]
30822   // D: empty
30823   // E: PHI [X, C], [Z, D]
30824   //
30825   // If we lower both CMOVs in a single step, we can instead generate:
30826   //
30827   //   A
30828   //   | \
30829   //   |  C
30830   //   | /|
30831   //   |/ |
30832   //   |  |
30833   //   |  D
30834   //   | /
30835   //   E
30836   //
30837   // A: X = ...; Y = ...
30838   // D: empty
30839   // E: PHI [X, A], [X, C], [Y, D]
30840   //
30841   // Which, in our sitofp/fcmp example, gives us something like:
30842   //
30843   //         ucomiss %xmm1, %xmm0
30844   //         movss  <1.0f>, %xmm0
30845   //         jne     .LBB5_4
30846   //         jp      .LBB5_4
30847   //         xorps   %xmm0, %xmm0
30848   // .LBB5_4:
30849   //         retq
30850   //
30851 
30852   // We lower cascaded CMOV into two successive branches to the same block.
30853   // EFLAGS is used by both, so mark it as live in the second.
30854   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
30855   MachineFunction *F = ThisMBB->getParent();
30856   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
30857   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
30858   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
30859 
30860   MachineFunction::iterator It = ++ThisMBB->getIterator();
30861   F->insert(It, FirstInsertedMBB);
30862   F->insert(It, SecondInsertedMBB);
30863   F->insert(It, SinkMBB);
30864 
30865   // For a cascaded CMOV, we lower it to two successive branches to
30866   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
30867   // the FirstInsertedMBB.
30868   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
30869 
30870   // If the EFLAGS register isn't dead in the terminator, then claim that it's
30871   // live into the sink and copy blocks.
30872   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
30873   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
30874       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
30875     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
30876     SinkMBB->addLiveIn(X86::EFLAGS);
30877   }
30878 
30879   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
30880   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
30881                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
30882                   ThisMBB->end());
30883   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
30884 
30885   // Fallthrough block for ThisMBB.
30886   ThisMBB->addSuccessor(FirstInsertedMBB);
30887   // The true block target of the first branch is always SinkMBB.
30888   ThisMBB->addSuccessor(SinkMBB);
30889   // Fallthrough block for FirstInsertedMBB.
30890   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
30891   // The true block for the branch of FirstInsertedMBB.
30892   FirstInsertedMBB->addSuccessor(SinkMBB);
30893   // This is fallthrough.
30894   SecondInsertedMBB->addSuccessor(SinkMBB);
30895 
30896   // Create the conditional branch instructions.
30897   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
30898   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
30899 
30900   X86::CondCode SecondCC =
30901       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
30902   BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
30903 
30904   //  SinkMBB:
30905   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
30906   Register DestReg = FirstCMOV.getOperand(0).getReg();
30907   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
30908   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
30909   MachineInstrBuilder MIB =
30910       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
30911           .addReg(Op1Reg)
30912           .addMBB(SecondInsertedMBB)
30913           .addReg(Op2Reg)
30914           .addMBB(ThisMBB);
30915 
30916   // The second SecondInsertedMBB provides the same incoming value as the
30917   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
30918   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
30919   // Copy the PHI result to the register defined by the second CMOV.
30920   BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
30921           TII->get(TargetOpcode::COPY),
30922           SecondCascadedCMOV.getOperand(0).getReg())
30923       .addReg(FirstCMOV.getOperand(0).getReg());
30924 
30925   // Now remove the CMOVs.
30926   FirstCMOV.eraseFromParent();
30927   SecondCascadedCMOV.eraseFromParent();
30928 
30929   return SinkMBB;
30930 }
30931 
30932 MachineBasicBlock *
EmitLoweredSelect(MachineInstr & MI,MachineBasicBlock * ThisMBB) const30933 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
30934                                      MachineBasicBlock *ThisMBB) const {
30935   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30936   DebugLoc DL = MI.getDebugLoc();
30937 
30938   // To "insert" a SELECT_CC instruction, we actually have to insert the
30939   // diamond control-flow pattern.  The incoming instruction knows the
30940   // destination vreg to set, the condition code register to branch on, the
30941   // true/false values to select between and a branch opcode to use.
30942 
30943   //  ThisMBB:
30944   //  ...
30945   //   TrueVal = ...
30946   //   cmpTY ccX, r1, r2
30947   //   bCC copy1MBB
30948   //   fallthrough --> FalseMBB
30949 
30950   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
30951   // as described above, by inserting a BB, and then making a PHI at the join
30952   // point to select the true and false operands of the CMOV in the PHI.
30953   //
30954   // The code also handles two different cases of multiple CMOV opcodes
30955   // in a row.
30956   //
30957   // Case 1:
30958   // In this case, there are multiple CMOVs in a row, all which are based on
30959   // the same condition setting (or the exact opposite condition setting).
30960   // In this case we can lower all the CMOVs using a single inserted BB, and
30961   // then make a number of PHIs at the join point to model the CMOVs. The only
30962   // trickiness here, is that in a case like:
30963   //
30964   // t2 = CMOV cond1 t1, f1
30965   // t3 = CMOV cond1 t2, f2
30966   //
30967   // when rewriting this into PHIs, we have to perform some renaming on the
30968   // temps since you cannot have a PHI operand refer to a PHI result earlier
30969   // in the same block.  The "simple" but wrong lowering would be:
30970   //
30971   // t2 = PHI t1(BB1), f1(BB2)
30972   // t3 = PHI t2(BB1), f2(BB2)
30973   //
30974   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
30975   // renaming is to note that on the path through BB1, t2 is really just a
30976   // copy of t1, and do that renaming, properly generating:
30977   //
30978   // t2 = PHI t1(BB1), f1(BB2)
30979   // t3 = PHI t1(BB1), f2(BB2)
30980   //
30981   // Case 2:
30982   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
30983   // function - EmitLoweredCascadedSelect.
30984 
30985   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
30986   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
30987   MachineInstr *LastCMOV = &MI;
30988   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
30989 
30990   // Check for case 1, where there are multiple CMOVs with the same condition
30991   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
30992   // number of jumps the most.
30993 
30994   if (isCMOVPseudo(MI)) {
30995     // See if we have a string of CMOVS with the same condition. Skip over
30996     // intervening debug insts.
30997     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
30998            (NextMIIt->getOperand(3).getImm() == CC ||
30999             NextMIIt->getOperand(3).getImm() == OppCC)) {
31000       LastCMOV = &*NextMIIt;
31001       ++NextMIIt;
31002       NextMIIt = skipDebugInstructionsForward(NextMIIt, ThisMBB->end());
31003     }
31004   }
31005 
31006   // This checks for case 2, but only do this if we didn't already find
31007   // case 1, as indicated by LastCMOV == MI.
31008   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
31009       NextMIIt->getOpcode() == MI.getOpcode() &&
31010       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
31011       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
31012       NextMIIt->getOperand(1).isKill()) {
31013     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
31014   }
31015 
31016   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
31017   MachineFunction *F = ThisMBB->getParent();
31018   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
31019   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
31020 
31021   MachineFunction::iterator It = ++ThisMBB->getIterator();
31022   F->insert(It, FalseMBB);
31023   F->insert(It, SinkMBB);
31024 
31025   // If the EFLAGS register isn't dead in the terminator, then claim that it's
31026   // live into the sink and copy blocks.
31027   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
31028   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
31029       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
31030     FalseMBB->addLiveIn(X86::EFLAGS);
31031     SinkMBB->addLiveIn(X86::EFLAGS);
31032   }
31033 
31034   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
31035   auto DbgEnd = MachineBasicBlock::iterator(LastCMOV);
31036   auto DbgIt = MachineBasicBlock::iterator(MI);
31037   while (DbgIt != DbgEnd) {
31038     auto Next = std::next(DbgIt);
31039     if (DbgIt->isDebugInstr())
31040       SinkMBB->push_back(DbgIt->removeFromParent());
31041     DbgIt = Next;
31042   }
31043 
31044   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
31045   SinkMBB->splice(SinkMBB->end(), ThisMBB,
31046                   std::next(MachineBasicBlock::iterator(LastCMOV)),
31047                   ThisMBB->end());
31048   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
31049 
31050   // Fallthrough block for ThisMBB.
31051   ThisMBB->addSuccessor(FalseMBB);
31052   // The true block target of the first (or only) branch is always a SinkMBB.
31053   ThisMBB->addSuccessor(SinkMBB);
31054   // Fallthrough block for FalseMBB.
31055   FalseMBB->addSuccessor(SinkMBB);
31056 
31057   // Create the conditional branch instruction.
31058   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
31059 
31060   //  SinkMBB:
31061   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
31062   //  ...
31063   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
31064   MachineBasicBlock::iterator MIItEnd =
31065       std::next(MachineBasicBlock::iterator(LastCMOV));
31066   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
31067 
31068   // Now remove the CMOV(s).
31069   ThisMBB->erase(MIItBegin, MIItEnd);
31070 
31071   return SinkMBB;
31072 }
31073 
31074 MachineBasicBlock *
EmitLoweredSegAlloca(MachineInstr & MI,MachineBasicBlock * BB) const31075 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
31076                                         MachineBasicBlock *BB) const {
31077   MachineFunction *MF = BB->getParent();
31078   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31079   DebugLoc DL = MI.getDebugLoc();
31080   const BasicBlock *LLVM_BB = BB->getBasicBlock();
31081 
31082   assert(MF->shouldSplitStack());
31083 
31084   const bool Is64Bit = Subtarget.is64Bit();
31085   const bool IsLP64 = Subtarget.isTarget64BitLP64();
31086 
31087   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
31088   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
31089 
31090   // BB:
31091   //  ... [Till the alloca]
31092   // If stacklet is not large enough, jump to mallocMBB
31093   //
31094   // bumpMBB:
31095   //  Allocate by subtracting from RSP
31096   //  Jump to continueMBB
31097   //
31098   // mallocMBB:
31099   //  Allocate by call to runtime
31100   //
31101   // continueMBB:
31102   //  ...
31103   //  [rest of original BB]
31104   //
31105 
31106   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31107   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31108   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31109 
31110   MachineRegisterInfo &MRI = MF->getRegInfo();
31111   const TargetRegisterClass *AddrRegClass =
31112       getRegClassFor(getPointerTy(MF->getDataLayout()));
31113 
31114   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
31115            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
31116            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
31117            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
31118            sizeVReg = MI.getOperand(1).getReg(),
31119            physSPReg =
31120                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
31121 
31122   MachineFunction::iterator MBBIter = ++BB->getIterator();
31123 
31124   MF->insert(MBBIter, bumpMBB);
31125   MF->insert(MBBIter, mallocMBB);
31126   MF->insert(MBBIter, continueMBB);
31127 
31128   continueMBB->splice(continueMBB->begin(), BB,
31129                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
31130   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
31131 
31132   // Add code to the main basic block to check if the stack limit has been hit,
31133   // and if so, jump to mallocMBB otherwise to bumpMBB.
31134   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
31135   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
31136     .addReg(tmpSPVReg).addReg(sizeVReg);
31137   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
31138     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
31139     .addReg(SPLimitVReg);
31140   BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
31141 
31142   // bumpMBB simply decreases the stack pointer, since we know the current
31143   // stacklet has enough space.
31144   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
31145     .addReg(SPLimitVReg);
31146   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
31147     .addReg(SPLimitVReg);
31148   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
31149 
31150   // Calls into a routine in libgcc to allocate more space from the heap.
31151   const uint32_t *RegMask =
31152       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
31153   if (IsLP64) {
31154     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
31155       .addReg(sizeVReg);
31156     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
31157       .addExternalSymbol("__morestack_allocate_stack_space")
31158       .addRegMask(RegMask)
31159       .addReg(X86::RDI, RegState::Implicit)
31160       .addReg(X86::RAX, RegState::ImplicitDefine);
31161   } else if (Is64Bit) {
31162     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
31163       .addReg(sizeVReg);
31164     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
31165       .addExternalSymbol("__morestack_allocate_stack_space")
31166       .addRegMask(RegMask)
31167       .addReg(X86::EDI, RegState::Implicit)
31168       .addReg(X86::EAX, RegState::ImplicitDefine);
31169   } else {
31170     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
31171       .addImm(12);
31172     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
31173     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
31174       .addExternalSymbol("__morestack_allocate_stack_space")
31175       .addRegMask(RegMask)
31176       .addReg(X86::EAX, RegState::ImplicitDefine);
31177   }
31178 
31179   if (!Is64Bit)
31180     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
31181       .addImm(16);
31182 
31183   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
31184     .addReg(IsLP64 ? X86::RAX : X86::EAX);
31185   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
31186 
31187   // Set up the CFG correctly.
31188   BB->addSuccessor(bumpMBB);
31189   BB->addSuccessor(mallocMBB);
31190   mallocMBB->addSuccessor(continueMBB);
31191   bumpMBB->addSuccessor(continueMBB);
31192 
31193   // Take care of the PHI nodes.
31194   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
31195           MI.getOperand(0).getReg())
31196       .addReg(mallocPtrVReg)
31197       .addMBB(mallocMBB)
31198       .addReg(bumpSPPtrVReg)
31199       .addMBB(bumpMBB);
31200 
31201   // Delete the original pseudo instruction.
31202   MI.eraseFromParent();
31203 
31204   // And we're done.
31205   return continueMBB;
31206 }
31207 
31208 MachineBasicBlock *
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const31209 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
31210                                        MachineBasicBlock *BB) const {
31211   MachineFunction *MF = BB->getParent();
31212   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
31213   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
31214   DebugLoc DL = MI.getDebugLoc();
31215 
31216   assert(!isAsynchronousEHPersonality(
31217              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
31218          "SEH does not use catchret!");
31219 
31220   // Only 32-bit EH needs to worry about manually restoring stack pointers.
31221   if (!Subtarget.is32Bit())
31222     return BB;
31223 
31224   // C++ EH creates a new target block to hold the restore code, and wires up
31225   // the new block to the return destination with a normal JMP_4.
31226   MachineBasicBlock *RestoreMBB =
31227       MF->CreateMachineBasicBlock(BB->getBasicBlock());
31228   assert(BB->succ_size() == 1);
31229   MF->insert(std::next(BB->getIterator()), RestoreMBB);
31230   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
31231   BB->addSuccessor(RestoreMBB);
31232   MI.getOperand(0).setMBB(RestoreMBB);
31233 
31234   auto RestoreMBBI = RestoreMBB->begin();
31235   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
31236   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
31237   return BB;
31238 }
31239 
31240 MachineBasicBlock *
EmitLoweredCatchPad(MachineInstr & MI,MachineBasicBlock * BB) const31241 X86TargetLowering::EmitLoweredCatchPad(MachineInstr &MI,
31242                                        MachineBasicBlock *BB) const {
31243   MachineFunction *MF = BB->getParent();
31244   const Constant *PerFn = MF->getFunction().getPersonalityFn();
31245   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
31246   // Only 32-bit SEH requires special handling for catchpad.
31247   if (IsSEH && Subtarget.is32Bit()) {
31248     const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
31249     DebugLoc DL = MI.getDebugLoc();
31250     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
31251   }
31252   MI.eraseFromParent();
31253   return BB;
31254 }
31255 
31256 MachineBasicBlock *
EmitLoweredTLSAddr(MachineInstr & MI,MachineBasicBlock * BB) const31257 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
31258                                       MachineBasicBlock *BB) const {
31259   // So, here we replace TLSADDR with the sequence:
31260   // adjust_stackdown -> TLSADDR -> adjust_stackup.
31261   // We need this because TLSADDR is lowered into calls
31262   // inside MC, therefore without the two markers shrink-wrapping
31263   // may push the prologue/epilogue pass them.
31264   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
31265   DebugLoc DL = MI.getDebugLoc();
31266   MachineFunction &MF = *BB->getParent();
31267 
31268   // Emit CALLSEQ_START right before the instruction.
31269   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
31270   MachineInstrBuilder CallseqStart =
31271     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
31272   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
31273 
31274   // Emit CALLSEQ_END right after the instruction.
31275   // We don't call erase from parent because we want to keep the
31276   // original instruction around.
31277   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
31278   MachineInstrBuilder CallseqEnd =
31279     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
31280   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
31281 
31282   return BB;
31283 }
31284 
31285 MachineBasicBlock *
EmitLoweredTLSCall(MachineInstr & MI,MachineBasicBlock * BB) const31286 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
31287                                       MachineBasicBlock *BB) const {
31288   // This is pretty easy.  We're taking the value that we received from
31289   // our load from the relocation, sticking it in either RDI (x86-64)
31290   // or EAX and doing an indirect call.  The return value will then
31291   // be in the normal return register.
31292   MachineFunction *F = BB->getParent();
31293   const X86InstrInfo *TII = Subtarget.getInstrInfo();
31294   DebugLoc DL = MI.getDebugLoc();
31295 
31296   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
31297   assert(MI.getOperand(3).isGlobal() && "This should be a global");
31298 
31299   // Get a register mask for the lowered call.
31300   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
31301   // proper register mask.
31302   const uint32_t *RegMask =
31303       Subtarget.is64Bit() ?
31304       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
31305       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
31306   if (Subtarget.is64Bit()) {
31307     MachineInstrBuilder MIB =
31308         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
31309             .addReg(X86::RIP)
31310             .addImm(0)
31311             .addReg(0)
31312             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
31313                               MI.getOperand(3).getTargetFlags())
31314             .addReg(0);
31315     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
31316     addDirectMem(MIB, X86::RDI);
31317     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
31318   } else if (!isPositionIndependent()) {
31319     MachineInstrBuilder MIB =
31320         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
31321             .addReg(0)
31322             .addImm(0)
31323             .addReg(0)
31324             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
31325                               MI.getOperand(3).getTargetFlags())
31326             .addReg(0);
31327     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
31328     addDirectMem(MIB, X86::EAX);
31329     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
31330   } else {
31331     MachineInstrBuilder MIB =
31332         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
31333             .addReg(TII->getGlobalBaseReg(F))
31334             .addImm(0)
31335             .addReg(0)
31336             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
31337                               MI.getOperand(3).getTargetFlags())
31338             .addReg(0);
31339     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
31340     addDirectMem(MIB, X86::EAX);
31341     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
31342   }
31343 
31344   MI.eraseFromParent(); // The pseudo instruction is gone now.
31345   return BB;
31346 }
31347 
getOpcodeForRetpoline(unsigned RPOpc)31348 static unsigned getOpcodeForRetpoline(unsigned RPOpc) {
31349   switch (RPOpc) {
31350   case X86::RETPOLINE_CALL32:
31351     return X86::CALLpcrel32;
31352   case X86::RETPOLINE_CALL64:
31353     return X86::CALL64pcrel32;
31354   case X86::RETPOLINE_TCRETURN32:
31355     return X86::TCRETURNdi;
31356   case X86::RETPOLINE_TCRETURN64:
31357     return X86::TCRETURNdi64;
31358   }
31359   llvm_unreachable("not retpoline opcode");
31360 }
31361 
getRetpolineSymbol(const X86Subtarget & Subtarget,unsigned Reg)31362 static const char *getRetpolineSymbol(const X86Subtarget &Subtarget,
31363                                       unsigned Reg) {
31364   if (Subtarget.useRetpolineExternalThunk()) {
31365     // When using an external thunk for retpolines, we pick names that match the
31366     // names GCC happens to use as well. This helps simplify the implementation
31367     // of the thunks for kernels where they have no easy ability to create
31368     // aliases and are doing non-trivial configuration of the thunk's body. For
31369     // example, the Linux kernel will do boot-time hot patching of the thunk
31370     // bodies and cannot easily export aliases of these to loaded modules.
31371     //
31372     // Note that at any point in the future, we may need to change the semantics
31373     // of how we implement retpolines and at that time will likely change the
31374     // name of the called thunk. Essentially, there is no hard guarantee that
31375     // LLVM will generate calls to specific thunks, we merely make a best-effort
31376     // attempt to help out kernels and other systems where duplicating the
31377     // thunks is costly.
31378     switch (Reg) {
31379     case X86::EAX:
31380       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31381       return "__x86_indirect_thunk_eax";
31382     case X86::ECX:
31383       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31384       return "__x86_indirect_thunk_ecx";
31385     case X86::EDX:
31386       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31387       return "__x86_indirect_thunk_edx";
31388     case X86::EDI:
31389       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31390       return "__x86_indirect_thunk_edi";
31391     case X86::R11:
31392       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
31393       return "__x86_indirect_thunk_r11";
31394     }
31395     llvm_unreachable("unexpected reg for retpoline");
31396   }
31397 
31398   // When targeting an internal COMDAT thunk use an LLVM-specific name.
31399   switch (Reg) {
31400   case X86::EAX:
31401     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31402     return "__llvm_retpoline_eax";
31403   case X86::ECX:
31404     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31405     return "__llvm_retpoline_ecx";
31406   case X86::EDX:
31407     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31408     return "__llvm_retpoline_edx";
31409   case X86::EDI:
31410     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
31411     return "__llvm_retpoline_edi";
31412   case X86::R11:
31413     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
31414     return "__llvm_retpoline_r11";
31415   }
31416   llvm_unreachable("unexpected reg for retpoline");
31417 }
31418 
31419 MachineBasicBlock *
EmitLoweredRetpoline(MachineInstr & MI,MachineBasicBlock * BB) const31420 X86TargetLowering::EmitLoweredRetpoline(MachineInstr &MI,
31421                                         MachineBasicBlock *BB) const {
31422   // Copy the virtual register into the R11 physical register and
31423   // call the retpoline thunk.
31424   DebugLoc DL = MI.getDebugLoc();
31425   const X86InstrInfo *TII = Subtarget.getInstrInfo();
31426   Register CalleeVReg = MI.getOperand(0).getReg();
31427   unsigned Opc = getOpcodeForRetpoline(MI.getOpcode());
31428 
31429   // Find an available scratch register to hold the callee. On 64-bit, we can
31430   // just use R11, but we scan for uses anyway to ensure we don't generate
31431   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
31432   // already a register use operand to the call to hold the callee. If none
31433   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
31434   // register and ESI is the base pointer to realigned stack frames with VLAs.
31435   SmallVector<unsigned, 3> AvailableRegs;
31436   if (Subtarget.is64Bit())
31437     AvailableRegs.push_back(X86::R11);
31438   else
31439     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
31440 
31441   // Zero out any registers that are already used.
31442   for (const auto &MO : MI.operands()) {
31443     if (MO.isReg() && MO.isUse())
31444       for (unsigned &Reg : AvailableRegs)
31445         if (Reg == MO.getReg())
31446           Reg = 0;
31447   }
31448 
31449   // Choose the first remaining non-zero available register.
31450   unsigned AvailableReg = 0;
31451   for (unsigned MaybeReg : AvailableRegs) {
31452     if (MaybeReg) {
31453       AvailableReg = MaybeReg;
31454       break;
31455     }
31456   }
31457   if (!AvailableReg)
31458     report_fatal_error("calling convention incompatible with retpoline, no "
31459                        "available registers");
31460 
31461   const char *Symbol = getRetpolineSymbol(Subtarget, AvailableReg);
31462 
31463   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
31464       .addReg(CalleeVReg);
31465   MI.getOperand(0).ChangeToES(Symbol);
31466   MI.setDesc(TII->get(Opc));
31467   MachineInstrBuilder(*BB->getParent(), &MI)
31468       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
31469   return BB;
31470 }
31471 
31472 /// SetJmp implies future control flow change upon calling the corresponding
31473 /// LongJmp.
31474 /// Instead of using the 'return' instruction, the long jump fixes the stack and
31475 /// performs an indirect branch. To do so it uses the registers that were stored
31476 /// in the jump buffer (when calling SetJmp).
31477 /// In case the shadow stack is enabled we need to fix it as well, because some
31478 /// return addresses will be skipped.
31479 /// The function will save the SSP for future fixing in the function
31480 /// emitLongJmpShadowStackFix.
31481 /// \sa emitLongJmpShadowStackFix
31482 /// \param [in] MI The temporary Machine Instruction for the builtin.
31483 /// \param [in] MBB The Machine Basic Block that will be modified.
emitSetJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const31484 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
31485                                                  MachineBasicBlock *MBB) const {
31486   DebugLoc DL = MI.getDebugLoc();
31487   MachineFunction *MF = MBB->getParent();
31488   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31489   MachineRegisterInfo &MRI = MF->getRegInfo();
31490   MachineInstrBuilder MIB;
31491 
31492   // Memory Reference.
31493   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
31494                                            MI.memoperands_end());
31495 
31496   // Initialize a register with zero.
31497   MVT PVT = getPointerTy(MF->getDataLayout());
31498   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
31499   Register ZReg = MRI.createVirtualRegister(PtrRC);
31500   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
31501   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
31502       .addDef(ZReg)
31503       .addReg(ZReg, RegState::Undef)
31504       .addReg(ZReg, RegState::Undef);
31505 
31506   // Read the current SSP Register value to the zeroed register.
31507   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
31508   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
31509   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
31510 
31511   // Write the SSP register value to offset 3 in input memory buffer.
31512   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
31513   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
31514   const int64_t SSPOffset = 3 * PVT.getStoreSize();
31515   const unsigned MemOpndSlot = 1;
31516   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31517     if (i == X86::AddrDisp)
31518       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
31519     else
31520       MIB.add(MI.getOperand(MemOpndSlot + i));
31521   }
31522   MIB.addReg(SSPCopyReg);
31523   MIB.setMemRefs(MMOs);
31524 }
31525 
31526 MachineBasicBlock *
emitEHSjLjSetJmp(MachineInstr & MI,MachineBasicBlock * MBB) const31527 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
31528                                     MachineBasicBlock *MBB) const {
31529   DebugLoc DL = MI.getDebugLoc();
31530   MachineFunction *MF = MBB->getParent();
31531   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31532   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
31533   MachineRegisterInfo &MRI = MF->getRegInfo();
31534 
31535   const BasicBlock *BB = MBB->getBasicBlock();
31536   MachineFunction::iterator I = ++MBB->getIterator();
31537 
31538   // Memory Reference
31539   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
31540                                            MI.memoperands_end());
31541 
31542   unsigned DstReg;
31543   unsigned MemOpndSlot = 0;
31544 
31545   unsigned CurOp = 0;
31546 
31547   DstReg = MI.getOperand(CurOp++).getReg();
31548   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
31549   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
31550   (void)TRI;
31551   Register mainDstReg = MRI.createVirtualRegister(RC);
31552   Register restoreDstReg = MRI.createVirtualRegister(RC);
31553 
31554   MemOpndSlot = CurOp;
31555 
31556   MVT PVT = getPointerTy(MF->getDataLayout());
31557   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
31558          "Invalid Pointer Size!");
31559 
31560   // For v = setjmp(buf), we generate
31561   //
31562   // thisMBB:
31563   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
31564   //  SjLjSetup restoreMBB
31565   //
31566   // mainMBB:
31567   //  v_main = 0
31568   //
31569   // sinkMBB:
31570   //  v = phi(main, restore)
31571   //
31572   // restoreMBB:
31573   //  if base pointer being used, load it from frame
31574   //  v_restore = 1
31575 
31576   MachineBasicBlock *thisMBB = MBB;
31577   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
31578   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
31579   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
31580   MF->insert(I, mainMBB);
31581   MF->insert(I, sinkMBB);
31582   MF->push_back(restoreMBB);
31583   restoreMBB->setHasAddressTaken();
31584 
31585   MachineInstrBuilder MIB;
31586 
31587   // Transfer the remainder of BB and its successor edges to sinkMBB.
31588   sinkMBB->splice(sinkMBB->begin(), MBB,
31589                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
31590   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
31591 
31592   // thisMBB:
31593   unsigned PtrStoreOpc = 0;
31594   unsigned LabelReg = 0;
31595   const int64_t LabelOffset = 1 * PVT.getStoreSize();
31596   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
31597                      !isPositionIndependent();
31598 
31599   // Prepare IP either in reg or imm.
31600   if (!UseImmLabel) {
31601     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
31602     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
31603     LabelReg = MRI.createVirtualRegister(PtrRC);
31604     if (Subtarget.is64Bit()) {
31605       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
31606               .addReg(X86::RIP)
31607               .addImm(0)
31608               .addReg(0)
31609               .addMBB(restoreMBB)
31610               .addReg(0);
31611     } else {
31612       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
31613       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
31614               .addReg(XII->getGlobalBaseReg(MF))
31615               .addImm(0)
31616               .addReg(0)
31617               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
31618               .addReg(0);
31619     }
31620   } else
31621     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
31622   // Store IP
31623   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
31624   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31625     if (i == X86::AddrDisp)
31626       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
31627     else
31628       MIB.add(MI.getOperand(MemOpndSlot + i));
31629   }
31630   if (!UseImmLabel)
31631     MIB.addReg(LabelReg);
31632   else
31633     MIB.addMBB(restoreMBB);
31634   MIB.setMemRefs(MMOs);
31635 
31636   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
31637     emitSetJmpShadowStackFix(MI, thisMBB);
31638   }
31639 
31640   // Setup
31641   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
31642           .addMBB(restoreMBB);
31643 
31644   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
31645   MIB.addRegMask(RegInfo->getNoPreservedMask());
31646   thisMBB->addSuccessor(mainMBB);
31647   thisMBB->addSuccessor(restoreMBB);
31648 
31649   // mainMBB:
31650   //  EAX = 0
31651   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
31652   mainMBB->addSuccessor(sinkMBB);
31653 
31654   // sinkMBB:
31655   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
31656           TII->get(X86::PHI), DstReg)
31657     .addReg(mainDstReg).addMBB(mainMBB)
31658     .addReg(restoreDstReg).addMBB(restoreMBB);
31659 
31660   // restoreMBB:
31661   if (RegInfo->hasBasePointer(*MF)) {
31662     const bool Uses64BitFramePtr =
31663         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
31664     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
31665     X86FI->setRestoreBasePointer(MF);
31666     Register FramePtr = RegInfo->getFrameRegister(*MF);
31667     Register BasePtr = RegInfo->getBaseRegister();
31668     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
31669     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
31670                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
31671       .setMIFlag(MachineInstr::FrameSetup);
31672   }
31673   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
31674   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
31675   restoreMBB->addSuccessor(sinkMBB);
31676 
31677   MI.eraseFromParent();
31678   return sinkMBB;
31679 }
31680 
31681 /// Fix the shadow stack using the previously saved SSP pointer.
31682 /// \sa emitSetJmpShadowStackFix
31683 /// \param [in] MI The temporary Machine Instruction for the builtin.
31684 /// \param [in] MBB The Machine Basic Block that will be modified.
31685 /// \return The sink MBB that will perform the future indirect branch.
31686 MachineBasicBlock *
emitLongJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const31687 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
31688                                              MachineBasicBlock *MBB) const {
31689   DebugLoc DL = MI.getDebugLoc();
31690   MachineFunction *MF = MBB->getParent();
31691   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31692   MachineRegisterInfo &MRI = MF->getRegInfo();
31693 
31694   // Memory Reference
31695   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
31696                                            MI.memoperands_end());
31697 
31698   MVT PVT = getPointerTy(MF->getDataLayout());
31699   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
31700 
31701   // checkSspMBB:
31702   //         xor vreg1, vreg1
31703   //         rdssp vreg1
31704   //         test vreg1, vreg1
31705   //         je sinkMBB   # Jump if Shadow Stack is not supported
31706   // fallMBB:
31707   //         mov buf+24/12(%rip), vreg2
31708   //         sub vreg1, vreg2
31709   //         jbe sinkMBB  # No need to fix the Shadow Stack
31710   // fixShadowMBB:
31711   //         shr 3/2, vreg2
31712   //         incssp vreg2  # fix the SSP according to the lower 8 bits
31713   //         shr 8, vreg2
31714   //         je sinkMBB
31715   // fixShadowLoopPrepareMBB:
31716   //         shl vreg2
31717   //         mov 128, vreg3
31718   // fixShadowLoopMBB:
31719   //         incssp vreg3
31720   //         dec vreg2
31721   //         jne fixShadowLoopMBB # Iterate until you finish fixing
31722   //                              # the Shadow Stack
31723   // sinkMBB:
31724 
31725   MachineFunction::iterator I = ++MBB->getIterator();
31726   const BasicBlock *BB = MBB->getBasicBlock();
31727 
31728   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
31729   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
31730   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
31731   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
31732   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
31733   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
31734   MF->insert(I, checkSspMBB);
31735   MF->insert(I, fallMBB);
31736   MF->insert(I, fixShadowMBB);
31737   MF->insert(I, fixShadowLoopPrepareMBB);
31738   MF->insert(I, fixShadowLoopMBB);
31739   MF->insert(I, sinkMBB);
31740 
31741   // Transfer the remainder of BB and its successor edges to sinkMBB.
31742   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
31743                   MBB->end());
31744   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
31745 
31746   MBB->addSuccessor(checkSspMBB);
31747 
31748   // Initialize a register with zero.
31749   Register ZReg = MRI.createVirtualRegister(PtrRC);
31750   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
31751   BuildMI(checkSspMBB, DL, TII->get(XorRROpc))
31752       .addDef(ZReg)
31753       .addReg(ZReg, RegState::Undef)
31754       .addReg(ZReg, RegState::Undef);
31755 
31756   // Read the current SSP Register value to the zeroed register.
31757   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
31758   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
31759   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
31760 
31761   // Check whether the result of the SSP register is zero and jump directly
31762   // to the sink.
31763   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
31764   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
31765       .addReg(SSPCopyReg)
31766       .addReg(SSPCopyReg);
31767   BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
31768   checkSspMBB->addSuccessor(sinkMBB);
31769   checkSspMBB->addSuccessor(fallMBB);
31770 
31771   // Reload the previously saved SSP register value.
31772   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
31773   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
31774   const int64_t SPPOffset = 3 * PVT.getStoreSize();
31775   MachineInstrBuilder MIB =
31776       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
31777   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31778     const MachineOperand &MO = MI.getOperand(i);
31779     if (i == X86::AddrDisp)
31780       MIB.addDisp(MO, SPPOffset);
31781     else if (MO.isReg()) // Don't add the whole operand, we don't want to
31782                          // preserve kill flags.
31783       MIB.addReg(MO.getReg());
31784     else
31785       MIB.add(MO);
31786   }
31787   MIB.setMemRefs(MMOs);
31788 
31789   // Subtract the current SSP from the previous SSP.
31790   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
31791   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
31792   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
31793       .addReg(PrevSSPReg)
31794       .addReg(SSPCopyReg);
31795 
31796   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
31797   BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
31798   fallMBB->addSuccessor(sinkMBB);
31799   fallMBB->addSuccessor(fixShadowMBB);
31800 
31801   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
31802   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
31803   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
31804   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
31805   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
31806       .addReg(SspSubReg)
31807       .addImm(Offset);
31808 
31809   // Increase SSP when looking only on the lower 8 bits of the delta.
31810   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
31811   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
31812 
31813   // Reset the lower 8 bits.
31814   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
31815   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
31816       .addReg(SspFirstShrReg)
31817       .addImm(8);
31818 
31819   // Jump if the result of the shift is zero.
31820   BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
31821   fixShadowMBB->addSuccessor(sinkMBB);
31822   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
31823 
31824   // Do a single shift left.
31825   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
31826   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
31827   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
31828       .addReg(SspSecondShrReg);
31829 
31830   // Save the value 128 to a register (will be used next with incssp).
31831   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
31832   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
31833   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
31834       .addImm(128);
31835   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
31836 
31837   // Since incssp only looks at the lower 8 bits, we might need to do several
31838   // iterations of incssp until we finish fixing the shadow stack.
31839   Register DecReg = MRI.createVirtualRegister(PtrRC);
31840   Register CounterReg = MRI.createVirtualRegister(PtrRC);
31841   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
31842       .addReg(SspAfterShlReg)
31843       .addMBB(fixShadowLoopPrepareMBB)
31844       .addReg(DecReg)
31845       .addMBB(fixShadowLoopMBB);
31846 
31847   // Every iteration we increase the SSP by 128.
31848   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
31849 
31850   // Every iteration we decrement the counter by 1.
31851   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
31852   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
31853 
31854   // Jump if the counter is not zero yet.
31855   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
31856   fixShadowLoopMBB->addSuccessor(sinkMBB);
31857   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
31858 
31859   return sinkMBB;
31860 }
31861 
31862 MachineBasicBlock *
emitEHSjLjLongJmp(MachineInstr & MI,MachineBasicBlock * MBB) const31863 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
31864                                      MachineBasicBlock *MBB) const {
31865   DebugLoc DL = MI.getDebugLoc();
31866   MachineFunction *MF = MBB->getParent();
31867   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31868   MachineRegisterInfo &MRI = MF->getRegInfo();
31869 
31870   // Memory Reference
31871   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
31872                                            MI.memoperands_end());
31873 
31874   MVT PVT = getPointerTy(MF->getDataLayout());
31875   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
31876          "Invalid Pointer Size!");
31877 
31878   const TargetRegisterClass *RC =
31879     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
31880   Register Tmp = MRI.createVirtualRegister(RC);
31881   // Since FP is only updated here but NOT referenced, it's treated as GPR.
31882   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
31883   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
31884   Register SP = RegInfo->getStackRegister();
31885 
31886   MachineInstrBuilder MIB;
31887 
31888   const int64_t LabelOffset = 1 * PVT.getStoreSize();
31889   const int64_t SPOffset = 2 * PVT.getStoreSize();
31890 
31891   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
31892   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
31893 
31894   MachineBasicBlock *thisMBB = MBB;
31895 
31896   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
31897   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
31898     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
31899   }
31900 
31901   // Reload FP
31902   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
31903   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31904     const MachineOperand &MO = MI.getOperand(i);
31905     if (MO.isReg()) // Don't add the whole operand, we don't want to
31906                     // preserve kill flags.
31907       MIB.addReg(MO.getReg());
31908     else
31909       MIB.add(MO);
31910   }
31911   MIB.setMemRefs(MMOs);
31912 
31913   // Reload IP
31914   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
31915   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31916     const MachineOperand &MO = MI.getOperand(i);
31917     if (i == X86::AddrDisp)
31918       MIB.addDisp(MO, LabelOffset);
31919     else if (MO.isReg()) // Don't add the whole operand, we don't want to
31920                          // preserve kill flags.
31921       MIB.addReg(MO.getReg());
31922     else
31923       MIB.add(MO);
31924   }
31925   MIB.setMemRefs(MMOs);
31926 
31927   // Reload SP
31928   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
31929   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
31930     if (i == X86::AddrDisp)
31931       MIB.addDisp(MI.getOperand(i), SPOffset);
31932     else
31933       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
31934                                  // the last instruction of the expansion.
31935   }
31936   MIB.setMemRefs(MMOs);
31937 
31938   // Jump
31939   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
31940 
31941   MI.eraseFromParent();
31942   return thisMBB;
31943 }
31944 
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const31945 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
31946                                                MachineBasicBlock *MBB,
31947                                                MachineBasicBlock *DispatchBB,
31948                                                int FI) const {
31949   DebugLoc DL = MI.getDebugLoc();
31950   MachineFunction *MF = MBB->getParent();
31951   MachineRegisterInfo *MRI = &MF->getRegInfo();
31952   const X86InstrInfo *TII = Subtarget.getInstrInfo();
31953 
31954   MVT PVT = getPointerTy(MF->getDataLayout());
31955   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
31956 
31957   unsigned Op = 0;
31958   unsigned VR = 0;
31959 
31960   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
31961                      !isPositionIndependent();
31962 
31963   if (UseImmLabel) {
31964     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
31965   } else {
31966     const TargetRegisterClass *TRC =
31967         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
31968     VR = MRI->createVirtualRegister(TRC);
31969     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
31970 
31971     if (Subtarget.is64Bit())
31972       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
31973           .addReg(X86::RIP)
31974           .addImm(1)
31975           .addReg(0)
31976           .addMBB(DispatchBB)
31977           .addReg(0);
31978     else
31979       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
31980           .addReg(0) /* TII->getGlobalBaseReg(MF) */
31981           .addImm(1)
31982           .addReg(0)
31983           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
31984           .addReg(0);
31985   }
31986 
31987   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
31988   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
31989   if (UseImmLabel)
31990     MIB.addMBB(DispatchBB);
31991   else
31992     MIB.addReg(VR);
31993 }
31994 
31995 MachineBasicBlock *
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * BB) const31996 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
31997                                          MachineBasicBlock *BB) const {
31998   DebugLoc DL = MI.getDebugLoc();
31999   MachineFunction *MF = BB->getParent();
32000   MachineRegisterInfo *MRI = &MF->getRegInfo();
32001   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32002   int FI = MF->getFrameInfo().getFunctionContextIndex();
32003 
32004   // Get a mapping of the call site numbers to all of the landing pads they're
32005   // associated with.
32006   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
32007   unsigned MaxCSNum = 0;
32008   for (auto &MBB : *MF) {
32009     if (!MBB.isEHPad())
32010       continue;
32011 
32012     MCSymbol *Sym = nullptr;
32013     for (const auto &MI : MBB) {
32014       if (MI.isDebugInstr())
32015         continue;
32016 
32017       assert(MI.isEHLabel() && "expected EH_LABEL");
32018       Sym = MI.getOperand(0).getMCSymbol();
32019       break;
32020     }
32021 
32022     if (!MF->hasCallSiteLandingPad(Sym))
32023       continue;
32024 
32025     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
32026       CallSiteNumToLPad[CSI].push_back(&MBB);
32027       MaxCSNum = std::max(MaxCSNum, CSI);
32028     }
32029   }
32030 
32031   // Get an ordered list of the machine basic blocks for the jump table.
32032   std::vector<MachineBasicBlock *> LPadList;
32033   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
32034   LPadList.reserve(CallSiteNumToLPad.size());
32035 
32036   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
32037     for (auto &LP : CallSiteNumToLPad[CSI]) {
32038       LPadList.push_back(LP);
32039       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
32040     }
32041   }
32042 
32043   assert(!LPadList.empty() &&
32044          "No landing pad destinations for the dispatch jump table!");
32045 
32046   // Create the MBBs for the dispatch code.
32047 
32048   // Shove the dispatch's address into the return slot in the function context.
32049   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
32050   DispatchBB->setIsEHPad(true);
32051 
32052   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
32053   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
32054   DispatchBB->addSuccessor(TrapBB);
32055 
32056   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
32057   DispatchBB->addSuccessor(DispContBB);
32058 
32059   // Insert MBBs.
32060   MF->push_back(DispatchBB);
32061   MF->push_back(DispContBB);
32062   MF->push_back(TrapBB);
32063 
32064   // Insert code into the entry block that creates and registers the function
32065   // context.
32066   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
32067 
32068   // Create the jump table and associated information
32069   unsigned JTE = getJumpTableEncoding();
32070   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
32071   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
32072 
32073   const X86RegisterInfo &RI = TII->getRegisterInfo();
32074   // Add a register mask with no preserved registers.  This results in all
32075   // registers being marked as clobbered.
32076   if (RI.hasBasePointer(*MF)) {
32077     const bool FPIs64Bit =
32078         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
32079     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
32080     MFI->setRestoreBasePointer(MF);
32081 
32082     Register FP = RI.getFrameRegister(*MF);
32083     Register BP = RI.getBaseRegister();
32084     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
32085     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
32086                  MFI->getRestoreBasePointerOffset())
32087         .addRegMask(RI.getNoPreservedMask());
32088   } else {
32089     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
32090         .addRegMask(RI.getNoPreservedMask());
32091   }
32092 
32093   // IReg is used as an index in a memory operand and therefore can't be SP
32094   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
32095   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
32096                     Subtarget.is64Bit() ? 8 : 4);
32097   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
32098       .addReg(IReg)
32099       .addImm(LPadList.size());
32100   BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
32101 
32102   if (Subtarget.is64Bit()) {
32103     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
32104     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
32105 
32106     // leaq .LJTI0_0(%rip), BReg
32107     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
32108         .addReg(X86::RIP)
32109         .addImm(1)
32110         .addReg(0)
32111         .addJumpTableIndex(MJTI)
32112         .addReg(0);
32113     // movzx IReg64, IReg
32114     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
32115         .addImm(0)
32116         .addReg(IReg)
32117         .addImm(X86::sub_32bit);
32118 
32119     switch (JTE) {
32120     case MachineJumpTableInfo::EK_BlockAddress:
32121       // jmpq *(BReg,IReg64,8)
32122       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
32123           .addReg(BReg)
32124           .addImm(8)
32125           .addReg(IReg64)
32126           .addImm(0)
32127           .addReg(0);
32128       break;
32129     case MachineJumpTableInfo::EK_LabelDifference32: {
32130       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
32131       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
32132       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
32133 
32134       // movl (BReg,IReg64,4), OReg
32135       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
32136           .addReg(BReg)
32137           .addImm(4)
32138           .addReg(IReg64)
32139           .addImm(0)
32140           .addReg(0);
32141       // movsx OReg64, OReg
32142       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
32143       // addq BReg, OReg64, TReg
32144       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
32145           .addReg(OReg64)
32146           .addReg(BReg);
32147       // jmpq *TReg
32148       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
32149       break;
32150     }
32151     default:
32152       llvm_unreachable("Unexpected jump table encoding");
32153     }
32154   } else {
32155     // jmpl *.LJTI0_0(,IReg,4)
32156     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
32157         .addReg(0)
32158         .addImm(4)
32159         .addReg(IReg)
32160         .addJumpTableIndex(MJTI)
32161         .addReg(0);
32162   }
32163 
32164   // Add the jump table entries as successors to the MBB.
32165   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
32166   for (auto &LP : LPadList)
32167     if (SeenMBBs.insert(LP).second)
32168       DispContBB->addSuccessor(LP);
32169 
32170   // N.B. the order the invoke BBs are processed in doesn't matter here.
32171   SmallVector<MachineBasicBlock *, 64> MBBLPads;
32172   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
32173   for (MachineBasicBlock *MBB : InvokeBBs) {
32174     // Remove the landing pad successor from the invoke block and replace it
32175     // with the new dispatch block.
32176     // Keep a copy of Successors since it's modified inside the loop.
32177     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
32178                                                    MBB->succ_rend());
32179     // FIXME: Avoid quadratic complexity.
32180     for (auto MBBS : Successors) {
32181       if (MBBS->isEHPad()) {
32182         MBB->removeSuccessor(MBBS);
32183         MBBLPads.push_back(MBBS);
32184       }
32185     }
32186 
32187     MBB->addSuccessor(DispatchBB);
32188 
32189     // Find the invoke call and mark all of the callee-saved registers as
32190     // 'implicit defined' so that they're spilled.  This prevents code from
32191     // moving instructions to before the EH block, where they will never be
32192     // executed.
32193     for (auto &II : reverse(*MBB)) {
32194       if (!II.isCall())
32195         continue;
32196 
32197       DenseMap<unsigned, bool> DefRegs;
32198       for (auto &MOp : II.operands())
32199         if (MOp.isReg())
32200           DefRegs[MOp.getReg()] = true;
32201 
32202       MachineInstrBuilder MIB(*MF, &II);
32203       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
32204         unsigned Reg = SavedRegs[RegIdx];
32205         if (!DefRegs[Reg])
32206           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
32207       }
32208 
32209       break;
32210     }
32211   }
32212 
32213   // Mark all former landing pads as non-landing pads.  The dispatch is the only
32214   // landing pad now.
32215   for (auto &LP : MBBLPads)
32216     LP->setIsEHPad(false);
32217 
32218   // The instruction is gone now.
32219   MI.eraseFromParent();
32220   return BB;
32221 }
32222 
32223 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const32224 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
32225                                                MachineBasicBlock *BB) const {
32226   MachineFunction *MF = BB->getParent();
32227   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32228   DebugLoc DL = MI.getDebugLoc();
32229 
32230   switch (MI.getOpcode()) {
32231   default: llvm_unreachable("Unexpected instr type to insert");
32232   case X86::TLS_addr32:
32233   case X86::TLS_addr64:
32234   case X86::TLS_base_addr32:
32235   case X86::TLS_base_addr64:
32236     return EmitLoweredTLSAddr(MI, BB);
32237   case X86::RETPOLINE_CALL32:
32238   case X86::RETPOLINE_CALL64:
32239   case X86::RETPOLINE_TCRETURN32:
32240   case X86::RETPOLINE_TCRETURN64:
32241     return EmitLoweredRetpoline(MI, BB);
32242   case X86::CATCHRET:
32243     return EmitLoweredCatchRet(MI, BB);
32244   case X86::CATCHPAD:
32245     return EmitLoweredCatchPad(MI, BB);
32246   case X86::SEG_ALLOCA_32:
32247   case X86::SEG_ALLOCA_64:
32248     return EmitLoweredSegAlloca(MI, BB);
32249   case X86::TLSCall_32:
32250   case X86::TLSCall_64:
32251     return EmitLoweredTLSCall(MI, BB);
32252   case X86::CMOV_FR32:
32253   case X86::CMOV_FR32X:
32254   case X86::CMOV_FR64:
32255   case X86::CMOV_FR64X:
32256   case X86::CMOV_GR8:
32257   case X86::CMOV_GR16:
32258   case X86::CMOV_GR32:
32259   case X86::CMOV_RFP32:
32260   case X86::CMOV_RFP64:
32261   case X86::CMOV_RFP80:
32262   case X86::CMOV_VR128:
32263   case X86::CMOV_VR128X:
32264   case X86::CMOV_VR256:
32265   case X86::CMOV_VR256X:
32266   case X86::CMOV_VR512:
32267   case X86::CMOV_VK2:
32268   case X86::CMOV_VK4:
32269   case X86::CMOV_VK8:
32270   case X86::CMOV_VK16:
32271   case X86::CMOV_VK32:
32272   case X86::CMOV_VK64:
32273     return EmitLoweredSelect(MI, BB);
32274 
32275   case X86::RDFLAGS32:
32276   case X86::RDFLAGS64: {
32277     unsigned PushF =
32278         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
32279     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
32280     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
32281     // Permit reads of the EFLAGS and DF registers without them being defined.
32282     // This intrinsic exists to read external processor state in flags, such as
32283     // the trap flag, interrupt flag, and direction flag, none of which are
32284     // modeled by the backend.
32285     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
32286            "Unexpected register in operand!");
32287     Push->getOperand(2).setIsUndef();
32288     assert(Push->getOperand(3).getReg() == X86::DF &&
32289            "Unexpected register in operand!");
32290     Push->getOperand(3).setIsUndef();
32291     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
32292 
32293     MI.eraseFromParent(); // The pseudo is gone now.
32294     return BB;
32295   }
32296 
32297   case X86::WRFLAGS32:
32298   case X86::WRFLAGS64: {
32299     unsigned Push =
32300         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
32301     unsigned PopF =
32302         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
32303     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
32304     BuildMI(*BB, MI, DL, TII->get(PopF));
32305 
32306     MI.eraseFromParent(); // The pseudo is gone now.
32307     return BB;
32308   }
32309 
32310   case X86::FP32_TO_INT16_IN_MEM:
32311   case X86::FP32_TO_INT32_IN_MEM:
32312   case X86::FP32_TO_INT64_IN_MEM:
32313   case X86::FP64_TO_INT16_IN_MEM:
32314   case X86::FP64_TO_INT32_IN_MEM:
32315   case X86::FP64_TO_INT64_IN_MEM:
32316   case X86::FP80_TO_INT16_IN_MEM:
32317   case X86::FP80_TO_INT32_IN_MEM:
32318   case X86::FP80_TO_INT64_IN_MEM: {
32319     // Change the floating point control register to use "round towards zero"
32320     // mode when truncating to an integer value.
32321     int OrigCWFrameIdx = MF->getFrameInfo().CreateStackObject(2, 2, false);
32322     addFrameReference(BuildMI(*BB, MI, DL,
32323                               TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
32324 
32325     // Load the old value of the control word...
32326     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
32327     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
32328                       OrigCWFrameIdx);
32329 
32330     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
32331     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
32332     BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
32333       .addReg(OldCW, RegState::Kill).addImm(0xC00);
32334 
32335     // Extract to 16 bits.
32336     Register NewCW16 =
32337         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
32338     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
32339       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
32340 
32341     // Prepare memory for FLDCW.
32342     int NewCWFrameIdx = MF->getFrameInfo().CreateStackObject(2, 2, false);
32343     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
32344                       NewCWFrameIdx)
32345       .addReg(NewCW16, RegState::Kill);
32346 
32347     // Reload the modified control word now...
32348     addFrameReference(BuildMI(*BB, MI, DL,
32349                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
32350 
32351     // Get the X86 opcode to use.
32352     unsigned Opc;
32353     switch (MI.getOpcode()) {
32354     default: llvm_unreachable("illegal opcode!");
32355     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
32356     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
32357     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
32358     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
32359     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
32360     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
32361     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
32362     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
32363     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
32364     }
32365 
32366     X86AddressMode AM = getAddressFromInstr(&MI, 0);
32367     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
32368         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
32369 
32370     // Reload the original control word now.
32371     addFrameReference(BuildMI(*BB, MI, DL,
32372                               TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
32373 
32374     MI.eraseFromParent(); // The pseudo instruction is gone now.
32375     return BB;
32376   }
32377 
32378   // xbegin
32379   case X86::XBEGIN:
32380     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
32381 
32382   case X86::VASTART_SAVE_XMM_REGS:
32383     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
32384 
32385   case X86::VAARG_64:
32386     return EmitVAARG64WithCustomInserter(MI, BB);
32387 
32388   case X86::EH_SjLj_SetJmp32:
32389   case X86::EH_SjLj_SetJmp64:
32390     return emitEHSjLjSetJmp(MI, BB);
32391 
32392   case X86::EH_SjLj_LongJmp32:
32393   case X86::EH_SjLj_LongJmp64:
32394     return emitEHSjLjLongJmp(MI, BB);
32395 
32396   case X86::Int_eh_sjlj_setup_dispatch:
32397     return EmitSjLjDispatchBlock(MI, BB);
32398 
32399   case TargetOpcode::STATEPOINT:
32400     // As an implementation detail, STATEPOINT shares the STACKMAP format at
32401     // this point in the process.  We diverge later.
32402     return emitPatchPoint(MI, BB);
32403 
32404   case TargetOpcode::STACKMAP:
32405   case TargetOpcode::PATCHPOINT:
32406     return emitPatchPoint(MI, BB);
32407 
32408   case TargetOpcode::PATCHABLE_EVENT_CALL:
32409     return emitXRayCustomEvent(MI, BB);
32410 
32411   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
32412     return emitXRayTypedEvent(MI, BB);
32413 
32414   case X86::LCMPXCHG8B: {
32415     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
32416     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
32417     // requires a memory operand. If it happens that current architecture is
32418     // i686 and for current function we need a base pointer
32419     // - which is ESI for i686 - register allocator would not be able to
32420     // allocate registers for an address in form of X(%reg, %reg, Y)
32421     // - there never would be enough unreserved registers during regalloc
32422     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
32423     // We are giving a hand to register allocator by precomputing the address in
32424     // a new vreg using LEA.
32425 
32426     // If it is not i686 or there is no base pointer - nothing to do here.
32427     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
32428       return BB;
32429 
32430     // Even though this code does not necessarily needs the base pointer to
32431     // be ESI, we check for that. The reason: if this assert fails, there are
32432     // some changes happened in the compiler base pointer handling, which most
32433     // probably have to be addressed somehow here.
32434     assert(TRI->getBaseRegister() == X86::ESI &&
32435            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
32436            "base pointer in mind");
32437 
32438     MachineRegisterInfo &MRI = MF->getRegInfo();
32439     MVT SPTy = getPointerTy(MF->getDataLayout());
32440     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
32441     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
32442 
32443     X86AddressMode AM = getAddressFromInstr(&MI, 0);
32444     // Regalloc does not need any help when the memory operand of CMPXCHG8B
32445     // does not use index register.
32446     if (AM.IndexReg == X86::NoRegister)
32447       return BB;
32448 
32449     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
32450     // four operand definitions that are E[ABCD] registers. We skip them and
32451     // then insert the LEA.
32452     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
32453     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
32454                                    RMBBI->definesRegister(X86::EBX) ||
32455                                    RMBBI->definesRegister(X86::ECX) ||
32456                                    RMBBI->definesRegister(X86::EDX))) {
32457       ++RMBBI;
32458     }
32459     MachineBasicBlock::iterator MBBI(RMBBI);
32460     addFullAddress(
32461         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
32462 
32463     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
32464 
32465     return BB;
32466   }
32467   case X86::LCMPXCHG16B:
32468     return BB;
32469   case X86::LCMPXCHG8B_SAVE_EBX:
32470   case X86::LCMPXCHG16B_SAVE_RBX: {
32471     unsigned BasePtr =
32472         MI.getOpcode() == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
32473     if (!BB->isLiveIn(BasePtr))
32474       BB->addLiveIn(BasePtr);
32475     return BB;
32476   }
32477   }
32478 }
32479 
32480 //===----------------------------------------------------------------------===//
32481 //                           X86 Optimization Hooks
32482 //===----------------------------------------------------------------------===//
32483 
32484 bool
targetShrinkDemandedConstant(SDValue Op,const APInt & Demanded,TargetLoweringOpt & TLO) const32485 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
32486                                                 const APInt &Demanded,
32487                                                 TargetLoweringOpt &TLO) const {
32488   // Only optimize Ands to prevent shrinking a constant that could be
32489   // matched by movzx.
32490   if (Op.getOpcode() != ISD::AND)
32491     return false;
32492 
32493   EVT VT = Op.getValueType();
32494 
32495   // Ignore vectors.
32496   if (VT.isVector())
32497     return false;
32498 
32499   unsigned Size = VT.getSizeInBits();
32500 
32501   // Make sure the RHS really is a constant.
32502   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
32503   if (!C)
32504     return false;
32505 
32506   const APInt &Mask = C->getAPIntValue();
32507 
32508   // Clear all non-demanded bits initially.
32509   APInt ShrunkMask = Mask & Demanded;
32510 
32511   // Find the width of the shrunk mask.
32512   unsigned Width = ShrunkMask.getActiveBits();
32513 
32514   // If the mask is all 0s there's nothing to do here.
32515   if (Width == 0)
32516     return false;
32517 
32518   // Find the next power of 2 width, rounding up to a byte.
32519   Width = PowerOf2Ceil(std::max(Width, 8U));
32520   // Truncate the width to size to handle illegal types.
32521   Width = std::min(Width, Size);
32522 
32523   // Calculate a possible zero extend mask for this constant.
32524   APInt ZeroExtendMask = APInt::getLowBitsSet(Size, Width);
32525 
32526   // If we aren't changing the mask, just return true to keep it and prevent
32527   // the caller from optimizing.
32528   if (ZeroExtendMask == Mask)
32529     return true;
32530 
32531   // Make sure the new mask can be represented by a combination of mask bits
32532   // and non-demanded bits.
32533   if (!ZeroExtendMask.isSubsetOf(Mask | ~Demanded))
32534     return false;
32535 
32536   // Replace the constant with the zero extend mask.
32537   SDLoc DL(Op);
32538   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
32539   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
32540   return TLO.CombineTo(Op, NewOp);
32541 }
32542 
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const32543 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
32544                                                       KnownBits &Known,
32545                                                       const APInt &DemandedElts,
32546                                                       const SelectionDAG &DAG,
32547                                                       unsigned Depth) const {
32548   unsigned BitWidth = Known.getBitWidth();
32549   unsigned Opc = Op.getOpcode();
32550   EVT VT = Op.getValueType();
32551   assert((Opc >= ISD::BUILTIN_OP_END ||
32552           Opc == ISD::INTRINSIC_WO_CHAIN ||
32553           Opc == ISD::INTRINSIC_W_CHAIN ||
32554           Opc == ISD::INTRINSIC_VOID) &&
32555          "Should use MaskedValueIsZero if you don't know whether Op"
32556          " is a target node!");
32557 
32558   Known.resetAll();
32559   switch (Opc) {
32560   default: break;
32561   case X86ISD::SETCC:
32562     Known.Zero.setBitsFrom(1);
32563     break;
32564   case X86ISD::MOVMSK: {
32565     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
32566     Known.Zero.setBitsFrom(NumLoBits);
32567     break;
32568   }
32569   case X86ISD::PEXTRB:
32570   case X86ISD::PEXTRW: {
32571     SDValue Src = Op.getOperand(0);
32572     EVT SrcVT = Src.getValueType();
32573     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
32574                                             Op.getConstantOperandVal(1));
32575     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
32576     Known = Known.zextOrTrunc(BitWidth, false);
32577     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
32578     break;
32579   }
32580   case X86ISD::VSRAI:
32581   case X86ISD::VSHLI:
32582   case X86ISD::VSRLI: {
32583     unsigned ShAmt = Op.getConstantOperandVal(1);
32584     if (ShAmt >= VT.getScalarSizeInBits()) {
32585       Known.setAllZero();
32586       break;
32587     }
32588 
32589     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
32590     if (Opc == X86ISD::VSHLI) {
32591       Known.Zero <<= ShAmt;
32592       Known.One <<= ShAmt;
32593       // Low bits are known zero.
32594       Known.Zero.setLowBits(ShAmt);
32595     } else if (Opc == X86ISD::VSRLI) {
32596       Known.Zero.lshrInPlace(ShAmt);
32597       Known.One.lshrInPlace(ShAmt);
32598       // High bits are known zero.
32599       Known.Zero.setHighBits(ShAmt);
32600     } else {
32601       Known.Zero.ashrInPlace(ShAmt);
32602       Known.One.ashrInPlace(ShAmt);
32603     }
32604     break;
32605   }
32606   case X86ISD::PACKUS: {
32607     // PACKUS is just a truncation if the upper half is zero.
32608     APInt DemandedLHS, DemandedRHS;
32609     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
32610 
32611     Known.One = APInt::getAllOnesValue(BitWidth * 2);
32612     Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
32613 
32614     KnownBits Known2;
32615     if (!!DemandedLHS) {
32616       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
32617       Known.One &= Known2.One;
32618       Known.Zero &= Known2.Zero;
32619     }
32620     if (!!DemandedRHS) {
32621       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
32622       Known.One &= Known2.One;
32623       Known.Zero &= Known2.Zero;
32624     }
32625 
32626     if (Known.countMinLeadingZeros() < BitWidth)
32627       Known.resetAll();
32628     Known = Known.trunc(BitWidth);
32629     break;
32630   }
32631   case X86ISD::ANDNP: {
32632     KnownBits Known2;
32633     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
32634     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
32635 
32636     // ANDNP = (~X & Y);
32637     Known.One &= Known2.Zero;
32638     Known.Zero |= Known2.One;
32639     break;
32640   }
32641   case X86ISD::FOR: {
32642     KnownBits Known2;
32643     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
32644     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
32645 
32646     // Output known-0 bits are only known if clear in both the LHS & RHS.
32647     Known.Zero &= Known2.Zero;
32648     // Output known-1 are known to be set if set in either the LHS | RHS.
32649     Known.One |= Known2.One;
32650     break;
32651   }
32652   case X86ISD::PSADBW: {
32653     assert(VT.getScalarType() == MVT::i64 &&
32654            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
32655            "Unexpected PSADBW types");
32656 
32657     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
32658     Known.Zero.setBitsFrom(16);
32659     break;
32660   }
32661   case X86ISD::CMOV: {
32662     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
32663     // If we don't know any bits, early out.
32664     if (Known.isUnknown())
32665       break;
32666     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
32667 
32668     // Only known if known in both the LHS and RHS.
32669     Known.One &= Known2.One;
32670     Known.Zero &= Known2.Zero;
32671     break;
32672   }
32673   }
32674 
32675   // Handle target shuffles.
32676   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
32677   if (isTargetShuffle(Opc)) {
32678     bool IsUnary;
32679     SmallVector<int, 64> Mask;
32680     SmallVector<SDValue, 2> Ops;
32681     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
32682                              IsUnary)) {
32683       unsigned NumOps = Ops.size();
32684       unsigned NumElts = VT.getVectorNumElements();
32685       if (Mask.size() == NumElts) {
32686         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
32687         Known.Zero.setAllBits(); Known.One.setAllBits();
32688         for (unsigned i = 0; i != NumElts; ++i) {
32689           if (!DemandedElts[i])
32690             continue;
32691           int M = Mask[i];
32692           if (M == SM_SentinelUndef) {
32693             // For UNDEF elements, we don't know anything about the common state
32694             // of the shuffle result.
32695             Known.resetAll();
32696             break;
32697           } else if (M == SM_SentinelZero) {
32698             Known.One.clearAllBits();
32699             continue;
32700           }
32701           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
32702                  "Shuffle index out of range");
32703 
32704           unsigned OpIdx = (unsigned)M / NumElts;
32705           unsigned EltIdx = (unsigned)M % NumElts;
32706           if (Ops[OpIdx].getValueType() != VT) {
32707             // TODO - handle target shuffle ops with different value types.
32708             Known.resetAll();
32709             break;
32710           }
32711           DemandedOps[OpIdx].setBit(EltIdx);
32712         }
32713         // Known bits are the values that are shared by every demanded element.
32714         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
32715           if (!DemandedOps[i])
32716             continue;
32717           KnownBits Known2 =
32718               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
32719           Known.One &= Known2.One;
32720           Known.Zero &= Known2.Zero;
32721         }
32722       }
32723     }
32724   }
32725 }
32726 
ComputeNumSignBitsForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const32727 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
32728     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
32729     unsigned Depth) const {
32730   EVT VT = Op.getValueType();
32731   unsigned VTBits = VT.getScalarSizeInBits();
32732   unsigned Opcode = Op.getOpcode();
32733   switch (Opcode) {
32734   case X86ISD::SETCC_CARRY:
32735     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
32736     return VTBits;
32737 
32738   case X86ISD::VTRUNC: {
32739     // TODO: Add DemandedElts support.
32740     SDValue Src = Op.getOperand(0);
32741     unsigned NumSrcBits = Src.getScalarValueSizeInBits();
32742     assert(VTBits < NumSrcBits && "Illegal truncation input type");
32743     unsigned Tmp = DAG.ComputeNumSignBits(Src, Depth + 1);
32744     if (Tmp > (NumSrcBits - VTBits))
32745       return Tmp - (NumSrcBits - VTBits);
32746     return 1;
32747   }
32748 
32749   case X86ISD::PACKSS: {
32750     // PACKSS is just a truncation if the sign bits extend to the packed size.
32751     APInt DemandedLHS, DemandedRHS;
32752     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
32753                         DemandedRHS);
32754 
32755     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
32756     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
32757     if (!!DemandedLHS)
32758       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
32759     if (!!DemandedRHS)
32760       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
32761     unsigned Tmp = std::min(Tmp0, Tmp1);
32762     if (Tmp > (SrcBits - VTBits))
32763       return Tmp - (SrcBits - VTBits);
32764     return 1;
32765   }
32766 
32767   case X86ISD::VSHLI: {
32768     SDValue Src = Op.getOperand(0);
32769     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
32770     if (ShiftVal.uge(VTBits))
32771       return VTBits; // Shifted all bits out --> zero.
32772     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
32773     if (ShiftVal.uge(Tmp))
32774       return 1; // Shifted all sign bits out --> unknown.
32775     return Tmp - ShiftVal.getZExtValue();
32776   }
32777 
32778   case X86ISD::VSRAI: {
32779     SDValue Src = Op.getOperand(0);
32780     APInt ShiftVal = Op.getConstantOperandAPInt(1);
32781     if (ShiftVal.uge(VTBits - 1))
32782       return VTBits; // Sign splat.
32783     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
32784     ShiftVal += Tmp;
32785     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
32786   }
32787 
32788   case X86ISD::PCMPGT:
32789   case X86ISD::PCMPEQ:
32790   case X86ISD::CMPP:
32791   case X86ISD::VPCOM:
32792   case X86ISD::VPCOMU:
32793     // Vector compares return zero/all-bits result values.
32794     return VTBits;
32795 
32796   case X86ISD::ANDNP: {
32797     unsigned Tmp0 =
32798         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
32799     if (Tmp0 == 1) return 1; // Early out.
32800     unsigned Tmp1 =
32801         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
32802     return std::min(Tmp0, Tmp1);
32803   }
32804 
32805   case X86ISD::CMOV: {
32806     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
32807     if (Tmp0 == 1) return 1;  // Early out.
32808     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
32809     return std::min(Tmp0, Tmp1);
32810   }
32811   }
32812 
32813   // Handle target shuffles.
32814   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
32815   if (isTargetShuffle(Opcode)) {
32816     bool IsUnary;
32817     SmallVector<int, 64> Mask;
32818     SmallVector<SDValue, 2> Ops;
32819     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
32820                              IsUnary)) {
32821       unsigned NumOps = Ops.size();
32822       unsigned NumElts = VT.getVectorNumElements();
32823       if (Mask.size() == NumElts) {
32824         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
32825         for (unsigned i = 0; i != NumElts; ++i) {
32826           if (!DemandedElts[i])
32827             continue;
32828           int M = Mask[i];
32829           if (M == SM_SentinelUndef) {
32830             // For UNDEF elements, we don't know anything about the common state
32831             // of the shuffle result.
32832             return 1;
32833           } else if (M == SM_SentinelZero) {
32834             // Zero = all sign bits.
32835             continue;
32836           }
32837           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
32838                  "Shuffle index out of range");
32839 
32840           unsigned OpIdx = (unsigned)M / NumElts;
32841           unsigned EltIdx = (unsigned)M % NumElts;
32842           if (Ops[OpIdx].getValueType() != VT) {
32843             // TODO - handle target shuffle ops with different value types.
32844             return 1;
32845           }
32846           DemandedOps[OpIdx].setBit(EltIdx);
32847         }
32848         unsigned Tmp0 = VTBits;
32849         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
32850           if (!DemandedOps[i])
32851             continue;
32852           unsigned Tmp1 =
32853               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
32854           Tmp0 = std::min(Tmp0, Tmp1);
32855         }
32856         return Tmp0;
32857       }
32858     }
32859   }
32860 
32861   // Fallback case.
32862   return 1;
32863 }
32864 
unwrapAddress(SDValue N) const32865 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
32866   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
32867     return N->getOperand(0);
32868   return N;
32869 }
32870 
32871 // Attempt to match a combined shuffle mask against supported unary shuffle
32872 // instructions.
32873 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT)32874 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
32875                               bool AllowFloatDomain, bool AllowIntDomain,
32876                               SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
32877                               const X86Subtarget &Subtarget, unsigned &Shuffle,
32878                               MVT &SrcVT, MVT &DstVT) {
32879   unsigned NumMaskElts = Mask.size();
32880   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
32881 
32882   // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
32883   if (MaskEltSize == 32 && isUndefOrEqual(Mask[0], 0) &&
32884       isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
32885     Shuffle = X86ISD::VZEXT_MOVL;
32886     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
32887     return true;
32888   }
32889 
32890   // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
32891   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
32892   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
32893                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
32894     unsigned MaxScale = 64 / MaskEltSize;
32895     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
32896       bool MatchAny = true;
32897       bool MatchZero = true;
32898       unsigned NumDstElts = NumMaskElts / Scale;
32899       for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
32900         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
32901           MatchAny = MatchZero = false;
32902           break;
32903         }
32904         MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
32905         MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
32906       }
32907       if (MatchAny || MatchZero) {
32908         assert(MatchZero && "Failed to match zext but matched aext?");
32909         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
32910         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
32911                                             MVT::getIntegerVT(MaskEltSize);
32912         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
32913 
32914         if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
32915           V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
32916 
32917         Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
32918         if (SrcVT.getVectorNumElements() != NumDstElts)
32919           Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
32920 
32921         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
32922         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
32923         return true;
32924       }
32925     }
32926   }
32927 
32928   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
32929   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
32930       isUndefOrEqual(Mask[0], 0) &&
32931       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
32932     Shuffle = X86ISD::VZEXT_MOVL;
32933     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
32934     return true;
32935   }
32936 
32937   // Check if we have SSE3 which will let us use MOVDDUP etc. The
32938   // instructions are no slower than UNPCKLPD but has the option to
32939   // fold the input operand into even an unaligned memory load.
32940   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
32941     if (isTargetShuffleEquivalent(Mask, {0, 0})) {
32942       Shuffle = X86ISD::MOVDDUP;
32943       SrcVT = DstVT = MVT::v2f64;
32944       return true;
32945     }
32946     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
32947       Shuffle = X86ISD::MOVSLDUP;
32948       SrcVT = DstVT = MVT::v4f32;
32949       return true;
32950     }
32951     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3})) {
32952       Shuffle = X86ISD::MOVSHDUP;
32953       SrcVT = DstVT = MVT::v4f32;
32954       return true;
32955     }
32956   }
32957 
32958   if (MaskVT.is256BitVector() && AllowFloatDomain) {
32959     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
32960     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
32961       Shuffle = X86ISD::MOVDDUP;
32962       SrcVT = DstVT = MVT::v4f64;
32963       return true;
32964     }
32965     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
32966       Shuffle = X86ISD::MOVSLDUP;
32967       SrcVT = DstVT = MVT::v8f32;
32968       return true;
32969     }
32970     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3, 5, 5, 7, 7})) {
32971       Shuffle = X86ISD::MOVSHDUP;
32972       SrcVT = DstVT = MVT::v8f32;
32973       return true;
32974     }
32975   }
32976 
32977   if (MaskVT.is512BitVector() && AllowFloatDomain) {
32978     assert(Subtarget.hasAVX512() &&
32979            "AVX512 required for 512-bit vector shuffles");
32980     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
32981       Shuffle = X86ISD::MOVDDUP;
32982       SrcVT = DstVT = MVT::v8f64;
32983       return true;
32984     }
32985     if (isTargetShuffleEquivalent(
32986             Mask, {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14})) {
32987       Shuffle = X86ISD::MOVSLDUP;
32988       SrcVT = DstVT = MVT::v16f32;
32989       return true;
32990     }
32991     if (isTargetShuffleEquivalent(
32992             Mask, {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15})) {
32993       Shuffle = X86ISD::MOVSHDUP;
32994       SrcVT = DstVT = MVT::v16f32;
32995       return true;
32996     }
32997   }
32998 
32999   return false;
33000 }
33001 
33002 // Attempt to match a combined shuffle mask against supported unary immediate
33003 // permute instructions.
33004 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryPermuteShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)33005 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
33006                                      const APInt &Zeroable,
33007                                      bool AllowFloatDomain, bool AllowIntDomain,
33008                                      const X86Subtarget &Subtarget,
33009                                      unsigned &Shuffle, MVT &ShuffleVT,
33010                                      unsigned &PermuteImm) {
33011   unsigned NumMaskElts = Mask.size();
33012   unsigned InputSizeInBits = MaskVT.getSizeInBits();
33013   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
33014   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
33015 
33016   bool ContainsZeros =
33017       llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
33018 
33019   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
33020   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
33021     // Check for lane crossing permutes.
33022     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
33023       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
33024       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
33025         Shuffle = X86ISD::VPERMI;
33026         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
33027         PermuteImm = getV4X86ShuffleImm(Mask);
33028         return true;
33029       }
33030       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
33031         SmallVector<int, 4> RepeatedMask;
33032         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
33033           Shuffle = X86ISD::VPERMI;
33034           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
33035           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
33036           return true;
33037         }
33038       }
33039     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
33040       // VPERMILPD can permute with a non-repeating shuffle.
33041       Shuffle = X86ISD::VPERMILPI;
33042       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
33043       PermuteImm = 0;
33044       for (int i = 0, e = Mask.size(); i != e; ++i) {
33045         int M = Mask[i];
33046         if (M == SM_SentinelUndef)
33047           continue;
33048         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
33049         PermuteImm |= (M & 1) << i;
33050       }
33051       return true;
33052     }
33053   }
33054 
33055   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
33056   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
33057   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
33058   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
33059       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
33060     SmallVector<int, 4> RepeatedMask;
33061     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
33062       // Narrow the repeated mask to create 32-bit element permutes.
33063       SmallVector<int, 4> WordMask = RepeatedMask;
33064       if (MaskScalarSizeInBits == 64)
33065         scaleShuffleMask<int>(2, RepeatedMask, WordMask);
33066 
33067       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
33068       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
33069       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
33070       PermuteImm = getV4X86ShuffleImm(WordMask);
33071       return true;
33072     }
33073   }
33074 
33075   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
33076   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16) {
33077     SmallVector<int, 4> RepeatedMask;
33078     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
33079       ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
33080       ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
33081 
33082       // PSHUFLW: permute lower 4 elements only.
33083       if (isUndefOrInRange(LoMask, 0, 4) &&
33084           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
33085         Shuffle = X86ISD::PSHUFLW;
33086         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
33087         PermuteImm = getV4X86ShuffleImm(LoMask);
33088         return true;
33089       }
33090 
33091       // PSHUFHW: permute upper 4 elements only.
33092       if (isUndefOrInRange(HiMask, 4, 8) &&
33093           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
33094         // Offset the HiMask so that we can create the shuffle immediate.
33095         int OffsetHiMask[4];
33096         for (int i = 0; i != 4; ++i)
33097           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
33098 
33099         Shuffle = X86ISD::PSHUFHW;
33100         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
33101         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
33102         return true;
33103       }
33104     }
33105   }
33106 
33107   // Attempt to match against byte/bit shifts.
33108   // FIXME: Add 512-bit support.
33109   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
33110                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
33111     int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
33112                                        Mask, 0, Zeroable, Subtarget);
33113     if (0 < ShiftAmt) {
33114       PermuteImm = (unsigned)ShiftAmt;
33115       return true;
33116     }
33117   }
33118 
33119   return false;
33120 }
33121 
33122 // Attempt to match a combined unary shuffle mask against supported binary
33123 // shuffle instructions.
33124 // TODO: Investigate sharing more of this with shuffle lowering.
matchBinaryShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT,bool IsUnary)33125 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
33126                                bool AllowFloatDomain, bool AllowIntDomain,
33127                                SDValue &V1, SDValue &V2, const SDLoc &DL,
33128                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
33129                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
33130                                bool IsUnary) {
33131   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
33132 
33133   if (MaskVT.is128BitVector()) {
33134     if (isTargetShuffleEquivalent(Mask, {0, 0}) && AllowFloatDomain) {
33135       V2 = V1;
33136       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
33137       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
33138       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
33139       return true;
33140     }
33141     if (isTargetShuffleEquivalent(Mask, {1, 1}) && AllowFloatDomain) {
33142       V2 = V1;
33143       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
33144       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
33145       return true;
33146     }
33147     if (isTargetShuffleEquivalent(Mask, {0, 3}) && Subtarget.hasSSE2() &&
33148         (AllowFloatDomain || !Subtarget.hasSSE41())) {
33149       std::swap(V1, V2);
33150       Shuffle = X86ISD::MOVSD;
33151       SrcVT = DstVT = MVT::v2f64;
33152       return true;
33153     }
33154     if (isTargetShuffleEquivalent(Mask, {4, 1, 2, 3}) &&
33155         (AllowFloatDomain || !Subtarget.hasSSE41())) {
33156       Shuffle = X86ISD::MOVSS;
33157       SrcVT = DstVT = MVT::v4f32;
33158       return true;
33159     }
33160   }
33161 
33162   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
33163   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
33164       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
33165       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
33166     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
33167                              Subtarget)) {
33168       DstVT = MaskVT;
33169       return true;
33170     }
33171   }
33172 
33173   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
33174   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
33175       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
33176       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
33177       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
33178       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
33179     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
33180                               Subtarget)) {
33181       SrcVT = DstVT = MaskVT;
33182       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
33183         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
33184       return true;
33185     }
33186   }
33187 
33188   return false;
33189 }
33190 
matchBinaryPermuteShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)33191 static bool matchBinaryPermuteShuffle(
33192     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
33193     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
33194     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
33195     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
33196   unsigned NumMaskElts = Mask.size();
33197   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
33198 
33199   // Attempt to match against PALIGNR byte rotate.
33200   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
33201                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
33202     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
33203     if (0 < ByteRotation) {
33204       Shuffle = X86ISD::PALIGNR;
33205       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
33206       PermuteImm = ByteRotation;
33207       return true;
33208     }
33209   }
33210 
33211   // Attempt to combine to X86ISD::BLENDI.
33212   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
33213                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
33214       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
33215     uint64_t BlendMask = 0;
33216     bool ForceV1Zero = false, ForceV2Zero = false;
33217     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
33218     if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
33219                             ForceV2Zero, BlendMask)) {
33220       if (MaskVT == MVT::v16i16) {
33221         // We can only use v16i16 PBLENDW if the lanes are repeated.
33222         SmallVector<int, 8> RepeatedMask;
33223         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
33224                                         RepeatedMask)) {
33225           assert(RepeatedMask.size() == 8 &&
33226                  "Repeated mask size doesn't match!");
33227           PermuteImm = 0;
33228           for (int i = 0; i < 8; ++i)
33229             if (RepeatedMask[i] >= 8)
33230               PermuteImm |= 1 << i;
33231           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
33232           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
33233           Shuffle = X86ISD::BLENDI;
33234           ShuffleVT = MaskVT;
33235           return true;
33236         }
33237       } else {
33238         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
33239         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
33240         PermuteImm = (unsigned)BlendMask;
33241         Shuffle = X86ISD::BLENDI;
33242         ShuffleVT = MaskVT;
33243         return true;
33244       }
33245     }
33246   }
33247 
33248   // Attempt to combine to INSERTPS, but only if it has elements that need to
33249   // be set to zero.
33250   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
33251       MaskVT.is128BitVector() &&
33252       llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; }) &&
33253       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
33254     Shuffle = X86ISD::INSERTPS;
33255     ShuffleVT = MVT::v4f32;
33256     return true;
33257   }
33258 
33259   // Attempt to combine to SHUFPD.
33260   if (AllowFloatDomain && EltSizeInBits == 64 &&
33261       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
33262        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
33263        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
33264     bool ForceV1Zero = false, ForceV2Zero = false;
33265     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
33266                                PermuteImm, Mask, Zeroable)) {
33267       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
33268       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
33269       Shuffle = X86ISD::SHUFP;
33270       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
33271       return true;
33272     }
33273   }
33274 
33275   // Attempt to combine to SHUFPS.
33276   if (AllowFloatDomain && EltSizeInBits == 32 &&
33277       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
33278        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
33279        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
33280     SmallVector<int, 4> RepeatedMask;
33281     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
33282       // Match each half of the repeated mask, to determine if its just
33283       // referencing one of the vectors, is zeroable or entirely undef.
33284       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
33285         int M0 = RepeatedMask[Offset];
33286         int M1 = RepeatedMask[Offset + 1];
33287 
33288         if (isUndefInRange(RepeatedMask, Offset, 2)) {
33289           return DAG.getUNDEF(MaskVT);
33290         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
33291           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
33292           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
33293           return getZeroVector(MaskVT, Subtarget, DAG, DL);
33294         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
33295           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
33296           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
33297           return V1;
33298         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
33299           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
33300           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
33301           return V2;
33302         }
33303 
33304         return SDValue();
33305       };
33306 
33307       int ShufMask[4] = {-1, -1, -1, -1};
33308       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
33309       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
33310 
33311       if (Lo && Hi) {
33312         V1 = Lo;
33313         V2 = Hi;
33314         Shuffle = X86ISD::SHUFP;
33315         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
33316         PermuteImm = getV4X86ShuffleImm(ShufMask);
33317         return true;
33318       }
33319     }
33320   }
33321 
33322   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
33323   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
33324       MaskVT.is128BitVector() &&
33325       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
33326     Shuffle = X86ISD::INSERTPS;
33327     ShuffleVT = MVT::v4f32;
33328     return true;
33329   }
33330 
33331   return false;
33332 }
33333 
33334 static SDValue combineX86ShuffleChainWithExtract(
33335     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
33336     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
33337     const X86Subtarget &Subtarget);
33338 
33339 /// Combine an arbitrary chain of shuffles into a single instruction if
33340 /// possible.
33341 ///
33342 /// This is the leaf of the recursive combine below. When we have found some
33343 /// chain of single-use x86 shuffle instructions and accumulated the combined
33344 /// shuffle mask represented by them, this will try to pattern match that mask
33345 /// into either a single instruction if there is a special purpose instruction
33346 /// for this operation, or into a PSHUFB instruction which is a fully general
33347 /// instruction but should only be used to replace chains over a certain depth.
combineX86ShuffleChain(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)33348 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
33349                                       ArrayRef<int> BaseMask, int Depth,
33350                                       bool HasVariableMask,
33351                                       bool AllowVariableMask, SelectionDAG &DAG,
33352                                       const X86Subtarget &Subtarget) {
33353   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
33354   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
33355          "Unexpected number of shuffle inputs!");
33356 
33357   // Find the inputs that enter the chain. Note that multiple uses are OK
33358   // here, we're not going to remove the operands we find.
33359   bool UnaryShuffle = (Inputs.size() == 1);
33360   SDValue V1 = peekThroughBitcasts(Inputs[0]);
33361   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
33362                              : peekThroughBitcasts(Inputs[1]));
33363 
33364   MVT VT1 = V1.getSimpleValueType();
33365   MVT VT2 = V2.getSimpleValueType();
33366   MVT RootVT = Root.getSimpleValueType();
33367   assert(VT1.getSizeInBits() == RootVT.getSizeInBits() &&
33368          VT2.getSizeInBits() == RootVT.getSizeInBits() &&
33369          "Vector size mismatch");
33370 
33371   SDLoc DL(Root);
33372   SDValue Res;
33373 
33374   unsigned NumBaseMaskElts = BaseMask.size();
33375   if (NumBaseMaskElts == 1) {
33376     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
33377     return DAG.getBitcast(RootVT, V1);
33378   }
33379 
33380   unsigned RootSizeInBits = RootVT.getSizeInBits();
33381   unsigned NumRootElts = RootVT.getVectorNumElements();
33382   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
33383   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
33384                      (RootVT.isFloatingPoint() && Depth >= 1) ||
33385                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
33386 
33387   // Don't combine if we are a AVX512/EVEX target and the mask element size
33388   // is different from the root element size - this would prevent writemasks
33389   // from being reused.
33390   // TODO - this currently prevents all lane shuffles from occurring.
33391   // TODO - check for writemasks usage instead of always preventing combining.
33392   // TODO - attempt to narrow Mask back to writemask size.
33393   bool IsEVEXShuffle =
33394       RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128);
33395 
33396   // Attempt to match a subvector broadcast.
33397   // shuffle(insert_subvector(undef, sub, 0), undef, 0, 0, 0, 0)
33398   if (UnaryShuffle &&
33399       (BaseMaskEltSizeInBits == 128 || BaseMaskEltSizeInBits == 256)) {
33400     SmallVector<int, 64> BroadcastMask(NumBaseMaskElts, 0);
33401     if (isTargetShuffleEquivalent(BaseMask, BroadcastMask)) {
33402       SDValue Src = Inputs[0];
33403       if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
33404           Src.getOperand(0).isUndef() &&
33405           Src.getOperand(1).getValueSizeInBits() == BaseMaskEltSizeInBits &&
33406           MayFoldLoad(Src.getOperand(1)) && isNullConstant(Src.getOperand(2))) {
33407         return DAG.getBitcast(RootVT, DAG.getNode(X86ISD::SUBV_BROADCAST, DL,
33408                                                   Src.getValueType(),
33409                                                   Src.getOperand(1)));
33410       }
33411     }
33412   }
33413 
33414   // TODO - handle 128/256-bit lane shuffles of 512-bit vectors.
33415 
33416   // Handle 128-bit lane shuffles of 256-bit vectors.
33417   // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
33418   // we need to use the zeroing feature.
33419   // TODO - this should support binary shuffles.
33420   if (UnaryShuffle && RootVT.is256BitVector() && NumBaseMaskElts == 2 &&
33421       !(Subtarget.hasAVX2() && BaseMask[0] >= -1 && BaseMask[1] >= -1) &&
33422       !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0)) {
33423     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
33424       return SDValue(); // Nothing to do!
33425     MVT ShuffleVT = (FloatDomain ? MVT::v4f64 : MVT::v4i64);
33426     unsigned PermMask = 0;
33427     PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
33428     PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
33429 
33430     Res = DAG.getBitcast(ShuffleVT, V1);
33431     Res = DAG.getNode(X86ISD::VPERM2X128, DL, ShuffleVT, Res,
33432                       DAG.getUNDEF(ShuffleVT),
33433                       DAG.getTargetConstant(PermMask, DL, MVT::i8));
33434     return DAG.getBitcast(RootVT, Res);
33435   }
33436 
33437   // For masks that have been widened to 128-bit elements or more,
33438   // narrow back down to 64-bit elements.
33439   SmallVector<int, 64> Mask;
33440   if (BaseMaskEltSizeInBits > 64) {
33441     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
33442     int MaskScale = BaseMaskEltSizeInBits / 64;
33443     scaleShuffleMask<int>(MaskScale, BaseMask, Mask);
33444   } else {
33445     Mask = SmallVector<int, 64>(BaseMask.begin(), BaseMask.end());
33446   }
33447 
33448   unsigned NumMaskElts = Mask.size();
33449   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
33450 
33451   // Determine the effective mask value type.
33452   FloatDomain &= (32 <= MaskEltSizeInBits);
33453   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
33454                            : MVT::getIntegerVT(MaskEltSizeInBits);
33455   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
33456 
33457   // Only allow legal mask types.
33458   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
33459     return SDValue();
33460 
33461   // Attempt to match the mask against known shuffle patterns.
33462   MVT ShuffleSrcVT, ShuffleVT;
33463   unsigned Shuffle, PermuteImm;
33464 
33465   // Which shuffle domains are permitted?
33466   // Permit domain crossing at higher combine depths.
33467   // TODO: Should we indicate which domain is preferred if both are allowed?
33468   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
33469   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
33470                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
33471 
33472   // Determine zeroable mask elements.
33473   APInt KnownUndef, KnownZero;
33474   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
33475   APInt Zeroable = KnownUndef | KnownZero;
33476 
33477   if (UnaryShuffle) {
33478     // If we are shuffling a X86ISD::VZEXT_LOAD then we can use the load
33479     // directly if we don't shuffle the lower element and we shuffle the upper
33480     // (zero) elements within themselves.
33481     if (V1.getOpcode() == X86ISD::VZEXT_LOAD &&
33482         (cast<MemIntrinsicSDNode>(V1)->getMemoryVT().getScalarSizeInBits() %
33483          MaskEltSizeInBits) == 0) {
33484       unsigned Scale =
33485           cast<MemIntrinsicSDNode>(V1)->getMemoryVT().getScalarSizeInBits() /
33486           MaskEltSizeInBits;
33487       ArrayRef<int> HiMask(Mask.data() + Scale, NumMaskElts - Scale);
33488       if (isSequentialOrUndefInRange(Mask, 0, Scale, 0) &&
33489           isUndefOrZeroOrInRange(HiMask, Scale, NumMaskElts)) {
33490         return DAG.getBitcast(RootVT, V1);
33491       }
33492     }
33493 
33494     // Attempt to match against broadcast-from-vector.
33495     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
33496     if ((Subtarget.hasAVX2() || (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits))
33497         && (!IsEVEXShuffle || NumRootElts == NumMaskElts)) {
33498       SmallVector<int, 64> BroadcastMask(NumMaskElts, 0);
33499       if (isTargetShuffleEquivalent(Mask, BroadcastMask)) {
33500         if (V1.getValueType() == MaskVT &&
33501             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
33502             MayFoldLoad(V1.getOperand(0))) {
33503           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
33504             return SDValue(); // Nothing to do!
33505           Res = V1.getOperand(0);
33506           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
33507           return DAG.getBitcast(RootVT, Res);
33508         }
33509         if (Subtarget.hasAVX2()) {
33510           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
33511             return SDValue(); // Nothing to do!
33512           Res = DAG.getBitcast(MaskVT, V1);
33513           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
33514           return DAG.getBitcast(RootVT, Res);
33515         }
33516       }
33517     }
33518 
33519     SDValue NewV1 = V1; // Save operand in case early exit happens.
33520     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
33521                           DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
33522                           ShuffleVT) &&
33523         (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
33524       if (Depth == 0 && Root.getOpcode() == Shuffle)
33525         return SDValue(); // Nothing to do!
33526       Res = DAG.getBitcast(ShuffleSrcVT, NewV1);
33527       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
33528       return DAG.getBitcast(RootVT, Res);
33529     }
33530 
33531     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
33532                                  AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
33533                                  PermuteImm) &&
33534         (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
33535       if (Depth == 0 && Root.getOpcode() == Shuffle)
33536         return SDValue(); // Nothing to do!
33537       Res = DAG.getBitcast(ShuffleVT, V1);
33538       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
33539                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
33540       return DAG.getBitcast(RootVT, Res);
33541     }
33542   }
33543 
33544   SDValue NewV1 = V1; // Save operands in case early exit happens.
33545   SDValue NewV2 = V2;
33546   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
33547                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
33548                          ShuffleVT, UnaryShuffle) &&
33549       (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
33550     if (Depth == 0 && Root.getOpcode() == Shuffle)
33551       return SDValue(); // Nothing to do!
33552     NewV1 = DAG.getBitcast(ShuffleSrcVT, NewV1);
33553     NewV2 = DAG.getBitcast(ShuffleSrcVT, NewV2);
33554     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
33555     return DAG.getBitcast(RootVT, Res);
33556   }
33557 
33558   NewV1 = V1; // Save operands in case early exit happens.
33559   NewV2 = V2;
33560   if (matchBinaryPermuteShuffle(
33561           MaskVT, Mask, Zeroable, AllowFloatDomain, AllowIntDomain, NewV1,
33562           NewV2, DL, DAG, Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
33563       (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
33564     if (Depth == 0 && Root.getOpcode() == Shuffle)
33565       return SDValue(); // Nothing to do!
33566     NewV1 = DAG.getBitcast(ShuffleVT, NewV1);
33567     NewV2 = DAG.getBitcast(ShuffleVT, NewV2);
33568     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
33569                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
33570     return DAG.getBitcast(RootVT, Res);
33571   }
33572 
33573   // Typically from here on, we need an integer version of MaskVT.
33574   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
33575   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
33576 
33577   // Annoyingly, SSE4A instructions don't map into the above match helpers.
33578   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
33579     uint64_t BitLen, BitIdx;
33580     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
33581                             Zeroable)) {
33582       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
33583         return SDValue(); // Nothing to do!
33584       V1 = DAG.getBitcast(IntMaskVT, V1);
33585       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
33586                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
33587                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
33588       return DAG.getBitcast(RootVT, Res);
33589     }
33590 
33591     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
33592       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
33593         return SDValue(); // Nothing to do!
33594       V1 = DAG.getBitcast(IntMaskVT, V1);
33595       V2 = DAG.getBitcast(IntMaskVT, V2);
33596       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
33597                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
33598                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
33599       return DAG.getBitcast(RootVT, Res);
33600     }
33601   }
33602 
33603   // Don't try to re-form single instruction chains under any circumstances now
33604   // that we've done encoding canonicalization for them.
33605   if (Depth < 1)
33606     return SDValue();
33607 
33608   // Depth threshold above which we can efficiently use variable mask shuffles.
33609   int VariableShuffleDepth = Subtarget.hasFastVariableShuffle() ? 1 : 2;
33610   AllowVariableMask &= (Depth >= VariableShuffleDepth) || HasVariableMask;
33611 
33612   bool MaskContainsZeros =
33613       any_of(Mask, [](int M) { return M == SM_SentinelZero; });
33614 
33615   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
33616     // If we have a single input lane-crossing shuffle then lower to VPERMV.
33617     if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
33618         ((Subtarget.hasAVX2() &&
33619           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
33620          (Subtarget.hasAVX512() &&
33621           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
33622            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
33623          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
33624          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
33625          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
33626          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
33627       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
33628       Res = DAG.getBitcast(MaskVT, V1);
33629       Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
33630       return DAG.getBitcast(RootVT, Res);
33631     }
33632 
33633     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
33634     // vector as the second source.
33635     if (UnaryShuffle && AllowVariableMask &&
33636         ((Subtarget.hasAVX512() &&
33637           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
33638            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
33639          (Subtarget.hasVLX() &&
33640           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
33641            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
33642          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
33643          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
33644          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
33645          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
33646       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
33647       for (unsigned i = 0; i != NumMaskElts; ++i)
33648         if (Mask[i] == SM_SentinelZero)
33649           Mask[i] = NumMaskElts + i;
33650 
33651       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
33652       Res = DAG.getBitcast(MaskVT, V1);
33653       SDValue Zero = getZeroVector(MaskVT, Subtarget, DAG, DL);
33654       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, Res, VPermMask, Zero);
33655       return DAG.getBitcast(RootVT, Res);
33656     }
33657 
33658     // If that failed and either input is extracted then try to combine as a
33659     // shuffle with the larger type.
33660     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
33661             Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
33662             DAG, Subtarget))
33663       return WideShuffle;
33664 
33665     // If we have a dual input lane-crossing shuffle then lower to VPERMV3.
33666     if (AllowVariableMask && !MaskContainsZeros &&
33667         ((Subtarget.hasAVX512() &&
33668           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
33669            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
33670          (Subtarget.hasVLX() &&
33671           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
33672            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
33673          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
33674          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
33675          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
33676          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
33677       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
33678       V1 = DAG.getBitcast(MaskVT, V1);
33679       V2 = DAG.getBitcast(MaskVT, V2);
33680       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
33681       return DAG.getBitcast(RootVT, Res);
33682     }
33683     return SDValue();
33684   }
33685 
33686   // See if we can combine a single input shuffle with zeros to a bit-mask,
33687   // which is much simpler than any shuffle.
33688   if (UnaryShuffle && MaskContainsZeros && AllowVariableMask &&
33689       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
33690       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
33691     APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
33692     APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
33693     APInt UndefElts(NumMaskElts, 0);
33694     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
33695     for (unsigned i = 0; i != NumMaskElts; ++i) {
33696       int M = Mask[i];
33697       if (M == SM_SentinelUndef) {
33698         UndefElts.setBit(i);
33699         continue;
33700       }
33701       if (M == SM_SentinelZero)
33702         continue;
33703       EltBits[i] = AllOnes;
33704     }
33705     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
33706     Res = DAG.getBitcast(MaskVT, V1);
33707     unsigned AndOpcode =
33708         FloatDomain ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
33709     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
33710     return DAG.getBitcast(RootVT, Res);
33711   }
33712 
33713   // If we have a single input shuffle with different shuffle patterns in the
33714   // the 128-bit lanes use the variable mask to VPERMILPS.
33715   // TODO Combine other mask types at higher depths.
33716   if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
33717       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
33718        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
33719     SmallVector<SDValue, 16> VPermIdx;
33720     for (int M : Mask) {
33721       SDValue Idx =
33722           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
33723       VPermIdx.push_back(Idx);
33724     }
33725     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
33726     Res = DAG.getBitcast(MaskVT, V1);
33727     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
33728     return DAG.getBitcast(RootVT, Res);
33729   }
33730 
33731   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
33732   // to VPERMIL2PD/VPERMIL2PS.
33733   if (AllowVariableMask && Subtarget.hasXOP() &&
33734       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
33735        MaskVT == MVT::v8f32)) {
33736     // VPERMIL2 Operation.
33737     // Bits[3] - Match Bit.
33738     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
33739     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
33740     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
33741     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
33742     SmallVector<int, 8> VPerm2Idx;
33743     unsigned M2ZImm = 0;
33744     for (int M : Mask) {
33745       if (M == SM_SentinelUndef) {
33746         VPerm2Idx.push_back(-1);
33747         continue;
33748       }
33749       if (M == SM_SentinelZero) {
33750         M2ZImm = 2;
33751         VPerm2Idx.push_back(8);
33752         continue;
33753       }
33754       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
33755       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
33756       VPerm2Idx.push_back(Index);
33757     }
33758     V1 = DAG.getBitcast(MaskVT, V1);
33759     V2 = DAG.getBitcast(MaskVT, V2);
33760     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
33761     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
33762                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
33763     return DAG.getBitcast(RootVT, Res);
33764   }
33765 
33766   // If we have 3 or more shuffle instructions or a chain involving a variable
33767   // mask, we can replace them with a single PSHUFB instruction profitably.
33768   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
33769   // instructions, but in practice PSHUFB tends to be *very* fast so we're
33770   // more aggressive.
33771   if (UnaryShuffle && AllowVariableMask &&
33772       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
33773        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
33774        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
33775     SmallVector<SDValue, 16> PSHUFBMask;
33776     int NumBytes = RootVT.getSizeInBits() / 8;
33777     int Ratio = NumBytes / NumMaskElts;
33778     for (int i = 0; i < NumBytes; ++i) {
33779       int M = Mask[i / Ratio];
33780       if (M == SM_SentinelUndef) {
33781         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
33782         continue;
33783       }
33784       if (M == SM_SentinelZero) {
33785         PSHUFBMask.push_back(DAG.getConstant(255, DL, MVT::i8));
33786         continue;
33787       }
33788       M = Ratio * M + i % Ratio;
33789       assert((M / 16) == (i / 16) && "Lane crossing detected");
33790       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
33791     }
33792     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
33793     Res = DAG.getBitcast(ByteVT, V1);
33794     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
33795     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
33796     return DAG.getBitcast(RootVT, Res);
33797   }
33798 
33799   // With XOP, if we have a 128-bit binary input shuffle we can always combine
33800   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
33801   // slower than PSHUFB on targets that support both.
33802   if (AllowVariableMask && RootVT.is128BitVector() && Subtarget.hasXOP()) {
33803     // VPPERM Mask Operation
33804     // Bits[4:0] - Byte Index (0 - 31)
33805     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
33806     SmallVector<SDValue, 16> VPPERMMask;
33807     int NumBytes = 16;
33808     int Ratio = NumBytes / NumMaskElts;
33809     for (int i = 0; i < NumBytes; ++i) {
33810       int M = Mask[i / Ratio];
33811       if (M == SM_SentinelUndef) {
33812         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
33813         continue;
33814       }
33815       if (M == SM_SentinelZero) {
33816         VPPERMMask.push_back(DAG.getConstant(128, DL, MVT::i8));
33817         continue;
33818       }
33819       M = Ratio * M + i % Ratio;
33820       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
33821     }
33822     MVT ByteVT = MVT::v16i8;
33823     V1 = DAG.getBitcast(ByteVT, V1);
33824     V2 = DAG.getBitcast(ByteVT, V2);
33825     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
33826     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
33827     return DAG.getBitcast(RootVT, Res);
33828   }
33829 
33830   // If that failed and either input is extracted then try to combine as a
33831   // shuffle with the larger type.
33832   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
33833           Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
33834           DAG, Subtarget))
33835     return WideShuffle;
33836 
33837   // If we have a dual input shuffle then lower to VPERMV3.
33838   if (!UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
33839       ((Subtarget.hasAVX512() &&
33840         (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
33841          MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
33842        (Subtarget.hasVLX() &&
33843         (MaskVT == MVT::v2f64 || MaskVT == MVT::v2i64 || MaskVT == MVT::v4f64 ||
33844          MaskVT == MVT::v4i64 || MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 ||
33845          MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
33846        (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
33847        (Subtarget.hasBWI() && Subtarget.hasVLX() &&
33848         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16)) ||
33849        (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
33850        (Subtarget.hasVBMI() && Subtarget.hasVLX() &&
33851         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8)))) {
33852     SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
33853     V1 = DAG.getBitcast(MaskVT, V1);
33854     V2 = DAG.getBitcast(MaskVT, V2);
33855     Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
33856     return DAG.getBitcast(RootVT, Res);
33857   }
33858 
33859   // Failed to find any combines.
33860   return SDValue();
33861 }
33862 
33863 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
33864 // instruction if possible.
33865 //
33866 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
33867 // type size to attempt to combine:
33868 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
33869 // -->
33870 // extract_subvector(shuffle(x,y,m2),0)
combineX86ShuffleChainWithExtract(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)33871 static SDValue combineX86ShuffleChainWithExtract(
33872     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
33873     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
33874     const X86Subtarget &Subtarget) {
33875   unsigned NumMaskElts = BaseMask.size();
33876   unsigned NumInputs = Inputs.size();
33877   if (NumInputs == 0)
33878     return SDValue();
33879 
33880   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
33881   SmallVector<unsigned, 4> Offsets(NumInputs, 0);
33882 
33883   // Peek through subvectors.
33884   // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
33885   unsigned WideSizeInBits = WideInputs[0].getValueSizeInBits();
33886   for (unsigned i = 0; i != NumInputs; ++i) {
33887     SDValue &Src = WideInputs[i];
33888     unsigned &Offset = Offsets[i];
33889     Src = peekThroughBitcasts(Src);
33890     EVT BaseVT = Src.getValueType();
33891     while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
33892            isa<ConstantSDNode>(Src.getOperand(1))) {
33893       Offset += Src.getConstantOperandVal(1);
33894       Src = Src.getOperand(0);
33895     }
33896     WideSizeInBits = std::max(WideSizeInBits,
33897                               (unsigned)Src.getValueSizeInBits());
33898     assert((Offset % BaseVT.getVectorNumElements()) == 0 &&
33899            "Unexpected subvector extraction");
33900     Offset /= BaseVT.getVectorNumElements();
33901     Offset *= NumMaskElts;
33902   }
33903 
33904   // Bail if we're always extracting from the lowest subvectors,
33905   // combineX86ShuffleChain should match this for the current width.
33906   if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
33907     return SDValue();
33908 
33909   EVT RootVT = Root.getValueType();
33910   unsigned RootSizeInBits = RootVT.getSizeInBits();
33911   unsigned Scale = WideSizeInBits / RootSizeInBits;
33912   assert((WideSizeInBits % RootSizeInBits) == 0 &&
33913          "Unexpected subvector extraction");
33914 
33915   // If the src vector types aren't the same, see if we can extend
33916   // them to match each other.
33917   // TODO: Support different scalar types?
33918   EVT WideSVT = WideInputs[0].getValueType().getScalarType();
33919   if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
33920         return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
33921                Op.getValueType().getScalarType() != WideSVT;
33922       }))
33923     return SDValue();
33924 
33925   for (SDValue &NewInput : WideInputs) {
33926     assert((WideSizeInBits % NewInput.getValueSizeInBits()) == 0 &&
33927            "Shuffle vector size mismatch");
33928     if (WideSizeInBits > NewInput.getValueSizeInBits())
33929       NewInput = widenSubVector(NewInput, false, Subtarget, DAG,
33930                                 SDLoc(NewInput), WideSizeInBits);
33931     assert(WideSizeInBits == NewInput.getValueSizeInBits() &&
33932            "Unexpected subvector extraction");
33933   }
33934 
33935   // Create new mask for larger type.
33936   for (unsigned i = 1; i != NumInputs; ++i)
33937     Offsets[i] += i * Scale * NumMaskElts;
33938 
33939   SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
33940   for (int &M : WideMask) {
33941     if (M < 0)
33942       continue;
33943     M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
33944   }
33945   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
33946 
33947   // Remove unused/repeated shuffle source ops.
33948   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
33949   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
33950 
33951   if (WideInputs.size() > 2)
33952     return SDValue();
33953 
33954   // Increase depth for every upper subvector we've peeked through.
33955   Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
33956 
33957   // Attempt to combine wider chain.
33958   // TODO: Can we use a better Root?
33959   SDValue WideRoot = WideInputs[0];
33960   if (SDValue WideShuffle = combineX86ShuffleChain(
33961           WideInputs, WideRoot, WideMask, Depth, HasVariableMask,
33962           AllowVariableMask, DAG, Subtarget)) {
33963     WideShuffle =
33964         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
33965     return DAG.getBitcast(RootVT, WideShuffle);
33966   }
33967   return SDValue();
33968 }
33969 
33970 // Attempt to constant fold all of the constant source ops.
33971 // Returns true if the entire shuffle is folded to a constant.
33972 // TODO: Extend this to merge multiple constant Ops and update the mask.
combineX86ShufflesConstants(ArrayRef<SDValue> Ops,ArrayRef<int> Mask,SDValue Root,bool HasVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)33973 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
33974                                            ArrayRef<int> Mask, SDValue Root,
33975                                            bool HasVariableMask,
33976                                            SelectionDAG &DAG,
33977                                            const X86Subtarget &Subtarget) {
33978   MVT VT = Root.getSimpleValueType();
33979 
33980   unsigned SizeInBits = VT.getSizeInBits();
33981   unsigned NumMaskElts = Mask.size();
33982   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
33983   unsigned NumOps = Ops.size();
33984 
33985   // Extract constant bits from each source op.
33986   bool OneUseConstantOp = false;
33987   SmallVector<APInt, 16> UndefEltsOps(NumOps);
33988   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
33989   for (unsigned i = 0; i != NumOps; ++i) {
33990     SDValue SrcOp = Ops[i];
33991     OneUseConstantOp |= SrcOp.hasOneUse();
33992     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
33993                                        RawBitsOps[i]))
33994       return SDValue();
33995   }
33996 
33997   // Only fold if at least one of the constants is only used once or
33998   // the combined shuffle has included a variable mask shuffle, this
33999   // is to avoid constant pool bloat.
34000   if (!OneUseConstantOp && !HasVariableMask)
34001     return SDValue();
34002 
34003   // Shuffle the constant bits according to the mask.
34004   APInt UndefElts(NumMaskElts, 0);
34005   APInt ZeroElts(NumMaskElts, 0);
34006   APInt ConstantElts(NumMaskElts, 0);
34007   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
34008                                         APInt::getNullValue(MaskSizeInBits));
34009   for (unsigned i = 0; i != NumMaskElts; ++i) {
34010     int M = Mask[i];
34011     if (M == SM_SentinelUndef) {
34012       UndefElts.setBit(i);
34013       continue;
34014     } else if (M == SM_SentinelZero) {
34015       ZeroElts.setBit(i);
34016       continue;
34017     }
34018     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
34019 
34020     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
34021     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
34022 
34023     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
34024     if (SrcUndefElts[SrcMaskIdx]) {
34025       UndefElts.setBit(i);
34026       continue;
34027     }
34028 
34029     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
34030     APInt &Bits = SrcEltBits[SrcMaskIdx];
34031     if (!Bits) {
34032       ZeroElts.setBit(i);
34033       continue;
34034     }
34035 
34036     ConstantElts.setBit(i);
34037     ConstantBitData[i] = Bits;
34038   }
34039   assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue());
34040 
34041   // Create the constant data.
34042   MVT MaskSVT;
34043   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
34044     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
34045   else
34046     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
34047 
34048   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
34049 
34050   SDLoc DL(Root);
34051   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
34052   return DAG.getBitcast(VT, CstOp);
34053 }
34054 
34055 /// Fully generic combining of x86 shuffle instructions.
34056 ///
34057 /// This should be the last combine run over the x86 shuffle instructions. Once
34058 /// they have been fully optimized, this will recursively consider all chains
34059 /// of single-use shuffle instructions, build a generic model of the cumulative
34060 /// shuffle operation, and check for simpler instructions which implement this
34061 /// operation. We use this primarily for two purposes:
34062 ///
34063 /// 1) Collapse generic shuffles to specialized single instructions when
34064 ///    equivalent. In most cases, this is just an encoding size win, but
34065 ///    sometimes we will collapse multiple generic shuffles into a single
34066 ///    special-purpose shuffle.
34067 /// 2) Look for sequences of shuffle instructions with 3 or more total
34068 ///    instructions, and replace them with the slightly more expensive SSSE3
34069 ///    PSHUFB instruction if available. We do this as the last combining step
34070 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
34071 ///    a suitable short sequence of other instructions. The PSHUFB will either
34072 ///    use a register or have to read from memory and so is slightly (but only
34073 ///    slightly) more expensive than the other shuffle instructions.
34074 ///
34075 /// Because this is inherently a quadratic operation (for each shuffle in
34076 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
34077 /// This should never be an issue in practice as the shuffle lowering doesn't
34078 /// produce sequences of more than 8 instructions.
34079 ///
34080 /// FIXME: We will currently miss some cases where the redundant shuffling
34081 /// would simplify under the threshold for PSHUFB formation because of
34082 /// combine-ordering. To fix this, we should do the redundant instruction
34083 /// combining in this recursive walk.
combineX86ShufflesRecursively(ArrayRef<SDValue> SrcOps,int SrcOpIndex,SDValue Root,ArrayRef<int> RootMask,ArrayRef<const SDNode * > SrcNodes,unsigned Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)34084 static SDValue combineX86ShufflesRecursively(
34085     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
34086     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
34087     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
34088     const X86Subtarget &Subtarget) {
34089   assert(RootMask.size() > 0 &&
34090          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
34091          "Illegal shuffle root mask");
34092 
34093   // Bound the depth of our recursive combine because this is ultimately
34094   // quadratic in nature.
34095   const unsigned MaxRecursionDepth = 8;
34096   if (Depth >= MaxRecursionDepth)
34097     return SDValue();
34098 
34099   // Directly rip through bitcasts to find the underlying operand.
34100   SDValue Op = SrcOps[SrcOpIndex];
34101   Op = peekThroughOneUseBitcasts(Op);
34102 
34103   MVT VT = Op.getSimpleValueType();
34104   if (!VT.isVector())
34105     return SDValue(); // Bail if we hit a non-vector.
34106 
34107   assert(Root.getSimpleValueType().isVector() &&
34108          "Shuffles operate on vector types!");
34109   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
34110          "Can only combine shuffles of the same vector register size.");
34111 
34112   // Extract target shuffle mask and resolve sentinels and inputs.
34113   // TODO - determine Op's demanded elts from RootMask.
34114   SmallVector<int, 64> OpMask;
34115   SmallVector<SDValue, 2> OpInputs;
34116   APInt OpUndef, OpZero;
34117   APInt OpDemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
34118   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
34119   if (!getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
34120                               OpZero, DAG, Depth, false))
34121     return SDValue();
34122 
34123   SmallVector<int, 64> Mask;
34124   SmallVector<SDValue, 16> Ops;
34125 
34126   // We don't need to merge masks if the root is empty.
34127   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
34128   if (EmptyRoot) {
34129     // Only resolve zeros if it will remove an input, otherwise we might end
34130     // up in an infinite loop.
34131     bool ResolveKnownZeros = true;
34132     if (!OpZero.isNullValue()) {
34133       APInt UsedInputs = APInt::getNullValue(OpInputs.size());
34134       for (int i = 0, e = OpMask.size(); i != e; ++i) {
34135         int M = OpMask[i];
34136         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
34137           continue;
34138         UsedInputs.setBit(M / OpMask.size());
34139         if (UsedInputs.isAllOnesValue()) {
34140           ResolveKnownZeros = false;
34141           break;
34142         }
34143       }
34144     }
34145     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
34146                                       ResolveKnownZeros);
34147 
34148     Mask = OpMask;
34149     Ops.append(OpInputs.begin(), OpInputs.end());
34150   } else {
34151     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
34152 
34153     // Add the inputs to the Ops list, avoiding duplicates.
34154     Ops.append(SrcOps.begin(), SrcOps.end());
34155 
34156     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
34157       // Attempt to find an existing match.
34158       SDValue InputBC = peekThroughBitcasts(Input);
34159       for (int i = 0, e = Ops.size(); i < e; ++i)
34160         if (InputBC == peekThroughBitcasts(Ops[i]))
34161           return i;
34162       // Match failed - should we replace an existing Op?
34163       if (InsertionPoint >= 0) {
34164         Ops[InsertionPoint] = Input;
34165         return InsertionPoint;
34166       }
34167       // Add to the end of the Ops list.
34168       Ops.push_back(Input);
34169       return Ops.size() - 1;
34170     };
34171 
34172     SmallVector<int, 2> OpInputIdx;
34173     for (SDValue OpInput : OpInputs)
34174       OpInputIdx.push_back(
34175           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
34176 
34177     assert(((RootMask.size() > OpMask.size() &&
34178              RootMask.size() % OpMask.size() == 0) ||
34179             (OpMask.size() > RootMask.size() &&
34180              OpMask.size() % RootMask.size() == 0) ||
34181             OpMask.size() == RootMask.size()) &&
34182            "The smaller number of elements must divide the larger.");
34183 
34184     // This function can be performance-critical, so we rely on the power-of-2
34185     // knowledge that we have about the mask sizes to replace div/rem ops with
34186     // bit-masks and shifts.
34187     assert(isPowerOf2_32(RootMask.size()) &&
34188            "Non-power-of-2 shuffle mask sizes");
34189     assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
34190     unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
34191     unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
34192 
34193     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
34194     unsigned RootRatio =
34195         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
34196     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
34197     assert((RootRatio == 1 || OpRatio == 1) &&
34198            "Must not have a ratio for both incoming and op masks!");
34199 
34200     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
34201     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
34202     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
34203     unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
34204     unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
34205 
34206     Mask.resize(MaskWidth, SM_SentinelUndef);
34207 
34208     // Merge this shuffle operation's mask into our accumulated mask. Note that
34209     // this shuffle's mask will be the first applied to the input, followed by
34210     // the root mask to get us all the way to the root value arrangement. The
34211     // reason for this order is that we are recursing up the operation chain.
34212     for (unsigned i = 0; i < MaskWidth; ++i) {
34213       unsigned RootIdx = i >> RootRatioLog2;
34214       if (RootMask[RootIdx] < 0) {
34215         // This is a zero or undef lane, we're done.
34216         Mask[i] = RootMask[RootIdx];
34217         continue;
34218       }
34219 
34220       unsigned RootMaskedIdx =
34221           RootRatio == 1
34222               ? RootMask[RootIdx]
34223               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
34224 
34225       // Just insert the scaled root mask value if it references an input other
34226       // than the SrcOp we're currently inserting.
34227       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
34228           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
34229         Mask[i] = RootMaskedIdx;
34230         continue;
34231       }
34232 
34233       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
34234       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
34235       if (OpMask[OpIdx] < 0) {
34236         // The incoming lanes are zero or undef, it doesn't matter which ones we
34237         // are using.
34238         Mask[i] = OpMask[OpIdx];
34239         continue;
34240       }
34241 
34242       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
34243       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
34244                                           : (OpMask[OpIdx] << OpRatioLog2) +
34245                                                 (RootMaskedIdx & (OpRatio - 1));
34246 
34247       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
34248       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
34249       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
34250       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
34251 
34252       Mask[i] = OpMaskedIdx;
34253     }
34254   }
34255 
34256   // Remove unused/repeated shuffle source ops.
34257   resolveTargetShuffleInputsAndMask(Ops, Mask);
34258 
34259   // Handle the all undef/zero cases early.
34260   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
34261     return DAG.getUNDEF(Root.getValueType());
34262 
34263   // TODO - should we handle the mixed zero/undef case as well? Just returning
34264   // a zero mask will lose information on undef elements possibly reducing
34265   // future combine possibilities.
34266   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
34267     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
34268                          SDLoc(Root));
34269 
34270   assert(!Ops.empty() && "Shuffle with no inputs detected");
34271   HasVariableMask |= IsOpVariableMask;
34272 
34273   // Update the list of shuffle nodes that have been combined so far.
34274   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
34275                                                 SrcNodes.end());
34276   CombinedNodes.push_back(Op.getNode());
34277 
34278   // See if we can recurse into each shuffle source op (if it's a target
34279   // shuffle). The source op should only be generally combined if it either has
34280   // a single use (i.e. current Op) or all its users have already been combined,
34281   // if not then we can still combine but should prevent generation of variable
34282   // shuffles to avoid constant pool bloat.
34283   // Don't recurse if we already have more source ops than we can combine in
34284   // the remaining recursion depth.
34285   if (Ops.size() < (MaxRecursionDepth - Depth)) {
34286     for (int i = 0, e = Ops.size(); i < e; ++i) {
34287       // For empty roots, we need to resolve zeroable elements before combining
34288       // them with other shuffles.
34289       SmallVector<int, 64> ResolvedMask = Mask;
34290       if (EmptyRoot)
34291         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
34292       bool AllowVar = false;
34293       if (Ops[i].getNode()->hasOneUse() ||
34294           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode()))
34295         AllowVar = AllowVariableMask;
34296       if (SDValue Res = combineX86ShufflesRecursively(
34297               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1,
34298               HasVariableMask, AllowVar, DAG, Subtarget))
34299         return Res;
34300     }
34301   }
34302 
34303   // Attempt to constant fold all of the constant source ops.
34304   if (SDValue Cst = combineX86ShufflesConstants(
34305           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
34306     return Cst;
34307 
34308   // We can only combine unary and binary shuffle mask cases.
34309   if (Ops.size() <= 2) {
34310     // Minor canonicalization of the accumulated shuffle mask to make it easier
34311     // to match below. All this does is detect masks with sequential pairs of
34312     // elements, and shrink them to the half-width mask. It does this in a loop
34313     // so it will reduce the size of the mask to the minimal width mask which
34314     // performs an equivalent shuffle.
34315     SmallVector<int, 64> WidenedMask;
34316     while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
34317       Mask = std::move(WidenedMask);
34318     }
34319 
34320     // Canonicalization of binary shuffle masks to improve pattern matching by
34321     // commuting the inputs.
34322     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
34323       ShuffleVectorSDNode::commuteMask(Mask);
34324       std::swap(Ops[0], Ops[1]);
34325     }
34326 
34327     // Finally, try to combine into a single shuffle instruction.
34328     return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
34329                                   AllowVariableMask, DAG, Subtarget);
34330   }
34331 
34332   // If that failed and any input is extracted then try to combine as a
34333   // shuffle with the larger type.
34334   return combineX86ShuffleChainWithExtract(Ops, Root, Mask, Depth,
34335                                            HasVariableMask, AllowVariableMask,
34336                                            DAG, Subtarget);
34337 }
34338 
34339 /// Helper entry wrapper to combineX86ShufflesRecursively.
combineX86ShufflesRecursively(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)34340 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
34341                                              const X86Subtarget &Subtarget) {
34342   return combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 0,
34343                                        /*HasVarMask*/ false,
34344                                        /*AllowVarMask*/ true, DAG, Subtarget);
34345 }
34346 
34347 /// Get the PSHUF-style mask from PSHUF node.
34348 ///
34349 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
34350 /// PSHUF-style masks that can be reused with such instructions.
getPSHUFShuffleMask(SDValue N)34351 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
34352   MVT VT = N.getSimpleValueType();
34353   SmallVector<int, 4> Mask;
34354   SmallVector<SDValue, 2> Ops;
34355   bool IsUnary;
34356   bool HaveMask =
34357       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
34358   (void)HaveMask;
34359   assert(HaveMask);
34360 
34361   // If we have more than 128-bits, only the low 128-bits of shuffle mask
34362   // matter. Check that the upper masks are repeats and remove them.
34363   if (VT.getSizeInBits() > 128) {
34364     int LaneElts = 128 / VT.getScalarSizeInBits();
34365 #ifndef NDEBUG
34366     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
34367       for (int j = 0; j < LaneElts; ++j)
34368         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
34369                "Mask doesn't repeat in high 128-bit lanes!");
34370 #endif
34371     Mask.resize(LaneElts);
34372   }
34373 
34374   switch (N.getOpcode()) {
34375   case X86ISD::PSHUFD:
34376     return Mask;
34377   case X86ISD::PSHUFLW:
34378     Mask.resize(4);
34379     return Mask;
34380   case X86ISD::PSHUFHW:
34381     Mask.erase(Mask.begin(), Mask.begin() + 4);
34382     for (int &M : Mask)
34383       M -= 4;
34384     return Mask;
34385   default:
34386     llvm_unreachable("No valid shuffle instruction found!");
34387   }
34388 }
34389 
34390 /// Search for a combinable shuffle across a chain ending in pshufd.
34391 ///
34392 /// We walk up the chain and look for a combinable shuffle, skipping over
34393 /// shuffles that we could hoist this shuffle's transformation past without
34394 /// altering anything.
34395 static SDValue
combineRedundantDWordShuffle(SDValue N,MutableArrayRef<int> Mask,SelectionDAG & DAG)34396 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
34397                              SelectionDAG &DAG) {
34398   assert(N.getOpcode() == X86ISD::PSHUFD &&
34399          "Called with something other than an x86 128-bit half shuffle!");
34400   SDLoc DL(N);
34401 
34402   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
34403   // of the shuffles in the chain so that we can form a fresh chain to replace
34404   // this one.
34405   SmallVector<SDValue, 8> Chain;
34406   SDValue V = N.getOperand(0);
34407   for (; V.hasOneUse(); V = V.getOperand(0)) {
34408     switch (V.getOpcode()) {
34409     default:
34410       return SDValue(); // Nothing combined!
34411 
34412     case ISD::BITCAST:
34413       // Skip bitcasts as we always know the type for the target specific
34414       // instructions.
34415       continue;
34416 
34417     case X86ISD::PSHUFD:
34418       // Found another dword shuffle.
34419       break;
34420 
34421     case X86ISD::PSHUFLW:
34422       // Check that the low words (being shuffled) are the identity in the
34423       // dword shuffle, and the high words are self-contained.
34424       if (Mask[0] != 0 || Mask[1] != 1 ||
34425           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
34426         return SDValue();
34427 
34428       Chain.push_back(V);
34429       continue;
34430 
34431     case X86ISD::PSHUFHW:
34432       // Check that the high words (being shuffled) are the identity in the
34433       // dword shuffle, and the low words are self-contained.
34434       if (Mask[2] != 2 || Mask[3] != 3 ||
34435           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
34436         return SDValue();
34437 
34438       Chain.push_back(V);
34439       continue;
34440 
34441     case X86ISD::UNPCKL:
34442     case X86ISD::UNPCKH:
34443       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
34444       // shuffle into a preceding word shuffle.
34445       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
34446           V.getSimpleValueType().getVectorElementType() != MVT::i16)
34447         return SDValue();
34448 
34449       // Search for a half-shuffle which we can combine with.
34450       unsigned CombineOp =
34451           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
34452       if (V.getOperand(0) != V.getOperand(1) ||
34453           !V->isOnlyUserOf(V.getOperand(0).getNode()))
34454         return SDValue();
34455       Chain.push_back(V);
34456       V = V.getOperand(0);
34457       do {
34458         switch (V.getOpcode()) {
34459         default:
34460           return SDValue(); // Nothing to combine.
34461 
34462         case X86ISD::PSHUFLW:
34463         case X86ISD::PSHUFHW:
34464           if (V.getOpcode() == CombineOp)
34465             break;
34466 
34467           Chain.push_back(V);
34468 
34469           LLVM_FALLTHROUGH;
34470         case ISD::BITCAST:
34471           V = V.getOperand(0);
34472           continue;
34473         }
34474         break;
34475       } while (V.hasOneUse());
34476       break;
34477     }
34478     // Break out of the loop if we break out of the switch.
34479     break;
34480   }
34481 
34482   if (!V.hasOneUse())
34483     // We fell out of the loop without finding a viable combining instruction.
34484     return SDValue();
34485 
34486   // Merge this node's mask and our incoming mask.
34487   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
34488   for (int &M : Mask)
34489     M = VMask[M];
34490   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
34491                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
34492 
34493   // Rebuild the chain around this new shuffle.
34494   while (!Chain.empty()) {
34495     SDValue W = Chain.pop_back_val();
34496 
34497     if (V.getValueType() != W.getOperand(0).getValueType())
34498       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
34499 
34500     switch (W.getOpcode()) {
34501     default:
34502       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
34503 
34504     case X86ISD::UNPCKL:
34505     case X86ISD::UNPCKH:
34506       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
34507       break;
34508 
34509     case X86ISD::PSHUFD:
34510     case X86ISD::PSHUFLW:
34511     case X86ISD::PSHUFHW:
34512       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
34513       break;
34514     }
34515   }
34516   if (V.getValueType() != N.getValueType())
34517     V = DAG.getBitcast(N.getValueType(), V);
34518 
34519   // Return the new chain to replace N.
34520   return V;
34521 }
34522 
34523 /// Try to combine x86 target specific shuffles.
combineTargetShuffle(SDValue N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)34524 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
34525                                     TargetLowering::DAGCombinerInfo &DCI,
34526                                     const X86Subtarget &Subtarget) {
34527   SDLoc DL(N);
34528   MVT VT = N.getSimpleValueType();
34529   SmallVector<int, 4> Mask;
34530   unsigned Opcode = N.getOpcode();
34531 
34532   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
34533   // single instruction.
34534   if (VT.getScalarSizeInBits() == 64 &&
34535       (Opcode == X86ISD::MOVSD || Opcode == X86ISD::UNPCKH ||
34536        Opcode == X86ISD::UNPCKL)) {
34537     auto BC0 = peekThroughBitcasts(N.getOperand(0));
34538     auto BC1 = peekThroughBitcasts(N.getOperand(1));
34539     EVT VT0 = BC0.getValueType();
34540     EVT VT1 = BC1.getValueType();
34541     unsigned Opcode0 = BC0.getOpcode();
34542     unsigned Opcode1 = BC1.getOpcode();
34543     if (Opcode0 == Opcode1 && VT0 == VT1 &&
34544         (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
34545          Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB ||
34546          Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS)) {
34547       SDValue Lo, Hi;
34548       if (Opcode == X86ISD::MOVSD) {
34549         Lo = BC1.getOperand(0);
34550         Hi = BC0.getOperand(1);
34551       } else {
34552         Lo = BC0.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
34553         Hi = BC1.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
34554       }
34555       SDValue Horiz = DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
34556       return DAG.getBitcast(VT, Horiz);
34557     }
34558   }
34559 
34560   switch (Opcode) {
34561   case X86ISD::VBROADCAST: {
34562     SDValue Src = N.getOperand(0);
34563     SDValue BC = peekThroughBitcasts(Src);
34564     EVT SrcVT = Src.getValueType();
34565     EVT BCVT = BC.getValueType();
34566 
34567     // If broadcasting from another shuffle, attempt to simplify it.
34568     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
34569     if (isTargetShuffle(BC.getOpcode()) &&
34570         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
34571       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
34572       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
34573                                         SM_SentinelUndef);
34574       for (unsigned i = 0; i != Scale; ++i)
34575         DemandedMask[i] = i;
34576       if (SDValue Res = combineX86ShufflesRecursively(
34577               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
34578               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
34579         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
34580                            DAG.getBitcast(SrcVT, Res));
34581     }
34582 
34583     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
34584     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
34585     if (Src.getOpcode() == ISD::BITCAST &&
34586         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits()) {
34587       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
34588                                    VT.getVectorNumElements());
34589       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
34590     }
34591 
34592     // Reduce broadcast source vector to lowest 128-bits.
34593     if (SrcVT.getSizeInBits() > 128)
34594       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
34595                          extract128BitVector(Src, 0, DAG, DL));
34596 
34597     // broadcast(scalar_to_vector(x)) -> broadcast(x).
34598     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
34599       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
34600 
34601     // Share broadcast with the longest vector and extract low subvector (free).
34602     for (SDNode *User : Src->uses())
34603       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
34604           User->getValueSizeInBits(0) > VT.getSizeInBits()) {
34605         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
34606                                 VT.getSizeInBits());
34607       }
34608 
34609     // vbroadcast(scalarload X) -> vbroadcast_load X
34610     // For float loads, extract other uses of the scalar from the broadcast.
34611     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
34612         ISD::isNormalLoad(Src.getNode())) {
34613       LoadSDNode *LN = cast<LoadSDNode>(Src);
34614       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
34615       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
34616       SDValue BcastLd =
34617           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
34618                                   LN->getMemoryVT(), LN->getMemOperand());
34619       // If the load value is used only by N, replace it via CombineTo N.
34620       bool NoReplaceExtract = Src.hasOneUse();
34621       DCI.CombineTo(N.getNode(), BcastLd);
34622       if (NoReplaceExtract) {
34623         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
34624         DCI.recursivelyDeleteUnusedNodes(LN);
34625       } else {
34626         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
34627                                   DAG.getIntPtrConstant(0, DL));
34628         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
34629       }
34630       return N; // Return N so it doesn't get rechecked!
34631     }
34632 
34633     return SDValue();
34634   }
34635   case X86ISD::BLENDI: {
34636     SDValue N0 = N.getOperand(0);
34637     SDValue N1 = N.getOperand(1);
34638 
34639     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
34640     // TODO: Handle MVT::v16i16 repeated blend mask.
34641     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
34642         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
34643       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
34644       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
34645           SrcVT.getScalarSizeInBits() >= 32) {
34646         unsigned BlendMask = N.getConstantOperandVal(2);
34647         unsigned Size = VT.getVectorNumElements();
34648         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
34649         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
34650         return DAG.getBitcast(
34651             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
34652                             N1.getOperand(0),
34653                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
34654       }
34655     }
34656     return SDValue();
34657   }
34658   case X86ISD::VPERMI: {
34659     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
34660     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
34661     SDValue N0 = N.getOperand(0);
34662     SDValue N1 = N.getOperand(1);
34663     unsigned EltSizeInBits = VT.getScalarSizeInBits();
34664     if (N0.getOpcode() == ISD::BITCAST &&
34665         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
34666       SDValue Src = N0.getOperand(0);
34667       EVT SrcVT = Src.getValueType();
34668       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
34669       return DAG.getBitcast(VT, Res);
34670     }
34671     return SDValue();
34672   }
34673   case X86ISD::PSHUFD:
34674   case X86ISD::PSHUFLW:
34675   case X86ISD::PSHUFHW:
34676     Mask = getPSHUFShuffleMask(N);
34677     assert(Mask.size() == 4);
34678     break;
34679   case X86ISD::MOVSD:
34680   case X86ISD::MOVSS: {
34681     SDValue N0 = N.getOperand(0);
34682     SDValue N1 = N.getOperand(1);
34683 
34684     // Canonicalize scalar FPOps:
34685     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
34686     // If commutable, allow OP(N1[0], N0[0]).
34687     unsigned Opcode1 = N1.getOpcode();
34688     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
34689         Opcode1 == ISD::FDIV) {
34690       SDValue N10 = N1.getOperand(0);
34691       SDValue N11 = N1.getOperand(1);
34692       if (N10 == N0 ||
34693           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
34694         if (N10 != N0)
34695           std::swap(N10, N11);
34696         MVT SVT = VT.getVectorElementType();
34697         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
34698         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
34699         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
34700         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
34701         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
34702         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
34703       }
34704     }
34705 
34706     return SDValue();
34707   }
34708   case X86ISD::INSERTPS: {
34709     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
34710     SDValue Op0 = N.getOperand(0);
34711     SDValue Op1 = N.getOperand(1);
34712     SDValue Op2 = N.getOperand(2);
34713     unsigned InsertPSMask = cast<ConstantSDNode>(Op2)->getZExtValue();
34714     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
34715     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
34716     unsigned ZeroMask = InsertPSMask & 0xF;
34717 
34718     // If we zero out all elements from Op0 then we don't need to reference it.
34719     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
34720       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
34721                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
34722 
34723     // If we zero out the element from Op1 then we don't need to reference it.
34724     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
34725       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
34726                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
34727 
34728     // Attempt to merge insertps Op1 with an inner target shuffle node.
34729     SmallVector<int, 8> TargetMask1;
34730     SmallVector<SDValue, 2> Ops1;
34731     APInt KnownUndef1, KnownZero1;
34732     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
34733                                      KnownZero1)) {
34734       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
34735         // Zero/UNDEF insertion - zero out element and remove dependency.
34736         InsertPSMask |= (1u << DstIdx);
34737         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
34738                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
34739       }
34740       // Update insertps mask srcidx and reference the source input directly.
34741       int M = TargetMask1[SrcIdx];
34742       assert(0 <= M && M < 8 && "Shuffle index out of range");
34743       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
34744       Op1 = Ops1[M < 4 ? 0 : 1];
34745       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
34746                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
34747     }
34748 
34749     // Attempt to merge insertps Op0 with an inner target shuffle node.
34750     SmallVector<int, 8> TargetMask0;
34751     SmallVector<SDValue, 2> Ops0;
34752     APInt KnownUndef0, KnownZero0;
34753     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
34754                                      KnownZero0)) {
34755       bool Updated = false;
34756       bool UseInput00 = false;
34757       bool UseInput01 = false;
34758       for (int i = 0; i != 4; ++i) {
34759         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
34760           // No change if element is already zero or the inserted element.
34761           continue;
34762         } else if (KnownUndef0[i] || KnownZero0[i]) {
34763           // If the target mask is undef/zero then we must zero the element.
34764           InsertPSMask |= (1u << i);
34765           Updated = true;
34766           continue;
34767         }
34768 
34769         // The input vector element must be inline.
34770         int M = TargetMask0[i];
34771         if (M != i && M != (i + 4))
34772           return SDValue();
34773 
34774         // Determine which inputs of the target shuffle we're using.
34775         UseInput00 |= (0 <= M && M < 4);
34776         UseInput01 |= (4 <= M);
34777       }
34778 
34779       // If we're not using both inputs of the target shuffle then use the
34780       // referenced input directly.
34781       if (UseInput00 && !UseInput01) {
34782         Updated = true;
34783         Op0 = Ops0[0];
34784       } else if (!UseInput00 && UseInput01) {
34785         Updated = true;
34786         Op0 = Ops0[1];
34787       }
34788 
34789       if (Updated)
34790         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
34791                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
34792     }
34793 
34794     // If we're inserting an element from a vbroadcast load, fold the
34795     // load into the X86insertps instruction. We need to convert the scalar
34796     // load to a vector and clear the source lane of the INSERTPS control.
34797     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
34798       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
34799       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
34800         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
34801                                    MemIntr->getBasePtr(),
34802                                    MemIntr->getMemOperand());
34803         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
34804                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
34805                                        Load),
34806                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
34807         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
34808         return Insert;
34809       }
34810     }
34811 
34812     return SDValue();
34813   }
34814   default:
34815     return SDValue();
34816   }
34817 
34818   // Nuke no-op shuffles that show up after combining.
34819   if (isNoopShuffleMask(Mask))
34820     return N.getOperand(0);
34821 
34822   // Look for simplifications involving one or two shuffle instructions.
34823   SDValue V = N.getOperand(0);
34824   switch (N.getOpcode()) {
34825   default:
34826     break;
34827   case X86ISD::PSHUFLW:
34828   case X86ISD::PSHUFHW:
34829     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
34830 
34831     // See if this reduces to a PSHUFD which is no more expensive and can
34832     // combine with more operations. Note that it has to at least flip the
34833     // dwords as otherwise it would have been removed as a no-op.
34834     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
34835       int DMask[] = {0, 1, 2, 3};
34836       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
34837       DMask[DOffset + 0] = DOffset + 1;
34838       DMask[DOffset + 1] = DOffset + 0;
34839       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
34840       V = DAG.getBitcast(DVT, V);
34841       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
34842                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
34843       return DAG.getBitcast(VT, V);
34844     }
34845 
34846     // Look for shuffle patterns which can be implemented as a single unpack.
34847     // FIXME: This doesn't handle the location of the PSHUFD generically, and
34848     // only works when we have a PSHUFD followed by two half-shuffles.
34849     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
34850         (V.getOpcode() == X86ISD::PSHUFLW ||
34851          V.getOpcode() == X86ISD::PSHUFHW) &&
34852         V.getOpcode() != N.getOpcode() &&
34853         V.hasOneUse()) {
34854       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
34855       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
34856         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
34857         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
34858         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
34859         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
34860         int WordMask[8];
34861         for (int i = 0; i < 4; ++i) {
34862           WordMask[i + NOffset] = Mask[i] + NOffset;
34863           WordMask[i + VOffset] = VMask[i] + VOffset;
34864         }
34865         // Map the word mask through the DWord mask.
34866         int MappedMask[8];
34867         for (int i = 0; i < 8; ++i)
34868           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
34869         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
34870             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
34871           // We can replace all three shuffles with an unpack.
34872           V = DAG.getBitcast(VT, D.getOperand(0));
34873           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
34874                                                 : X86ISD::UNPCKH,
34875                              DL, VT, V, V);
34876         }
34877       }
34878     }
34879 
34880     break;
34881 
34882   case X86ISD::PSHUFD:
34883     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
34884       return NewN;
34885 
34886     break;
34887   }
34888 
34889   return SDValue();
34890 }
34891 
34892 /// Checks if the shuffle mask takes subsequent elements
34893 /// alternately from two vectors.
34894 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
isAddSubOrSubAddMask(ArrayRef<int> Mask,bool & Op0Even)34895 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
34896 
34897   int ParitySrc[2] = {-1, -1};
34898   unsigned Size = Mask.size();
34899   for (unsigned i = 0; i != Size; ++i) {
34900     int M = Mask[i];
34901     if (M < 0)
34902       continue;
34903 
34904     // Make sure we are using the matching element from the input.
34905     if ((M % Size) != i)
34906       return false;
34907 
34908     // Make sure we use the same input for all elements of the same parity.
34909     int Src = M / Size;
34910     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
34911       return false;
34912     ParitySrc[i % 2] = Src;
34913   }
34914 
34915   // Make sure each input is used.
34916   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
34917     return false;
34918 
34919   Op0Even = ParitySrc[0] == 0;
34920   return true;
34921 }
34922 
34923 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
34924 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
34925 /// are written to the parameters \p Opnd0 and \p Opnd1.
34926 ///
34927 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
34928 /// so it is easier to generically match. We also insert dummy vector shuffle
34929 /// nodes for the operands which explicitly discard the lanes which are unused
34930 /// by this operation to try to flow through the rest of the combiner
34931 /// the fact that they're unused.
isAddSubOrSubAdd(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,bool & IsSubAdd)34932 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
34933                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
34934                              bool &IsSubAdd) {
34935 
34936   EVT VT = N->getValueType(0);
34937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34938   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
34939       !VT.getSimpleVT().isFloatingPoint())
34940     return false;
34941 
34942   // We only handle target-independent shuffles.
34943   // FIXME: It would be easy and harmless to use the target shuffle mask
34944   // extraction tool to support more.
34945   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
34946     return false;
34947 
34948   SDValue V1 = N->getOperand(0);
34949   SDValue V2 = N->getOperand(1);
34950 
34951   // Make sure we have an FADD and an FSUB.
34952   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
34953       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
34954       V1.getOpcode() == V2.getOpcode())
34955     return false;
34956 
34957   // If there are other uses of these operations we can't fold them.
34958   if (!V1->hasOneUse() || !V2->hasOneUse())
34959     return false;
34960 
34961   // Ensure that both operations have the same operands. Note that we can
34962   // commute the FADD operands.
34963   SDValue LHS, RHS;
34964   if (V1.getOpcode() == ISD::FSUB) {
34965     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
34966     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
34967         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
34968       return false;
34969   } else {
34970     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
34971     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
34972     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
34973         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
34974       return false;
34975   }
34976 
34977   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
34978   bool Op0Even;
34979   if (!isAddSubOrSubAddMask(Mask, Op0Even))
34980     return false;
34981 
34982   // It's a subadd if the vector in the even parity is an FADD.
34983   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
34984                      : V2->getOpcode() == ISD::FADD;
34985 
34986   Opnd0 = LHS;
34987   Opnd1 = RHS;
34988   return true;
34989 }
34990 
34991 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
combineShuffleToFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)34992 static SDValue combineShuffleToFMAddSub(SDNode *N,
34993                                         const X86Subtarget &Subtarget,
34994                                         SelectionDAG &DAG) {
34995   // We only handle target-independent shuffles.
34996   // FIXME: It would be easy and harmless to use the target shuffle mask
34997   // extraction tool to support more.
34998   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
34999     return SDValue();
35000 
35001   MVT VT = N->getSimpleValueType(0);
35002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35003   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
35004     return SDValue();
35005 
35006   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
35007   SDValue Op0 = N->getOperand(0);
35008   SDValue Op1 = N->getOperand(1);
35009   SDValue FMAdd = Op0, FMSub = Op1;
35010   if (FMSub.getOpcode() != X86ISD::FMSUB)
35011     std::swap(FMAdd, FMSub);
35012 
35013   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
35014       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
35015       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
35016       FMAdd.getOperand(2) != FMSub.getOperand(2))
35017     return SDValue();
35018 
35019   // Check for correct shuffle mask.
35020   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
35021   bool Op0Even;
35022   if (!isAddSubOrSubAddMask(Mask, Op0Even))
35023     return SDValue();
35024 
35025   // FMAddSub takes zeroth operand from FMSub node.
35026   SDLoc DL(N);
35027   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
35028   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
35029   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
35030                      FMAdd.getOperand(2));
35031 }
35032 
35033 /// Try to combine a shuffle into a target-specific add-sub or
35034 /// mul-add-sub node.
combineShuffleToAddSubOrFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)35035 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
35036                                                 const X86Subtarget &Subtarget,
35037                                                 SelectionDAG &DAG) {
35038   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
35039     return V;
35040 
35041   SDValue Opnd0, Opnd1;
35042   bool IsSubAdd;
35043   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
35044     return SDValue();
35045 
35046   MVT VT = N->getSimpleValueType(0);
35047   SDLoc DL(N);
35048 
35049   // Try to generate X86ISD::FMADDSUB node here.
35050   SDValue Opnd2;
35051   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
35052     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
35053     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
35054   }
35055 
35056   if (IsSubAdd)
35057     return SDValue();
35058 
35059   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
35060   // the ADDSUB idiom has been successfully recognized. There are no known
35061   // X86 targets with 512-bit ADDSUB instructions!
35062   if (VT.is512BitVector())
35063     return SDValue();
35064 
35065   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
35066 }
35067 
35068 // We are looking for a shuffle where both sources are concatenated with undef
35069 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
35070 // if we can express this as a single-source shuffle, that's preferable.
combineShuffleOfConcatUndef(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)35071 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
35072                                            const X86Subtarget &Subtarget) {
35073   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
35074     return SDValue();
35075 
35076   EVT VT = N->getValueType(0);
35077 
35078   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
35079   if (!VT.is128BitVector() && !VT.is256BitVector())
35080     return SDValue();
35081 
35082   if (VT.getVectorElementType() != MVT::i32 &&
35083       VT.getVectorElementType() != MVT::i64 &&
35084       VT.getVectorElementType() != MVT::f32 &&
35085       VT.getVectorElementType() != MVT::f64)
35086     return SDValue();
35087 
35088   SDValue N0 = N->getOperand(0);
35089   SDValue N1 = N->getOperand(1);
35090 
35091   // Check that both sources are concats with undef.
35092   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
35093       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
35094       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
35095       !N1.getOperand(1).isUndef())
35096     return SDValue();
35097 
35098   // Construct the new shuffle mask. Elements from the first source retain their
35099   // index, but elements from the second source no longer need to skip an undef.
35100   SmallVector<int, 8> Mask;
35101   int NumElts = VT.getVectorNumElements();
35102 
35103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
35104   for (int Elt : SVOp->getMask())
35105     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
35106 
35107   SDLoc DL(N);
35108   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
35109                                N1.getOperand(0));
35110   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
35111 }
35112 
35113 /// Eliminate a redundant shuffle of a horizontal math op.
foldShuffleOfHorizOp(SDNode * N,SelectionDAG & DAG)35114 static SDValue foldShuffleOfHorizOp(SDNode *N, SelectionDAG &DAG) {
35115   unsigned Opcode = N->getOpcode();
35116   if (Opcode != X86ISD::MOVDDUP && Opcode != X86ISD::VBROADCAST)
35117     if (Opcode != ISD::VECTOR_SHUFFLE || !N->getOperand(1).isUndef())
35118       return SDValue();
35119 
35120   // For a broadcast, peek through an extract element of index 0 to find the
35121   // horizontal op: broadcast (ext_vec_elt HOp, 0)
35122   EVT VT = N->getValueType(0);
35123   if (Opcode == X86ISD::VBROADCAST) {
35124     SDValue SrcOp = N->getOperand(0);
35125     if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
35126         SrcOp.getValueType() == MVT::f64 &&
35127         SrcOp.getOperand(0).getValueType() == VT &&
35128         isNullConstant(SrcOp.getOperand(1)))
35129       N = SrcOp.getNode();
35130   }
35131 
35132   SDValue HOp = N->getOperand(0);
35133   if (HOp.getOpcode() != X86ISD::HADD && HOp.getOpcode() != X86ISD::FHADD &&
35134       HOp.getOpcode() != X86ISD::HSUB && HOp.getOpcode() != X86ISD::FHSUB)
35135     return SDValue();
35136 
35137   // 128-bit horizontal math instructions are defined to operate on adjacent
35138   // lanes of each operand as:
35139   // v4X32: A[0] + A[1] , A[2] + A[3] , B[0] + B[1] , B[2] + B[3]
35140   // ...similarly for v2f64 and v8i16.
35141   if (!HOp.getOperand(0).isUndef() && !HOp.getOperand(1).isUndef() &&
35142       HOp.getOperand(0) != HOp.getOperand(1))
35143     return SDValue();
35144 
35145   // The shuffle that we are eliminating may have allowed the horizontal op to
35146   // have an undemanded (undefined) operand. Duplicate the other (defined)
35147   // operand to ensure that the results are defined across all lanes without the
35148   // shuffle.
35149   auto updateHOp = [](SDValue HorizOp, SelectionDAG &DAG) {
35150     SDValue X;
35151     if (HorizOp.getOperand(0).isUndef()) {
35152       assert(!HorizOp.getOperand(1).isUndef() && "Not expecting foldable h-op");
35153       X = HorizOp.getOperand(1);
35154     } else if (HorizOp.getOperand(1).isUndef()) {
35155       assert(!HorizOp.getOperand(0).isUndef() && "Not expecting foldable h-op");
35156       X = HorizOp.getOperand(0);
35157     } else {
35158       return HorizOp;
35159     }
35160     return DAG.getNode(HorizOp.getOpcode(), SDLoc(HorizOp),
35161                        HorizOp.getValueType(), X, X);
35162   };
35163 
35164   // When the operands of a horizontal math op are identical, the low half of
35165   // the result is the same as the high half. If a target shuffle is also
35166   // replicating low and high halves (and without changing the type/length of
35167   // the vector), we don't need the shuffle.
35168   if (Opcode == X86ISD::MOVDDUP || Opcode == X86ISD::VBROADCAST) {
35169     if (HOp.getScalarValueSizeInBits() == 64 && HOp.getValueType() == VT) {
35170       // movddup (hadd X, X) --> hadd X, X
35171       // broadcast (extract_vec_elt (hadd X, X), 0) --> hadd X, X
35172       assert((HOp.getValueType() == MVT::v2f64 ||
35173               HOp.getValueType() == MVT::v4f64) && "Unexpected type for h-op");
35174       return updateHOp(HOp, DAG);
35175     }
35176     return SDValue();
35177   }
35178 
35179   // shuffle (hadd X, X), undef, [low half...high half] --> hadd X, X
35180   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
35181   // TODO: Other mask possibilities like {1,1} and {1,0} could be added here,
35182   // but this should be tied to whatever horizontal op matching and shuffle
35183   // canonicalization are producing.
35184   if (HOp.getValueSizeInBits() == 128 &&
35185       (isTargetShuffleEquivalent(Mask, {0, 0}) ||
35186        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1}) ||
35187        isTargetShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3})))
35188     return updateHOp(HOp, DAG);
35189 
35190   if (HOp.getValueSizeInBits() == 256 &&
35191       (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2}) ||
35192        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1, 4, 5, 4, 5}) ||
35193        isTargetShuffleEquivalent(
35194            Mask, {0, 1, 2, 3, 0, 1, 2, 3, 8, 9, 10, 11, 8, 9, 10, 11})))
35195     return updateHOp(HOp, DAG);
35196 
35197   return SDValue();
35198 }
35199 
35200 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
35201 /// low half of each source vector and does not set any high half elements in
35202 /// the destination vector, narrow the shuffle to half its original size.
narrowShuffle(ShuffleVectorSDNode * Shuf,SelectionDAG & DAG)35203 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
35204   if (!Shuf->getValueType(0).isSimple())
35205     return SDValue();
35206   MVT VT = Shuf->getSimpleValueType(0);
35207   if (!VT.is256BitVector() && !VT.is512BitVector())
35208     return SDValue();
35209 
35210   // See if we can ignore all of the high elements of the shuffle.
35211   ArrayRef<int> Mask = Shuf->getMask();
35212   if (!isUndefUpperHalf(Mask))
35213     return SDValue();
35214 
35215   // Check if the shuffle mask accesses only the low half of each input vector
35216   // (half-index output is 0 or 2).
35217   int HalfIdx1, HalfIdx2;
35218   SmallVector<int, 8> HalfMask(Mask.size() / 2);
35219   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
35220       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
35221     return SDValue();
35222 
35223   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
35224   // The trick is knowing that all of the insert/extract are actually free
35225   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
35226   // of narrow inputs into a narrow output, and that is always cheaper than
35227   // the wide shuffle that we started with.
35228   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
35229                                Shuf->getOperand(1), HalfMask, HalfIdx1,
35230                                HalfIdx2, false, DAG, /*UseConcat*/true);
35231 }
35232 
combineShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35233 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
35234                               TargetLowering::DAGCombinerInfo &DCI,
35235                               const X86Subtarget &Subtarget) {
35236   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
35237     if (SDValue V = narrowShuffle(Shuf, DAG))
35238       return V;
35239 
35240   // If we have legalized the vector types, look for blends of FADD and FSUB
35241   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
35242   SDLoc dl(N);
35243   EVT VT = N->getValueType(0);
35244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35245   if (TLI.isTypeLegal(VT)) {
35246     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
35247       return AddSub;
35248 
35249     if (SDValue HAddSub = foldShuffleOfHorizOp(N, DAG))
35250       return HAddSub;
35251   }
35252 
35253   // Attempt to combine into a vector load/broadcast.
35254   if (SDValue LD = combineToConsecutiveLoads(VT, N, dl, DAG, Subtarget, true))
35255     return LD;
35256 
35257   // For AVX2, we sometimes want to combine
35258   // (vector_shuffle <mask> (concat_vectors t1, undef)
35259   //                        (concat_vectors t2, undef))
35260   // Into:
35261   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
35262   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
35263   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
35264     return ShufConcat;
35265 
35266   if (isTargetShuffle(N->getOpcode())) {
35267     SDValue Op(N, 0);
35268     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
35269       return Shuffle;
35270 
35271     // Try recursively combining arbitrary sequences of x86 shuffle
35272     // instructions into higher-order shuffles. We do this after combining
35273     // specific PSHUF instruction sequences into their minimal form so that we
35274     // can evaluate how many specialized shuffle instructions are involved in
35275     // a particular chain.
35276     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
35277       return Res;
35278 
35279     // Simplify source operands based on shuffle mask.
35280     // TODO - merge this into combineX86ShufflesRecursively.
35281     APInt KnownUndef, KnownZero;
35282     APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
35283     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, DCI))
35284       return SDValue(N, 0);
35285   }
35286 
35287   // Look for a v2i64/v2f64 VZEXT_MOVL of a node that already produces zeros
35288   // in the upper 64 bits.
35289   // TODO: Can we generalize this using computeKnownBits.
35290   if (N->getOpcode() == X86ISD::VZEXT_MOVL &&
35291       (VT == MVT::v2f64 || VT == MVT::v2i64) &&
35292       N->getOperand(0).getOpcode() == ISD::BITCAST &&
35293       (N->getOperand(0).getOperand(0).getValueType() == MVT::v4f32 ||
35294        N->getOperand(0).getOperand(0).getValueType() == MVT::v4i32)) {
35295     SDValue In = N->getOperand(0).getOperand(0);
35296     switch (In.getOpcode()) {
35297     default:
35298       break;
35299     case X86ISD::CVTP2SI:   case X86ISD::CVTP2UI:
35300     case X86ISD::MCVTP2SI:  case X86ISD::MCVTP2UI:
35301     case X86ISD::CVTTP2SI:  case X86ISD::CVTTP2UI:
35302     case X86ISD::MCVTTP2SI: case X86ISD::MCVTTP2UI:
35303     case X86ISD::CVTSI2P:   case X86ISD::CVTUI2P:
35304     case X86ISD::MCVTSI2P:  case X86ISD::MCVTUI2P:
35305     case X86ISD::VFPROUND:  case X86ISD::VMFPROUND:
35306       if (In.getOperand(0).getValueType() == MVT::v2f64 ||
35307           In.getOperand(0).getValueType() == MVT::v2i64)
35308         return N->getOperand(0); // return the bitcast
35309       break;
35310     case X86ISD::STRICT_CVTTP2SI:
35311     case X86ISD::STRICT_CVTTP2UI:
35312     case X86ISD::STRICT_CVTSI2P:
35313     case X86ISD::STRICT_CVTUI2P:
35314     case X86ISD::STRICT_VFPROUND:
35315       if (In.getOperand(1).getValueType() == MVT::v2f64 ||
35316           In.getOperand(1).getValueType() == MVT::v2i64)
35317         return N->getOperand(0);
35318       break;
35319     }
35320   }
35321 
35322   // Pull subvector inserts into undef through VZEXT_MOVL by making it an
35323   // insert into a zero vector. This helps get VZEXT_MOVL closer to
35324   // scalar_to_vectors where 256/512 are canonicalized to an insert and a
35325   // 128-bit scalar_to_vector. This reduces the number of isel patterns.
35326   if (N->getOpcode() == X86ISD::VZEXT_MOVL && !DCI.isBeforeLegalizeOps() &&
35327       N->getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR &&
35328       N->getOperand(0).hasOneUse() &&
35329       N->getOperand(0).getOperand(0).isUndef() &&
35330       isNullConstant(N->getOperand(0).getOperand(2))) {
35331     SDValue In = N->getOperand(0).getOperand(1);
35332     SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, dl, In.getValueType(), In);
35333     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT,
35334                        getZeroVector(VT.getSimpleVT(), Subtarget, DAG, dl),
35335                        Movl, N->getOperand(0).getOperand(2));
35336   }
35337 
35338   // If this a vzmovl of a full vector load, replace it with a vzload, unless
35339   // the load is volatile.
35340   if (N->getOpcode() == X86ISD::VZEXT_MOVL && N->getOperand(0).hasOneUse() &&
35341       ISD::isNormalLoad(N->getOperand(0).getNode())) {
35342     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
35343     if (LN->isSimple()) {
35344       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
35345       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
35346       SDValue VZLoad =
35347           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
35348                                   VT.getVectorElementType(),
35349                                   LN->getPointerInfo(),
35350                                   LN->getAlignment(),
35351                                   MachineMemOperand::MOLoad);
35352       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
35353       return VZLoad;
35354     }
35355   }
35356 
35357   return SDValue();
35358 }
35359 
SimplifyDemandedVectorEltsForTargetNode(SDValue Op,const APInt & DemandedElts,APInt & KnownUndef,APInt & KnownZero,TargetLoweringOpt & TLO,unsigned Depth) const35360 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
35361     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
35362     TargetLoweringOpt &TLO, unsigned Depth) const {
35363   int NumElts = DemandedElts.getBitWidth();
35364   unsigned Opc = Op.getOpcode();
35365   EVT VT = Op.getValueType();
35366 
35367   // Handle special case opcodes.
35368   switch (Opc) {
35369   case X86ISD::PMULDQ:
35370   case X86ISD::PMULUDQ: {
35371     APInt LHSUndef, LHSZero;
35372     APInt RHSUndef, RHSZero;
35373     SDValue LHS = Op.getOperand(0);
35374     SDValue RHS = Op.getOperand(1);
35375     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
35376                                    Depth + 1))
35377       return true;
35378     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
35379                                    Depth + 1))
35380       return true;
35381     // Multiply by zero.
35382     KnownZero = LHSZero | RHSZero;
35383     break;
35384   }
35385   case X86ISD::VSHL:
35386   case X86ISD::VSRL:
35387   case X86ISD::VSRA: {
35388     // We only need the bottom 64-bits of the (128-bit) shift amount.
35389     SDValue Amt = Op.getOperand(1);
35390     MVT AmtVT = Amt.getSimpleValueType();
35391     assert(AmtVT.is128BitVector() && "Unexpected value type");
35392 
35393     // If we reuse the shift amount just for sse shift amounts then we know that
35394     // only the bottom 64-bits are only ever used.
35395     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
35396       unsigned UseOpc = Use->getOpcode();
35397       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
35398               UseOpc == X86ISD::VSRA) &&
35399              Use->getOperand(0) != Amt;
35400     });
35401 
35402     APInt AmtUndef, AmtZero;
35403     unsigned NumAmtElts = AmtVT.getVectorNumElements();
35404     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
35405     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
35406                                    Depth + 1, AssumeSingleUse))
35407       return true;
35408     LLVM_FALLTHROUGH;
35409   }
35410   case X86ISD::VSHLI:
35411   case X86ISD::VSRLI:
35412   case X86ISD::VSRAI: {
35413     SDValue Src = Op.getOperand(0);
35414     APInt SrcUndef;
35415     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
35416                                    Depth + 1))
35417       return true;
35418     // TODO convert SrcUndef to KnownUndef.
35419     break;
35420   }
35421   case X86ISD::KSHIFTL: {
35422     SDValue Src = Op.getOperand(0);
35423     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
35424     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
35425     unsigned ShiftAmt = Amt->getZExtValue();
35426 
35427     if (ShiftAmt == 0)
35428       return TLO.CombineTo(Op, Src);
35429 
35430     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
35431     // single shift.  We can do this if the bottom bits (which are shifted
35432     // out) are never demanded.
35433     if (Src.getOpcode() == X86ISD::KSHIFTR) {
35434       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
35435         unsigned C1 = Src.getConstantOperandVal(1);
35436         unsigned NewOpc = X86ISD::KSHIFTL;
35437         int Diff = ShiftAmt - C1;
35438         if (Diff < 0) {
35439           Diff = -Diff;
35440           NewOpc = X86ISD::KSHIFTR;
35441         }
35442 
35443         SDLoc dl(Op);
35444         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
35445         return TLO.CombineTo(
35446             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
35447       }
35448     }
35449 
35450     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
35451     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
35452                                    Depth + 1))
35453       return true;
35454 
35455     KnownUndef <<= ShiftAmt;
35456     KnownZero <<= ShiftAmt;
35457     KnownZero.setLowBits(ShiftAmt);
35458     break;
35459   }
35460   case X86ISD::KSHIFTR: {
35461     SDValue Src = Op.getOperand(0);
35462     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
35463     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
35464     unsigned ShiftAmt = Amt->getZExtValue();
35465 
35466     if (ShiftAmt == 0)
35467       return TLO.CombineTo(Op, Src);
35468 
35469     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
35470     // single shift.  We can do this if the top bits (which are shifted
35471     // out) are never demanded.
35472     if (Src.getOpcode() == X86ISD::KSHIFTL) {
35473       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
35474         unsigned C1 = Src.getConstantOperandVal(1);
35475         unsigned NewOpc = X86ISD::KSHIFTR;
35476         int Diff = ShiftAmt - C1;
35477         if (Diff < 0) {
35478           Diff = -Diff;
35479           NewOpc = X86ISD::KSHIFTL;
35480         }
35481 
35482         SDLoc dl(Op);
35483         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
35484         return TLO.CombineTo(
35485             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
35486       }
35487     }
35488 
35489     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
35490     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
35491                                    Depth + 1))
35492       return true;
35493 
35494     KnownUndef.lshrInPlace(ShiftAmt);
35495     KnownZero.lshrInPlace(ShiftAmt);
35496     KnownZero.setHighBits(ShiftAmt);
35497     break;
35498   }
35499   case X86ISD::CVTSI2P:
35500   case X86ISD::CVTUI2P: {
35501     SDValue Src = Op.getOperand(0);
35502     MVT SrcVT = Src.getSimpleValueType();
35503     APInt SrcUndef, SrcZero;
35504     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
35505     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
35506                                    Depth + 1))
35507       return true;
35508     break;
35509   }
35510   case X86ISD::PACKSS:
35511   case X86ISD::PACKUS: {
35512     SDValue N0 = Op.getOperand(0);
35513     SDValue N1 = Op.getOperand(1);
35514 
35515     APInt DemandedLHS, DemandedRHS;
35516     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
35517 
35518     APInt SrcUndef, SrcZero;
35519     if (SimplifyDemandedVectorElts(N0, DemandedLHS, SrcUndef, SrcZero, TLO,
35520                                    Depth + 1))
35521       return true;
35522     if (SimplifyDemandedVectorElts(N1, DemandedRHS, SrcUndef, SrcZero, TLO,
35523                                    Depth + 1))
35524       return true;
35525 
35526     // Aggressively peek through ops to get at the demanded elts.
35527     // TODO - we should do this for all target/faux shuffles ops.
35528     if (!DemandedElts.isAllOnesValue()) {
35529       APInt DemandedSrcBits =
35530           APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
35531       SDValue NewN0 = SimplifyMultipleUseDemandedBits(
35532           N0, DemandedSrcBits, DemandedLHS, TLO.DAG, Depth + 1);
35533       SDValue NewN1 = SimplifyMultipleUseDemandedBits(
35534           N1, DemandedSrcBits, DemandedRHS, TLO.DAG, Depth + 1);
35535       if (NewN0 || NewN1) {
35536         NewN0 = NewN0 ? NewN0 : N0;
35537         NewN1 = NewN1 ? NewN1 : N1;
35538         return TLO.CombineTo(Op,
35539                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
35540       }
35541     }
35542     break;
35543   }
35544   case X86ISD::HADD:
35545   case X86ISD::HSUB:
35546   case X86ISD::FHADD:
35547   case X86ISD::FHSUB: {
35548     APInt DemandedLHS, DemandedRHS;
35549     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
35550 
35551     APInt LHSUndef, LHSZero;
35552     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, LHSUndef,
35553                                    LHSZero, TLO, Depth + 1))
35554       return true;
35555     APInt RHSUndef, RHSZero;
35556     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, RHSUndef,
35557                                    RHSZero, TLO, Depth + 1))
35558       return true;
35559     break;
35560   }
35561   case X86ISD::VTRUNC:
35562   case X86ISD::VTRUNCS:
35563   case X86ISD::VTRUNCUS: {
35564     SDValue Src = Op.getOperand(0);
35565     MVT SrcVT = Src.getSimpleValueType();
35566     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
35567     APInt SrcUndef, SrcZero;
35568     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
35569                                    Depth + 1))
35570       return true;
35571     KnownZero = SrcZero.zextOrTrunc(NumElts);
35572     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
35573     break;
35574   }
35575   case X86ISD::BLENDV: {
35576     APInt SelUndef, SelZero;
35577     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
35578                                    SelZero, TLO, Depth + 1))
35579       return true;
35580 
35581     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
35582     APInt LHSUndef, LHSZero;
35583     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
35584                                    LHSZero, TLO, Depth + 1))
35585       return true;
35586 
35587     APInt RHSUndef, RHSZero;
35588     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
35589                                    RHSZero, TLO, Depth + 1))
35590       return true;
35591 
35592     KnownZero = LHSZero & RHSZero;
35593     KnownUndef = LHSUndef & RHSUndef;
35594     break;
35595   }
35596   case X86ISD::VBROADCAST: {
35597     SDValue Src = Op.getOperand(0);
35598     MVT SrcVT = Src.getSimpleValueType();
35599     if (!SrcVT.isVector())
35600       return false;
35601     // Don't bother broadcasting if we just need the 0'th element.
35602     if (DemandedElts == 1) {
35603       if (Src.getValueType() != VT)
35604         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
35605                              SDLoc(Op));
35606       return TLO.CombineTo(Op, Src);
35607     }
35608     APInt SrcUndef, SrcZero;
35609     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
35610     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
35611                                    Depth + 1))
35612       return true;
35613     break;
35614   }
35615   case X86ISD::VPERMV: {
35616     SDValue Mask = Op.getOperand(0);
35617     APInt MaskUndef, MaskZero;
35618     if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
35619                                    Depth + 1))
35620       return true;
35621     break;
35622   }
35623   case X86ISD::PSHUFB:
35624   case X86ISD::VPERMV3:
35625   case X86ISD::VPERMILPV: {
35626     SDValue Mask = Op.getOperand(1);
35627     APInt MaskUndef, MaskZero;
35628     if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
35629                                    Depth + 1))
35630       return true;
35631     break;
35632   }
35633   case X86ISD::VPPERM:
35634   case X86ISD::VPERMIL2: {
35635     SDValue Mask = Op.getOperand(2);
35636     APInt MaskUndef, MaskZero;
35637     if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
35638                                    Depth + 1))
35639       return true;
35640     break;
35641   }
35642   }
35643 
35644   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
35645   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
35646   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
35647   if ((VT.is256BitVector() || VT.is512BitVector()) &&
35648       DemandedElts.lshr(NumElts / 2) == 0) {
35649     unsigned SizeInBits = VT.getSizeInBits();
35650     unsigned ExtSizeInBits = SizeInBits / 2;
35651 
35652     // See if 512-bit ops only use the bottom 128-bits.
35653     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
35654       ExtSizeInBits = SizeInBits / 4;
35655 
35656     switch (Opc) {
35657       // Zero upper elements.
35658     case X86ISD::VZEXT_MOVL: {
35659       SDLoc DL(Op);
35660       SDValue Ext0 =
35661           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
35662       SDValue ExtOp =
35663           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0);
35664       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
35665       SDValue Insert =
35666           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
35667       return TLO.CombineTo(Op, Insert);
35668     }
35669       // Subvector broadcast.
35670     case X86ISD::SUBV_BROADCAST: {
35671       SDLoc DL(Op);
35672       SDValue Src = Op.getOperand(0);
35673       if (Src.getValueSizeInBits() > ExtSizeInBits)
35674         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
35675       else if (Src.getValueSizeInBits() < ExtSizeInBits) {
35676         MVT SrcSVT = Src.getSimpleValueType().getScalarType();
35677         MVT SrcVT =
35678             MVT::getVectorVT(SrcSVT, ExtSizeInBits / SrcSVT.getSizeInBits());
35679         Src = TLO.DAG.getNode(X86ISD::SUBV_BROADCAST, DL, SrcVT, Src);
35680       }
35681       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Src, 0,
35682                                                TLO.DAG, DL, ExtSizeInBits));
35683     }
35684       // Byte shifts by immediate.
35685     case X86ISD::VSHLDQ:
35686     case X86ISD::VSRLDQ:
35687       // Shift by uniform.
35688     case X86ISD::VSHL:
35689     case X86ISD::VSRL:
35690     case X86ISD::VSRA:
35691       // Shift by immediate.
35692     case X86ISD::VSHLI:
35693     case X86ISD::VSRLI:
35694     case X86ISD::VSRAI: {
35695       SDLoc DL(Op);
35696       SDValue Ext0 =
35697           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
35698       SDValue ExtOp =
35699           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
35700       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
35701       SDValue Insert =
35702           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
35703       return TLO.CombineTo(Op, Insert);
35704     }
35705     case X86ISD::VPERMI: {
35706       // Simplify PERMPD/PERMQ to extract_subvector.
35707       // TODO: This should be done in shuffle combining.
35708       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
35709         SmallVector<int, 4> Mask;
35710         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
35711         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
35712           SDLoc DL(Op);
35713           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
35714           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
35715           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
35716           return TLO.CombineTo(Op, Insert);
35717         }
35718       }
35719       break;
35720     }
35721       // Target Shuffles.
35722     case X86ISD::PSHUFB:
35723     case X86ISD::UNPCKL:
35724     case X86ISD::UNPCKH:
35725       // Saturated Packs.
35726     case X86ISD::PACKSS:
35727     case X86ISD::PACKUS:
35728       // Horizontal Ops.
35729     case X86ISD::HADD:
35730     case X86ISD::HSUB:
35731     case X86ISD::FHADD:
35732     case X86ISD::FHSUB: {
35733       SDLoc DL(Op);
35734       MVT ExtVT = VT.getSimpleVT();
35735       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
35736                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
35737       SDValue Ext0 =
35738           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
35739       SDValue Ext1 =
35740           extractSubVector(Op.getOperand(1), 0, TLO.DAG, DL, ExtSizeInBits);
35741       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ext0, Ext1);
35742       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
35743       SDValue Insert =
35744           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
35745       return TLO.CombineTo(Op, Insert);
35746     }
35747     }
35748   }
35749 
35750   // Get target/faux shuffle mask.
35751   APInt OpUndef, OpZero;
35752   SmallVector<int, 64> OpMask;
35753   SmallVector<SDValue, 2> OpInputs;
35754   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
35755                               OpZero, TLO.DAG, Depth, false))
35756     return false;
35757 
35758   // Shuffle inputs must be the same size as the result.
35759   if (OpMask.size() != (unsigned)NumElts ||
35760       llvm::any_of(OpInputs, [VT](SDValue V) {
35761         return VT.getSizeInBits() != V.getValueSizeInBits() ||
35762                !V.getValueType().isVector();
35763       }))
35764     return false;
35765 
35766   KnownZero = OpZero;
35767   KnownUndef = OpUndef;
35768 
35769   // Check if shuffle mask can be simplified to undef/zero/identity.
35770   int NumSrcs = OpInputs.size();
35771   for (int i = 0; i != NumElts; ++i)
35772     if (!DemandedElts[i])
35773       OpMask[i] = SM_SentinelUndef;
35774 
35775   if (isUndefInRange(OpMask, 0, NumElts)) {
35776     KnownUndef.setAllBits();
35777     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
35778   }
35779   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
35780     KnownZero.setAllBits();
35781     return TLO.CombineTo(
35782         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
35783   }
35784   for (int Src = 0; Src != NumSrcs; ++Src)
35785     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
35786       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
35787 
35788   // Attempt to simplify inputs.
35789   for (int Src = 0; Src != NumSrcs; ++Src) {
35790     // TODO: Support inputs of different types.
35791     if (OpInputs[Src].getValueType() != VT)
35792       continue;
35793 
35794     int Lo = Src * NumElts;
35795     APInt SrcElts = APInt::getNullValue(NumElts);
35796     for (int i = 0; i != NumElts; ++i)
35797       if (DemandedElts[i]) {
35798         int M = OpMask[i] - Lo;
35799         if (0 <= M && M < NumElts)
35800           SrcElts.setBit(M);
35801       }
35802 
35803     // TODO - Propagate input undef/zero elts.
35804     APInt SrcUndef, SrcZero;
35805     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
35806                                    TLO, Depth + 1))
35807       return true;
35808   }
35809 
35810   // If we don't demand all elements, then attempt to combine to a simpler
35811   // shuffle.
35812   // TODO: Handle other depths, but first we need to handle the fact that
35813   // it might combine to the same shuffle.
35814   if (!DemandedElts.isAllOnesValue() && Depth == 0) {
35815     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
35816     for (int i = 0; i != NumElts; ++i)
35817       if (DemandedElts[i])
35818         DemandedMask[i] = i;
35819 
35820     SDValue NewShuffle = combineX86ShufflesRecursively(
35821         {Op}, 0, Op, DemandedMask, {}, Depth, /*HasVarMask*/ false,
35822         /*AllowVarMask*/ true, TLO.DAG, Subtarget);
35823     if (NewShuffle)
35824       return TLO.CombineTo(Op, NewShuffle);
35825   }
35826 
35827   return false;
35828 }
35829 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const35830 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
35831     SDValue Op, const APInt &OriginalDemandedBits,
35832     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
35833     unsigned Depth) const {
35834   EVT VT = Op.getValueType();
35835   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
35836   unsigned Opc = Op.getOpcode();
35837   switch(Opc) {
35838   case X86ISD::PMULDQ:
35839   case X86ISD::PMULUDQ: {
35840     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
35841     KnownBits KnownOp;
35842     SDValue LHS = Op.getOperand(0);
35843     SDValue RHS = Op.getOperand(1);
35844     // FIXME: Can we bound this better?
35845     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
35846     if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
35847                              TLO, Depth + 1))
35848       return true;
35849     if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
35850                              TLO, Depth + 1))
35851       return true;
35852 
35853     // Aggressively peek through ops to get at the demanded low bits.
35854     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
35855         LHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
35856     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
35857         RHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
35858     if (DemandedLHS || DemandedRHS) {
35859       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
35860       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
35861       return TLO.CombineTo(
35862           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
35863     }
35864     break;
35865   }
35866   case X86ISD::VSHLI: {
35867     SDValue Op0 = Op.getOperand(0);
35868 
35869     unsigned ShAmt = Op.getConstantOperandVal(1);
35870     if (ShAmt >= BitWidth)
35871       break;
35872 
35873     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
35874 
35875     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
35876     // single shift.  We can do this if the bottom bits (which are shifted
35877     // out) are never demanded.
35878     if (Op0.getOpcode() == X86ISD::VSRLI &&
35879         OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
35880       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
35881       if (Shift2Amt < BitWidth) {
35882         int Diff = ShAmt - Shift2Amt;
35883         if (Diff == 0)
35884           return TLO.CombineTo(Op, Op0.getOperand(0));
35885 
35886         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
35887         SDValue NewShift = TLO.DAG.getNode(
35888             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
35889             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
35890         return TLO.CombineTo(Op, NewShift);
35891       }
35892     }
35893 
35894     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
35895                              TLO, Depth + 1))
35896       return true;
35897 
35898     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
35899     Known.Zero <<= ShAmt;
35900     Known.One <<= ShAmt;
35901 
35902     // Low bits known zero.
35903     Known.Zero.setLowBits(ShAmt);
35904     break;
35905   }
35906   case X86ISD::VSRLI: {
35907     unsigned ShAmt = Op.getConstantOperandVal(1);
35908     if (ShAmt >= BitWidth)
35909       break;
35910 
35911     APInt DemandedMask = OriginalDemandedBits << ShAmt;
35912 
35913     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
35914                              OriginalDemandedElts, Known, TLO, Depth + 1))
35915       return true;
35916 
35917     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
35918     Known.Zero.lshrInPlace(ShAmt);
35919     Known.One.lshrInPlace(ShAmt);
35920 
35921     // High bits known zero.
35922     Known.Zero.setHighBits(ShAmt);
35923     break;
35924   }
35925   case X86ISD::VSRAI: {
35926     SDValue Op0 = Op.getOperand(0);
35927     SDValue Op1 = Op.getOperand(1);
35928 
35929     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
35930     if (ShAmt >= BitWidth)
35931       break;
35932 
35933     APInt DemandedMask = OriginalDemandedBits << ShAmt;
35934 
35935     // If we just want the sign bit then we don't need to shift it.
35936     if (OriginalDemandedBits.isSignMask())
35937       return TLO.CombineTo(Op, Op0);
35938 
35939     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
35940     if (Op0.getOpcode() == X86ISD::VSHLI &&
35941         Op.getOperand(1) == Op0.getOperand(1)) {
35942       SDValue Op00 = Op0.getOperand(0);
35943       unsigned NumSignBits =
35944           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
35945       if (ShAmt < NumSignBits)
35946         return TLO.CombineTo(Op, Op00);
35947     }
35948 
35949     // If any of the demanded bits are produced by the sign extension, we also
35950     // demand the input sign bit.
35951     if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
35952       DemandedMask.setSignBit();
35953 
35954     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
35955                              TLO, Depth + 1))
35956       return true;
35957 
35958     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
35959     Known.Zero.lshrInPlace(ShAmt);
35960     Known.One.lshrInPlace(ShAmt);
35961 
35962     // If the input sign bit is known to be zero, or if none of the top bits
35963     // are demanded, turn this into an unsigned shift right.
35964     if (Known.Zero[BitWidth - ShAmt - 1] ||
35965         OriginalDemandedBits.countLeadingZeros() >= ShAmt)
35966       return TLO.CombineTo(
35967           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
35968 
35969     // High bits are known one.
35970     if (Known.One[BitWidth - ShAmt - 1])
35971       Known.One.setHighBits(ShAmt);
35972     break;
35973   }
35974   case X86ISD::PEXTRB:
35975   case X86ISD::PEXTRW: {
35976     SDValue Vec = Op.getOperand(0);
35977     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
35978     MVT VecVT = Vec.getSimpleValueType();
35979     unsigned NumVecElts = VecVT.getVectorNumElements();
35980 
35981     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
35982       unsigned Idx = CIdx->getZExtValue();
35983       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
35984 
35985       // If we demand no bits from the vector then we must have demanded
35986       // bits from the implict zext - simplify to zero.
35987       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
35988       if (DemandedVecBits == 0)
35989         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
35990 
35991       APInt KnownUndef, KnownZero;
35992       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
35993       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
35994                                      KnownZero, TLO, Depth + 1))
35995         return true;
35996 
35997       KnownBits KnownVec;
35998       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
35999                                KnownVec, TLO, Depth + 1))
36000         return true;
36001 
36002       if (SDValue V = SimplifyMultipleUseDemandedBits(
36003               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
36004         return TLO.CombineTo(
36005             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
36006 
36007       Known = KnownVec.zext(BitWidth, true);
36008       return false;
36009     }
36010     break;
36011   }
36012   case X86ISD::PINSRB:
36013   case X86ISD::PINSRW: {
36014     SDValue Vec = Op.getOperand(0);
36015     SDValue Scl = Op.getOperand(1);
36016     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
36017     MVT VecVT = Vec.getSimpleValueType();
36018 
36019     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
36020       unsigned Idx = CIdx->getZExtValue();
36021       if (!OriginalDemandedElts[Idx])
36022         return TLO.CombineTo(Op, Vec);
36023 
36024       KnownBits KnownVec;
36025       APInt DemandedVecElts(OriginalDemandedElts);
36026       DemandedVecElts.clearBit(Idx);
36027       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
36028                                KnownVec, TLO, Depth + 1))
36029         return true;
36030 
36031       KnownBits KnownScl;
36032       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
36033       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
36034       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
36035         return true;
36036 
36037       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
36038       Known.One = KnownVec.One & KnownScl.One;
36039       Known.Zero = KnownVec.Zero & KnownScl.Zero;
36040       return false;
36041     }
36042     break;
36043   }
36044   case X86ISD::PACKSS:
36045     // PACKSS saturates to MIN/MAX integer values. So if we just want the
36046     // sign bit then we can just ask for the source operands sign bit.
36047     // TODO - add known bits handling.
36048     if (OriginalDemandedBits.isSignMask()) {
36049       APInt DemandedLHS, DemandedRHS;
36050       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
36051 
36052       KnownBits KnownLHS, KnownRHS;
36053       APInt SignMask = APInt::getSignMask(BitWidth * 2);
36054       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
36055                                KnownLHS, TLO, Depth + 1))
36056         return true;
36057       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
36058                                KnownRHS, TLO, Depth + 1))
36059         return true;
36060     }
36061     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
36062     break;
36063   case X86ISD::PCMPGT:
36064     // icmp sgt(0, R) == ashr(R, BitWidth-1).
36065     // iff we only need the sign bit then we can use R directly.
36066     if (OriginalDemandedBits.isSignMask() &&
36067         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
36068       return TLO.CombineTo(Op, Op.getOperand(1));
36069     break;
36070   case X86ISD::MOVMSK: {
36071     SDValue Src = Op.getOperand(0);
36072     MVT SrcVT = Src.getSimpleValueType();
36073     unsigned SrcBits = SrcVT.getScalarSizeInBits();
36074     unsigned NumElts = SrcVT.getVectorNumElements();
36075 
36076     // If we don't need the sign bits at all just return zero.
36077     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
36078       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
36079 
36080     // Only demand the vector elements of the sign bits we need.
36081     APInt KnownUndef, KnownZero;
36082     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
36083     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
36084                                    TLO, Depth + 1))
36085       return true;
36086 
36087     Known.Zero = KnownZero.zextOrSelf(BitWidth);
36088     Known.Zero.setHighBits(BitWidth - NumElts);
36089 
36090     // MOVMSK only uses the MSB from each vector element.
36091     KnownBits KnownSrc;
36092     if (SimplifyDemandedBits(Src, APInt::getSignMask(SrcBits), DemandedElts,
36093                              KnownSrc, TLO, Depth + 1))
36094       return true;
36095 
36096     if (KnownSrc.One[SrcBits - 1])
36097       Known.One.setLowBits(NumElts);
36098     else if (KnownSrc.Zero[SrcBits - 1])
36099       Known.Zero.setLowBits(NumElts);
36100     return false;
36101   }
36102   }
36103 
36104   return TargetLowering::SimplifyDemandedBitsForTargetNode(
36105       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
36106 }
36107 
SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,SelectionDAG & DAG,unsigned Depth) const36108 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
36109     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
36110     SelectionDAG &DAG, unsigned Depth) const {
36111   int NumElts = DemandedElts.getBitWidth();
36112   unsigned Opc = Op.getOpcode();
36113   EVT VT = Op.getValueType();
36114 
36115   switch (Opc) {
36116   case X86ISD::PINSRB:
36117   case X86ISD::PINSRW: {
36118     // If we don't demand the inserted element, return the base vector.
36119     SDValue Vec = Op.getOperand(0);
36120     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
36121     MVT VecVT = Vec.getSimpleValueType();
36122     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
36123         !DemandedElts[CIdx->getZExtValue()])
36124       return Vec;
36125      break;
36126   }
36127   case X86ISD::PCMPGT:
36128     // icmp sgt(0, R) == ashr(R, BitWidth-1).
36129     // iff we only need the sign bit then we can use R directly.
36130     if (DemandedBits.isSignMask() &&
36131         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
36132       return Op.getOperand(1);
36133     break;
36134   }
36135 
36136   APInt ShuffleUndef, ShuffleZero;
36137   SmallVector<int, 16> ShuffleMask;
36138   SmallVector<SDValue, 2> ShuffleOps;
36139   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
36140                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
36141     // If all the demanded elts are from one operand and are inline,
36142     // then we can use the operand directly.
36143     int NumOps = ShuffleOps.size();
36144     if (ShuffleMask.size() == (unsigned)NumElts &&
36145         llvm::all_of(ShuffleOps, [VT](SDValue V) {
36146           return VT.getSizeInBits() == V.getValueSizeInBits();
36147         })) {
36148 
36149       if (DemandedElts.isSubsetOf(ShuffleUndef))
36150         return DAG.getUNDEF(VT);
36151       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
36152         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
36153 
36154       // Bitmask that indicates which ops have only been accessed 'inline'.
36155       APInt IdentityOp = APInt::getAllOnesValue(NumOps);
36156       for (int i = 0; i != NumElts; ++i) {
36157         int M = ShuffleMask[i];
36158         if (!DemandedElts[i] || ShuffleUndef[i])
36159           continue;
36160         int Op = M / NumElts;
36161         int Index = M % NumElts;
36162         if (M < 0 || Index != i) {
36163           IdentityOp.clearAllBits();
36164           break;
36165         }
36166         IdentityOp &= APInt::getOneBitSet(NumOps, Op);
36167         if (IdentityOp == 0)
36168           break;
36169       }
36170       assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&
36171              "Multiple identity shuffles detected");
36172 
36173       if (IdentityOp != 0)
36174         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
36175     }
36176   }
36177 
36178   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
36179       Op, DemandedBits, DemandedElts, DAG, Depth);
36180 }
36181 
36182 // Helper to peek through bitops/setcc to determine size of source vector.
36183 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
checkBitcastSrcVectorSize(SDValue Src,unsigned Size)36184 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size) {
36185   switch (Src.getOpcode()) {
36186   case ISD::SETCC:
36187     return Src.getOperand(0).getValueSizeInBits() == Size;
36188   case ISD::AND:
36189   case ISD::XOR:
36190   case ISD::OR:
36191     return checkBitcastSrcVectorSize(Src.getOperand(0), Size) &&
36192            checkBitcastSrcVectorSize(Src.getOperand(1), Size);
36193   }
36194   return false;
36195 }
36196 
36197 // Helper to push sign extension of vXi1 SETCC result through bitops.
signExtendBitcastSrcVector(SelectionDAG & DAG,EVT SExtVT,SDValue Src,const SDLoc & DL)36198 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
36199                                           SDValue Src, const SDLoc &DL) {
36200   switch (Src.getOpcode()) {
36201   case ISD::SETCC:
36202     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
36203   case ISD::AND:
36204   case ISD::XOR:
36205   case ISD::OR:
36206     return DAG.getNode(
36207         Src.getOpcode(), DL, SExtVT,
36208         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
36209         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
36210   }
36211   llvm_unreachable("Unexpected node type for vXi1 sign extension");
36212 }
36213 
36214 // Try to match patterns such as
36215 // (i16 bitcast (v16i1 x))
36216 // ->
36217 // (i16 movmsk (16i8 sext (v16i1 x)))
36218 // before the illegal vector is scalarized on subtargets that don't have legal
36219 // vxi1 types.
combineBitcastvxi1(SelectionDAG & DAG,EVT VT,SDValue Src,const SDLoc & DL,const X86Subtarget & Subtarget)36220 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
36221                                   const SDLoc &DL,
36222                                   const X86Subtarget &Subtarget) {
36223   EVT SrcVT = Src.getValueType();
36224   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
36225     return SDValue();
36226 
36227   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
36228   // movmskb even with avx512. This will be better than truncating to vXi1 and
36229   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
36230   // vpcmpeqb/vpcmpgtb.
36231   bool IsTruncated = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
36232                      (Src.getOperand(0).getValueType() == MVT::v16i8 ||
36233                       Src.getOperand(0).getValueType() == MVT::v32i8 ||
36234                       Src.getOperand(0).getValueType() == MVT::v64i8);
36235 
36236   // With AVX512 vxi1 types are legal and we prefer using k-regs.
36237   // MOVMSK is supported in SSE2 or later.
36238   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !IsTruncated))
36239     return SDValue();
36240 
36241   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
36242   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
36243   // v8i16 and v16i16.
36244   // For these two cases, we can shuffle the upper element bytes to a
36245   // consecutive sequence at the start of the vector and treat the results as
36246   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
36247   // for v16i16 this is not the case, because the shuffle is expensive, so we
36248   // avoid sign-extending to this type entirely.
36249   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
36250   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
36251   MVT SExtVT;
36252   bool PropagateSExt = false;
36253   switch (SrcVT.getSimpleVT().SimpleTy) {
36254   default:
36255     return SDValue();
36256   case MVT::v2i1:
36257     SExtVT = MVT::v2i64;
36258     break;
36259   case MVT::v4i1:
36260     SExtVT = MVT::v4i32;
36261     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
36262     // sign-extend to a 256-bit operation to avoid truncation.
36263     if (Subtarget.hasAVX() && checkBitcastSrcVectorSize(Src, 256)) {
36264       SExtVT = MVT::v4i64;
36265       PropagateSExt = true;
36266     }
36267     break;
36268   case MVT::v8i1:
36269     SExtVT = MVT::v8i16;
36270     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
36271     // sign-extend to a 256-bit operation to match the compare.
36272     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
36273     // 256-bit because the shuffle is cheaper than sign extending the result of
36274     // the compare.
36275     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256) ||
36276                                checkBitcastSrcVectorSize(Src, 512))) {
36277       SExtVT = MVT::v8i32;
36278       PropagateSExt = true;
36279     }
36280     break;
36281   case MVT::v16i1:
36282     SExtVT = MVT::v16i8;
36283     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
36284     // it is not profitable to sign-extend to 256-bit because this will
36285     // require an extra cross-lane shuffle which is more expensive than
36286     // truncating the result of the compare to 128-bits.
36287     break;
36288   case MVT::v32i1:
36289     SExtVT = MVT::v32i8;
36290     break;
36291   case MVT::v64i1:
36292     // If we have AVX512F, but not AVX512BW and the input is truncated from
36293     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
36294     if (Subtarget.hasAVX512() && !Subtarget.hasBWI()) {
36295       SExtVT = MVT::v64i8;
36296       break;
36297     }
36298     return SDValue();
36299   };
36300 
36301   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
36302                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
36303 
36304   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
36305     V = getPMOVMSKB(DL, V, DAG, Subtarget);
36306   } else {
36307     if (SExtVT == MVT::v8i16)
36308       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
36309                       DAG.getUNDEF(MVT::v8i16));
36310     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
36311   }
36312 
36313   EVT IntVT =
36314       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
36315   V = DAG.getZExtOrTrunc(V, DL, IntVT);
36316   return DAG.getBitcast(VT, V);
36317 }
36318 
36319 // Convert a vXi1 constant build vector to the same width scalar integer.
combinevXi1ConstantToInteger(SDValue Op,SelectionDAG & DAG)36320 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
36321   EVT SrcVT = Op.getValueType();
36322   assert(SrcVT.getVectorElementType() == MVT::i1 &&
36323          "Expected a vXi1 vector");
36324   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
36325          "Expected a constant build vector");
36326 
36327   APInt Imm(SrcVT.getVectorNumElements(), 0);
36328   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
36329     SDValue In = Op.getOperand(Idx);
36330     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
36331       Imm.setBit(Idx);
36332   }
36333   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
36334   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
36335 }
36336 
combineCastedMaskArithmetic(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36337 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
36338                                            TargetLowering::DAGCombinerInfo &DCI,
36339                                            const X86Subtarget &Subtarget) {
36340   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
36341 
36342   if (!DCI.isBeforeLegalizeOps())
36343     return SDValue();
36344 
36345   // Only do this if we have k-registers.
36346   if (!Subtarget.hasAVX512())
36347     return SDValue();
36348 
36349   EVT DstVT = N->getValueType(0);
36350   SDValue Op = N->getOperand(0);
36351   EVT SrcVT = Op.getValueType();
36352 
36353   if (!Op.hasOneUse())
36354     return SDValue();
36355 
36356   // Look for logic ops.
36357   if (Op.getOpcode() != ISD::AND &&
36358       Op.getOpcode() != ISD::OR &&
36359       Op.getOpcode() != ISD::XOR)
36360     return SDValue();
36361 
36362   // Make sure we have a bitcast between mask registers and a scalar type.
36363   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
36364         DstVT.isScalarInteger()) &&
36365       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
36366         SrcVT.isScalarInteger()))
36367     return SDValue();
36368 
36369   SDValue LHS = Op.getOperand(0);
36370   SDValue RHS = Op.getOperand(1);
36371 
36372   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
36373       LHS.getOperand(0).getValueType() == DstVT)
36374     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
36375                        DAG.getBitcast(DstVT, RHS));
36376 
36377   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
36378       RHS.getOperand(0).getValueType() == DstVT)
36379     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
36380                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
36381 
36382   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
36383   // Most of these have to move a constant from the scalar domain anyway.
36384   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
36385     RHS = combinevXi1ConstantToInteger(RHS, DAG);
36386     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
36387                        DAG.getBitcast(DstVT, LHS), RHS);
36388   }
36389 
36390   return SDValue();
36391 }
36392 
createMMXBuildVector(BuildVectorSDNode * BV,SelectionDAG & DAG,const X86Subtarget & Subtarget)36393 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
36394                                     const X86Subtarget &Subtarget) {
36395   SDLoc DL(BV);
36396   unsigned NumElts = BV->getNumOperands();
36397   SDValue Splat = BV->getSplatValue();
36398 
36399   // Build MMX element from integer GPR or SSE float values.
36400   auto CreateMMXElement = [&](SDValue V) {
36401     if (V.isUndef())
36402       return DAG.getUNDEF(MVT::x86mmx);
36403     if (V.getValueType().isFloatingPoint()) {
36404       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
36405         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
36406         V = DAG.getBitcast(MVT::v2i64, V);
36407         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
36408       }
36409       V = DAG.getBitcast(MVT::i32, V);
36410     } else {
36411       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
36412     }
36413     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
36414   };
36415 
36416   // Convert build vector ops to MMX data in the bottom elements.
36417   SmallVector<SDValue, 8> Ops;
36418 
36419   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
36420   if (Splat) {
36421     if (Splat.isUndef())
36422       return DAG.getUNDEF(MVT::x86mmx);
36423 
36424     Splat = CreateMMXElement(Splat);
36425 
36426     if (Subtarget.hasSSE1()) {
36427       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
36428       if (NumElts == 8)
36429         Splat = DAG.getNode(
36430             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
36431             DAG.getConstant(Intrinsic::x86_mmx_punpcklbw, DL, MVT::i32), Splat,
36432             Splat);
36433 
36434       // Use PSHUFW to repeat 16-bit elements.
36435       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
36436       return DAG.getNode(
36437           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
36438           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL, MVT::i32),
36439           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
36440     }
36441     Ops.append(NumElts, Splat);
36442   } else {
36443     for (unsigned i = 0; i != NumElts; ++i)
36444       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
36445   }
36446 
36447   // Use tree of PUNPCKLs to build up general MMX vector.
36448   while (Ops.size() > 1) {
36449     unsigned NumOps = Ops.size();
36450     unsigned IntrinOp =
36451         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
36452                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
36453                                     : Intrinsic::x86_mmx_punpcklbw));
36454     SDValue Intrin = DAG.getConstant(IntrinOp, DL, MVT::i32);
36455     for (unsigned i = 0; i != NumOps; i += 2)
36456       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
36457                                Ops[i], Ops[i + 1]);
36458     Ops.resize(NumOps / 2);
36459   }
36460 
36461   return Ops[0];
36462 }
36463 
combineBitcast(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36464 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
36465                               TargetLowering::DAGCombinerInfo &DCI,
36466                               const X86Subtarget &Subtarget) {
36467   SDValue N0 = N->getOperand(0);
36468   EVT VT = N->getValueType(0);
36469   EVT SrcVT = N0.getValueType();
36470 
36471   // Try to match patterns such as
36472   // (i16 bitcast (v16i1 x))
36473   // ->
36474   // (i16 movmsk (16i8 sext (v16i1 x)))
36475   // before the setcc result is scalarized on subtargets that don't have legal
36476   // vxi1 types.
36477   if (DCI.isBeforeLegalize()) {
36478     SDLoc dl(N);
36479     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
36480       return V;
36481 
36482     // Recognize the IR pattern for the movmsk intrinsic under SSE1 befoer type
36483     // legalization destroys the v4i32 type.
36484     if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && SrcVT == MVT::v4i1 &&
36485         VT.isScalarInteger() && N0.getOpcode() == ISD::SETCC &&
36486         N0.getOperand(0).getValueType() == MVT::v4i32 &&
36487         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()) &&
36488         cast<CondCodeSDNode>(N0.getOperand(2))->get() == ISD::SETLT) {
36489       SDValue N00 = N0.getOperand(0);
36490       // Only do this if we can avoid scalarizing the input.
36491       if (ISD::isNormalLoad(N00.getNode()) ||
36492           (N00.getOpcode() == ISD::BITCAST &&
36493            N00.getOperand(0).getValueType() == MVT::v4f32)) {
36494         SDValue V = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32,
36495                                 DAG.getBitcast(MVT::v4f32, N00));
36496         return DAG.getZExtOrTrunc(V, dl, VT);
36497       }
36498     }
36499 
36500     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
36501     // type, widen both sides to avoid a trip through memory.
36502     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
36503         Subtarget.hasAVX512()) {
36504       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
36505       N0 = DAG.getBitcast(MVT::v8i1, N0);
36506       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
36507                          DAG.getIntPtrConstant(0, dl));
36508     }
36509 
36510     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
36511     // type, widen both sides to avoid a trip through memory.
36512     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
36513         Subtarget.hasAVX512()) {
36514       // Use zeros for the widening if we already have some zeroes. This can
36515       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
36516       // stream of this.
36517       // FIXME: It might make sense to detect a concat_vectors with a mix of
36518       // zeroes and undef and turn it into insert_subvector for i1 vectors as
36519       // a separate combine. What we can't do is canonicalize the operands of
36520       // such a concat or we'll get into a loop with SimplifyDemandedBits.
36521       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
36522         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
36523         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
36524           SrcVT = LastOp.getValueType();
36525           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
36526           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
36527           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
36528           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
36529           N0 = DAG.getBitcast(MVT::i8, N0);
36530           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
36531         }
36532       }
36533 
36534       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
36535       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
36536       Ops[0] = N0;
36537       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
36538       N0 = DAG.getBitcast(MVT::i8, N0);
36539       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
36540     }
36541   }
36542 
36543   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
36544   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
36545   // due to insert_subvector legalization on KNL. By promoting the copy to i16
36546   // we can help with known bits propagation from the vXi1 domain to the
36547   // scalar domain.
36548   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
36549       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
36550       N0.getOperand(0).getValueType() == MVT::v16i1 &&
36551       isNullConstant(N0.getOperand(1)))
36552     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
36553                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
36554 
36555   // Combine (bitcast (vbroadcast_load)) -> (vbroadcast_load). The memory VT
36556   // determines // the number of bits loaded. Remaining bits are zero.
36557   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
36558       VT.getScalarSizeInBits() == SrcVT.getScalarSizeInBits()) {
36559     auto *BCast = cast<MemIntrinsicSDNode>(N0);
36560     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36561     SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
36562     SDValue ResNode =
36563         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
36564                                 VT.getVectorElementType(),
36565                                 BCast->getMemOperand());
36566     DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
36567     return ResNode;
36568   }
36569 
36570   // Since MMX types are special and don't usually play with other vector types,
36571   // it's better to handle them early to be sure we emit efficient code by
36572   // avoiding store-load conversions.
36573   if (VT == MVT::x86mmx) {
36574     // Detect MMX constant vectors.
36575     APInt UndefElts;
36576     SmallVector<APInt, 1> EltBits;
36577     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
36578       SDLoc DL(N0);
36579       // Handle zero-extension of i32 with MOVD.
36580       if (EltBits[0].countLeadingZeros() >= 32)
36581         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
36582                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
36583       // Else, bitcast to a double.
36584       // TODO - investigate supporting sext 32-bit immediates on x86_64.
36585       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
36586       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
36587     }
36588 
36589     // Detect bitcasts to x86mmx low word.
36590     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
36591         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
36592         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
36593       bool LowUndef = true, AllUndefOrZero = true;
36594       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
36595         SDValue Op = N0.getOperand(i);
36596         LowUndef &= Op.isUndef() || (i >= e/2);
36597         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
36598       }
36599       if (AllUndefOrZero) {
36600         SDValue N00 = N0.getOperand(0);
36601         SDLoc dl(N00);
36602         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
36603                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
36604         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
36605       }
36606     }
36607 
36608     // Detect bitcasts of 64-bit build vectors and convert to a
36609     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
36610     // lowest element.
36611     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
36612         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
36613          SrcVT == MVT::v8i8))
36614       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
36615 
36616     // Detect bitcasts between element or subvector extraction to x86mmx.
36617     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
36618          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
36619         isNullConstant(N0.getOperand(1))) {
36620       SDValue N00 = N0.getOperand(0);
36621       if (N00.getValueType().is128BitVector())
36622         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
36623                            DAG.getBitcast(MVT::v2i64, N00));
36624     }
36625 
36626     // Detect bitcasts from FP_TO_SINT to x86mmx.
36627     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
36628       SDLoc DL(N0);
36629       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
36630                                 DAG.getUNDEF(MVT::v2i32));
36631       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
36632                          DAG.getBitcast(MVT::v2i64, Res));
36633     }
36634   }
36635 
36636   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
36637   // most of these to scalar anyway.
36638   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
36639       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
36640       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
36641     return combinevXi1ConstantToInteger(N0, DAG);
36642   }
36643 
36644   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
36645       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
36646       isa<ConstantSDNode>(N0)) {
36647     auto *C = cast<ConstantSDNode>(N0);
36648     if (C->isAllOnesValue())
36649       return DAG.getConstant(1, SDLoc(N0), VT);
36650     if (C->isNullValue())
36651       return DAG.getConstant(0, SDLoc(N0), VT);
36652   }
36653 
36654   // Try to remove bitcasts from input and output of mask arithmetic to
36655   // remove GPR<->K-register crossings.
36656   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
36657     return V;
36658 
36659   // Convert a bitcasted integer logic operation that has one bitcasted
36660   // floating-point operand into a floating-point logic operation. This may
36661   // create a load of a constant, but that is cheaper than materializing the
36662   // constant in an integer register and transferring it to an SSE register or
36663   // transferring the SSE operand to integer register and back.
36664   unsigned FPOpcode;
36665   switch (N0.getOpcode()) {
36666     case ISD::AND: FPOpcode = X86ISD::FAND; break;
36667     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
36668     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
36669     default: return SDValue();
36670   }
36671 
36672   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
36673         (Subtarget.hasSSE2() && VT == MVT::f64)))
36674     return SDValue();
36675 
36676   SDValue LogicOp0 = N0.getOperand(0);
36677   SDValue LogicOp1 = N0.getOperand(1);
36678   SDLoc DL0(N0);
36679 
36680   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
36681   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
36682       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).getValueType() == VT &&
36683       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
36684     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
36685     return DAG.getNode(FPOpcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
36686   }
36687   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
36688   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
36689       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).getValueType() == VT &&
36690       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
36691     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
36692     return DAG.getNode(FPOpcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
36693   }
36694 
36695   return SDValue();
36696 }
36697 
36698 // Given a ABS node, detect the following pattern:
36699 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
36700 // This is useful as it is the input into a SAD pattern.
detectZextAbsDiff(const SDValue & Abs,SDValue & Op0,SDValue & Op1)36701 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
36702   SDValue AbsOp1 = Abs->getOperand(0);
36703   if (AbsOp1.getOpcode() != ISD::SUB)
36704     return false;
36705 
36706   Op0 = AbsOp1.getOperand(0);
36707   Op1 = AbsOp1.getOperand(1);
36708 
36709   // Check if the operands of the sub are zero-extended from vectors of i8.
36710   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
36711       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
36712       Op1.getOpcode() != ISD::ZERO_EXTEND ||
36713       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
36714     return false;
36715 
36716   return true;
36717 }
36718 
36719 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
36720 // to these zexts.
createPSADBW(SelectionDAG & DAG,const SDValue & Zext0,const SDValue & Zext1,const SDLoc & DL,const X86Subtarget & Subtarget)36721 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
36722                             const SDValue &Zext1, const SDLoc &DL,
36723                             const X86Subtarget &Subtarget) {
36724   // Find the appropriate width for the PSADBW.
36725   EVT InVT = Zext0.getOperand(0).getValueType();
36726   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
36727 
36728   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
36729   // fill in the missing vector elements with 0.
36730   unsigned NumConcat = RegSize / InVT.getSizeInBits();
36731   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
36732   Ops[0] = Zext0.getOperand(0);
36733   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
36734   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
36735   Ops[0] = Zext1.getOperand(0);
36736   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
36737 
36738   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
36739   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
36740                           ArrayRef<SDValue> Ops) {
36741     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
36742     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
36743   };
36744   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
36745   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
36746                           PSADBWBuilder);
36747 }
36748 
36749 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
36750 // PHMINPOSUW.
combineHorizontalMinMaxResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)36751 static SDValue combineHorizontalMinMaxResult(SDNode *Extract, SelectionDAG &DAG,
36752                                              const X86Subtarget &Subtarget) {
36753   // Bail without SSE41.
36754   if (!Subtarget.hasSSE41())
36755     return SDValue();
36756 
36757   EVT ExtractVT = Extract->getValueType(0);
36758   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
36759     return SDValue();
36760 
36761   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
36762   ISD::NodeType BinOp;
36763   SDValue Src = DAG.matchBinOpReduction(
36764       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
36765   if (!Src)
36766     return SDValue();
36767 
36768   EVT SrcVT = Src.getValueType();
36769   EVT SrcSVT = SrcVT.getScalarType();
36770   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
36771     return SDValue();
36772 
36773   SDLoc DL(Extract);
36774   SDValue MinPos = Src;
36775 
36776   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
36777   while (SrcVT.getSizeInBits() > 128) {
36778     unsigned NumElts = SrcVT.getVectorNumElements();
36779     unsigned NumSubElts = NumElts / 2;
36780     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcSVT, NumSubElts);
36781     unsigned SubSizeInBits = SrcVT.getSizeInBits();
36782     SDValue Lo = extractSubVector(MinPos, 0, DAG, DL, SubSizeInBits);
36783     SDValue Hi = extractSubVector(MinPos, NumSubElts, DAG, DL, SubSizeInBits);
36784     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
36785   }
36786   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
36787           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
36788          "Unexpected value type");
36789 
36790   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
36791   // to flip the value accordingly.
36792   SDValue Mask;
36793   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
36794   if (BinOp == ISD::SMAX)
36795     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
36796   else if (BinOp == ISD::SMIN)
36797     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
36798   else if (BinOp == ISD::UMAX)
36799     Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
36800 
36801   if (Mask)
36802     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
36803 
36804   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
36805   // shuffling each upper element down and insert zeros. This means that the
36806   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
36807   // ready for the PHMINPOS.
36808   if (ExtractVT == MVT::i8) {
36809     SDValue Upper = DAG.getVectorShuffle(
36810         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
36811         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
36812     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
36813   }
36814 
36815   // Perform the PHMINPOS on a v8i16 vector,
36816   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
36817   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
36818   MinPos = DAG.getBitcast(SrcVT, MinPos);
36819 
36820   if (Mask)
36821     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
36822 
36823   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
36824                      DAG.getIntPtrConstant(0, DL));
36825 }
36826 
36827 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
combineHorizontalPredicateResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)36828 static SDValue combineHorizontalPredicateResult(SDNode *Extract,
36829                                                 SelectionDAG &DAG,
36830                                                 const X86Subtarget &Subtarget) {
36831   // Bail without SSE2.
36832   if (!Subtarget.hasSSE2())
36833     return SDValue();
36834 
36835   EVT ExtractVT = Extract->getValueType(0);
36836   unsigned BitWidth = ExtractVT.getSizeInBits();
36837   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
36838       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
36839     return SDValue();
36840 
36841   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
36842   ISD::NodeType BinOp;
36843   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
36844   if (!Match && ExtractVT == MVT::i1)
36845     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
36846   if (!Match)
36847     return SDValue();
36848 
36849   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
36850   // which we can't support here for now.
36851   if (Match.getScalarValueSizeInBits() != BitWidth)
36852     return SDValue();
36853 
36854   SDValue Movmsk;
36855   SDLoc DL(Extract);
36856   EVT MatchVT = Match.getValueType();
36857   unsigned NumElts = MatchVT.getVectorNumElements();
36858   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
36859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36860 
36861   if (ExtractVT == MVT::i1) {
36862     // Special case for (pre-legalization) vXi1 reductions.
36863     if (NumElts > 64 || !isPowerOf2_32(NumElts))
36864       return SDValue();
36865     if (TLI.isTypeLegal(MatchVT)) {
36866       // If this is a legal AVX512 predicate type then we can just bitcast.
36867       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
36868       Movmsk = DAG.getBitcast(MovmskVT, Match);
36869     } else {
36870       // Use combineBitcastvxi1 to create the MOVMSK.
36871       while (NumElts > MaxElts) {
36872         SDValue Lo, Hi;
36873         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
36874         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
36875         NumElts /= 2;
36876       }
36877       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
36878       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
36879     }
36880     if (!Movmsk)
36881       return SDValue();
36882     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
36883   } else {
36884     // Bail with AVX512VL (which uses predicate registers).
36885     if (Subtarget.hasVLX())
36886       return SDValue();
36887 
36888     unsigned MatchSizeInBits = Match.getValueSizeInBits();
36889     if (!(MatchSizeInBits == 128 ||
36890           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
36891       return SDValue();
36892 
36893     // Make sure this isn't a vector of 1 element. The perf win from using
36894     // MOVMSK diminishes with less elements in the reduction, but it is
36895     // generally better to get the comparison over to the GPRs as soon as
36896     // possible to reduce the number of vector ops.
36897     if (Match.getValueType().getVectorNumElements() < 2)
36898       return SDValue();
36899 
36900     // Check that we are extracting a reduction of all sign bits.
36901     if (DAG.ComputeNumSignBits(Match) != BitWidth)
36902       return SDValue();
36903 
36904     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
36905       SDValue Lo, Hi;
36906       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
36907       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
36908       MatchSizeInBits = Match.getValueSizeInBits();
36909     }
36910 
36911     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
36912     MVT MaskSrcVT;
36913     if (64 == BitWidth || 32 == BitWidth)
36914       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
36915                                    MatchSizeInBits / BitWidth);
36916     else
36917       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
36918 
36919     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
36920     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
36921     NumElts = MaskSrcVT.getVectorNumElements();
36922   }
36923   assert((NumElts <= 32 || NumElts == 64) &&
36924          "Not expecting more than 64 elements");
36925 
36926   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
36927   if (BinOp == ISD::XOR) {
36928     // parity -> (AND (CTPOP(MOVMSK X)), 1)
36929     SDValue Mask = DAG.getConstant(1, DL, CmpVT);
36930     SDValue Result = DAG.getNode(ISD::CTPOP, DL, CmpVT, Movmsk);
36931     Result = DAG.getNode(ISD::AND, DL, CmpVT, Result, Mask);
36932     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
36933   }
36934 
36935   SDValue CmpC;
36936   ISD::CondCode CondCode;
36937   if (BinOp == ISD::OR) {
36938     // any_of -> MOVMSK != 0
36939     CmpC = DAG.getConstant(0, DL, CmpVT);
36940     CondCode = ISD::CondCode::SETNE;
36941   } else {
36942     // all_of -> MOVMSK == ((1 << NumElts) - 1)
36943     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
36944                            DL, CmpVT);
36945     CondCode = ISD::CondCode::SETEQ;
36946   }
36947 
36948   // The setcc produces an i8 of 0/1, so extend that to the result width and
36949   // negate to get the final 0/-1 mask value.
36950   EVT SetccVT =
36951       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
36952   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
36953   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
36954   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
36955   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
36956 }
36957 
combineBasicSADPattern(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)36958 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
36959                                       const X86Subtarget &Subtarget) {
36960   // PSADBW is only supported on SSE2 and up.
36961   if (!Subtarget.hasSSE2())
36962     return SDValue();
36963 
36964   // Verify the type we're extracting from is any integer type above i16.
36965   EVT VT = Extract->getOperand(0).getValueType();
36966   if (!VT.isSimple() || !(VT.getVectorElementType().getSizeInBits() > 16))
36967     return SDValue();
36968 
36969   unsigned RegSize = 128;
36970   if (Subtarget.useBWIRegs())
36971     RegSize = 512;
36972   else if (Subtarget.hasAVX())
36973     RegSize = 256;
36974 
36975   // We handle upto v16i* for SSE2 / v32i* for AVX / v64i* for AVX512.
36976   // TODO: We should be able to handle larger vectors by splitting them before
36977   // feeding them into several SADs, and then reducing over those.
36978   if (RegSize / VT.getVectorNumElements() < 8)
36979     return SDValue();
36980 
36981   // Match shuffle + add pyramid.
36982   ISD::NodeType BinOp;
36983   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
36984 
36985   // The operand is expected to be zero extended from i8
36986   // (verified in detectZextAbsDiff).
36987   // In order to convert to i64 and above, additional any/zero/sign
36988   // extend is expected.
36989   // The zero extend from 32 bit has no mathematical effect on the result.
36990   // Also the sign extend is basically zero extend
36991   // (extends the sign bit which is zero).
36992   // So it is correct to skip the sign/zero extend instruction.
36993   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
36994     Root.getOpcode() == ISD::ZERO_EXTEND ||
36995     Root.getOpcode() == ISD::ANY_EXTEND))
36996     Root = Root.getOperand(0);
36997 
36998   // If there was a match, we want Root to be a select that is the root of an
36999   // abs-diff pattern.
37000   if (!Root || Root.getOpcode() != ISD::ABS)
37001     return SDValue();
37002 
37003   // Check whether we have an abs-diff pattern feeding into the select.
37004   SDValue Zext0, Zext1;
37005   if (!detectZextAbsDiff(Root, Zext0, Zext1))
37006     return SDValue();
37007 
37008   // Create the SAD instruction.
37009   SDLoc DL(Extract);
37010   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
37011 
37012   // If the original vector was wider than 8 elements, sum over the results
37013   // in the SAD vector.
37014   unsigned Stages = Log2_32(VT.getVectorNumElements());
37015   MVT SadVT = SAD.getSimpleValueType();
37016   if (Stages > 3) {
37017     unsigned SadElems = SadVT.getVectorNumElements();
37018 
37019     for(unsigned i = Stages - 3; i > 0; --i) {
37020       SmallVector<int, 16> Mask(SadElems, -1);
37021       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
37022         Mask[j] = MaskEnd + j;
37023 
37024       SDValue Shuffle =
37025           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
37026       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
37027     }
37028   }
37029 
37030   MVT Type = Extract->getSimpleValueType(0);
37031   unsigned TypeSizeInBits = Type.getSizeInBits();
37032   // Return the lowest TypeSizeInBits bits.
37033   MVT ResVT = MVT::getVectorVT(Type, SadVT.getSizeInBits() / TypeSizeInBits);
37034   SAD = DAG.getBitcast(ResVT, SAD);
37035   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Type, SAD,
37036                      Extract->getOperand(1));
37037 }
37038 
37039 // Attempt to peek through a target shuffle and extract the scalar from the
37040 // source.
combineExtractWithShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37041 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
37042                                          TargetLowering::DAGCombinerInfo &DCI,
37043                                          const X86Subtarget &Subtarget) {
37044   if (DCI.isBeforeLegalizeOps())
37045     return SDValue();
37046 
37047   SDLoc dl(N);
37048   SDValue Src = N->getOperand(0);
37049   SDValue Idx = N->getOperand(1);
37050 
37051   EVT VT = N->getValueType(0);
37052   EVT SrcVT = Src.getValueType();
37053   EVT SrcSVT = SrcVT.getVectorElementType();
37054   unsigned NumSrcElts = SrcVT.getVectorNumElements();
37055 
37056   // Don't attempt this for boolean mask vectors or unknown extraction indices.
37057   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
37058     return SDValue();
37059 
37060   SDValue SrcBC = peekThroughBitcasts(Src);
37061 
37062   // Handle extract(broadcast(scalar_value)), it doesn't matter what index is.
37063   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
37064     SDValue SrcOp = SrcBC.getOperand(0);
37065     if (SrcOp.getValueSizeInBits() == VT.getSizeInBits())
37066       return DAG.getBitcast(VT, SrcOp);
37067   }
37068 
37069   // If we're extracting a single element from a broadcast load and there are
37070   // no other users, just create a single load.
37071   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
37072     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
37073     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
37074     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
37075         VT.getSizeInBits() == SrcBCWidth) {
37076       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
37077                                  MemIntr->getBasePtr(),
37078                                  MemIntr->getPointerInfo(),
37079                                  MemIntr->getAlignment(),
37080                                  MemIntr->getMemOperand()->getFlags());
37081       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
37082       return Load;
37083     }
37084   }
37085 
37086   // Handle extract(truncate(x)) for 0'th index.
37087   // TODO: Treat this as a faux shuffle?
37088   // TODO: When can we use this for general indices?
37089   if (ISD::TRUNCATE == Src.getOpcode() && SrcVT.is128BitVector() &&
37090       isNullConstant(Idx)) {
37091     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
37092     Src = DAG.getBitcast(SrcVT, Src);
37093     return DAG.getNode(N->getOpcode(), dl, VT, Src, Idx);
37094   }
37095 
37096   // Resolve the target shuffle inputs and mask.
37097   SmallVector<int, 16> Mask;
37098   SmallVector<SDValue, 2> Ops;
37099   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
37100     return SDValue();
37101 
37102   // Attempt to narrow/widen the shuffle mask to the correct size.
37103   if (Mask.size() != NumSrcElts) {
37104     if ((NumSrcElts % Mask.size()) == 0) {
37105       SmallVector<int, 16> ScaledMask;
37106       int Scale = NumSrcElts / Mask.size();
37107       scaleShuffleMask<int>(Scale, Mask, ScaledMask);
37108       Mask = std::move(ScaledMask);
37109     } else if ((Mask.size() % NumSrcElts) == 0) {
37110       // Simplify Mask based on demanded element.
37111       int ExtractIdx = (int)N->getConstantOperandVal(1);
37112       int Scale = Mask.size() / NumSrcElts;
37113       int Lo = Scale * ExtractIdx;
37114       int Hi = Scale * (ExtractIdx + 1);
37115       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
37116         if (i < Lo || Hi <= i)
37117           Mask[i] = SM_SentinelUndef;
37118 
37119       SmallVector<int, 16> WidenedMask;
37120       while (Mask.size() > NumSrcElts &&
37121              canWidenShuffleElements(Mask, WidenedMask))
37122         Mask = std::move(WidenedMask);
37123       // TODO - investigate support for wider shuffle masks with known upper
37124       // undef/zero elements for implicit zero-extension.
37125     }
37126   }
37127 
37128   // Check if narrowing/widening failed.
37129   if (Mask.size() != NumSrcElts)
37130     return SDValue();
37131 
37132   int SrcIdx = Mask[N->getConstantOperandVal(1)];
37133 
37134   // If the shuffle source element is undef/zero then we can just accept it.
37135   if (SrcIdx == SM_SentinelUndef)
37136     return DAG.getUNDEF(VT);
37137 
37138   if (SrcIdx == SM_SentinelZero)
37139     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
37140                                 : DAG.getConstant(0, dl, VT);
37141 
37142   SDValue SrcOp = Ops[SrcIdx / Mask.size()];
37143   SrcIdx = SrcIdx % Mask.size();
37144 
37145   // We can only extract other elements from 128-bit vectors and in certain
37146   // circumstances, depending on SSE-level.
37147   // TODO: Investigate using extract_subvector for larger vectors.
37148   // TODO: Investigate float/double extraction if it will be just stored.
37149   if ((SrcVT == MVT::v4i32 || SrcVT == MVT::v2i64) &&
37150       ((SrcIdx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
37151     assert(SrcSVT == VT && "Unexpected extraction type");
37152     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
37153     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcSVT, SrcOp,
37154                        DAG.getIntPtrConstant(SrcIdx, dl));
37155   }
37156 
37157   if ((SrcVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
37158       (SrcVT == MVT::v16i8 && Subtarget.hasSSE41())) {
37159     assert(VT.getSizeInBits() >= SrcSVT.getSizeInBits() &&
37160            "Unexpected extraction type");
37161     unsigned OpCode = (SrcVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
37162     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
37163     SDValue ExtOp = DAG.getNode(OpCode, dl, MVT::i32, SrcOp,
37164                                 DAG.getIntPtrConstant(SrcIdx, dl));
37165     return DAG.getZExtOrTrunc(ExtOp, dl, VT);
37166   }
37167 
37168   return SDValue();
37169 }
37170 
37171 /// Extracting a scalar FP value from vector element 0 is free, so extract each
37172 /// operand first, then perform the math as a scalar op.
scalarizeExtEltFP(SDNode * ExtElt,SelectionDAG & DAG)37173 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG) {
37174   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
37175   SDValue Vec = ExtElt->getOperand(0);
37176   SDValue Index = ExtElt->getOperand(1);
37177   EVT VT = ExtElt->getValueType(0);
37178   EVT VecVT = Vec.getValueType();
37179 
37180   // TODO: If this is a unary/expensive/expand op, allow extraction from a
37181   // non-zero element because the shuffle+scalar op will be cheaper?
37182   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
37183     return SDValue();
37184 
37185   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
37186   // extract, the condition code), so deal with those as a special-case.
37187   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
37188     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
37189     if (OpVT != MVT::f32 && OpVT != MVT::f64)
37190       return SDValue();
37191 
37192     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
37193     SDLoc DL(ExtElt);
37194     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
37195                                Vec.getOperand(0), Index);
37196     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
37197                                Vec.getOperand(1), Index);
37198     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
37199   }
37200 
37201   if (VT != MVT::f32 && VT != MVT::f64)
37202     return SDValue();
37203 
37204   // Vector FP selects don't fit the pattern of FP math ops (because the
37205   // condition has a different type and we have to change the opcode), so deal
37206   // with those here.
37207   // FIXME: This is restricted to pre type legalization by ensuring the setcc
37208   // has i1 elements. If we loosen this we need to convert vector bool to a
37209   // scalar bool.
37210   if (Vec.getOpcode() == ISD::VSELECT &&
37211       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
37212       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
37213       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
37214     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
37215     SDLoc DL(ExtElt);
37216     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
37217                                Vec.getOperand(0).getValueType().getScalarType(),
37218                                Vec.getOperand(0), Index);
37219     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
37220                                Vec.getOperand(1), Index);
37221     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
37222                                Vec.getOperand(2), Index);
37223     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
37224   }
37225 
37226   // TODO: This switch could include FNEG and the x86-specific FP logic ops
37227   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
37228   // missed load folding and fma+fneg combining.
37229   switch (Vec.getOpcode()) {
37230   case ISD::FMA: // Begin 3 operands
37231   case ISD::FMAD:
37232   case ISD::FADD: // Begin 2 operands
37233   case ISD::FSUB:
37234   case ISD::FMUL:
37235   case ISD::FDIV:
37236   case ISD::FREM:
37237   case ISD::FCOPYSIGN:
37238   case ISD::FMINNUM:
37239   case ISD::FMAXNUM:
37240   case ISD::FMINNUM_IEEE:
37241   case ISD::FMAXNUM_IEEE:
37242   case ISD::FMAXIMUM:
37243   case ISD::FMINIMUM:
37244   case X86ISD::FMAX:
37245   case X86ISD::FMIN:
37246   case ISD::FABS: // Begin 1 operand
37247   case ISD::FSQRT:
37248   case ISD::FRINT:
37249   case ISD::FCEIL:
37250   case ISD::FTRUNC:
37251   case ISD::FNEARBYINT:
37252   case ISD::FROUND:
37253   case ISD::FFLOOR:
37254   case X86ISD::FRCP:
37255   case X86ISD::FRSQRT: {
37256     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
37257     SDLoc DL(ExtElt);
37258     SmallVector<SDValue, 4> ExtOps;
37259     for (SDValue Op : Vec->ops())
37260       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
37261     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
37262   }
37263   default:
37264     return SDValue();
37265   }
37266   llvm_unreachable("All opcodes should return within switch");
37267 }
37268 
37269 /// Try to convert a vector reduction sequence composed of binops and shuffles
37270 /// into horizontal ops.
combineReductionToHorizontal(SDNode * ExtElt,SelectionDAG & DAG,const X86Subtarget & Subtarget)37271 static SDValue combineReductionToHorizontal(SDNode *ExtElt, SelectionDAG &DAG,
37272                                             const X86Subtarget &Subtarget) {
37273   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
37274 
37275   // We need at least SSE2 to anything here.
37276   if (!Subtarget.hasSSE2())
37277     return SDValue();
37278 
37279   ISD::NodeType Opc;
37280   SDValue Rdx =
37281       DAG.matchBinOpReduction(ExtElt, Opc, {ISD::ADD, ISD::FADD}, true);
37282   if (!Rdx)
37283     return SDValue();
37284 
37285   SDValue Index = ExtElt->getOperand(1);
37286   assert(isNullConstant(Index) &&
37287          "Reduction doesn't end in an extract from index 0");
37288 
37289   EVT VT = ExtElt->getValueType(0);
37290   EVT VecVT = Rdx.getValueType();
37291   if (VecVT.getScalarType() != VT)
37292     return SDValue();
37293 
37294   SDLoc DL(ExtElt);
37295 
37296   // vXi8 reduction - sub 128-bit vector.
37297   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
37298     if (VecVT == MVT::v4i8) {
37299       // Pad with zero.
37300       if (Subtarget.hasSSE41()) {
37301         Rdx = DAG.getBitcast(MVT::i32, Rdx);
37302         Rdx = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
37303                           DAG.getConstant(0, DL, MVT::v4i32), Rdx,
37304                           DAG.getIntPtrConstant(0, DL));
37305         Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
37306       } else {
37307         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
37308                           DAG.getConstant(0, DL, VecVT));
37309       }
37310     }
37311     if (Rdx.getValueType() == MVT::v8i8) {
37312       // Pad with undef.
37313       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
37314                         DAG.getUNDEF(MVT::v8i8));
37315     }
37316     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
37317                       DAG.getConstant(0, DL, MVT::v16i8));
37318     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
37319     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
37320   }
37321 
37322   // Must be a >=128-bit vector with pow2 elements.
37323   if ((VecVT.getSizeInBits() % 128) != 0 ||
37324       !isPowerOf2_32(VecVT.getVectorNumElements()))
37325     return SDValue();
37326 
37327   // vXi8 reduction - sum lo/hi halves then use PSADBW.
37328   if (VT == MVT::i8) {
37329     while (Rdx.getValueSizeInBits() > 128) {
37330       unsigned HalfSize = VecVT.getSizeInBits() / 2;
37331       unsigned HalfElts = VecVT.getVectorNumElements() / 2;
37332       SDValue Lo = extractSubVector(Rdx, 0, DAG, DL, HalfSize);
37333       SDValue Hi = extractSubVector(Rdx, HalfElts, DAG, DL, HalfSize);
37334       Rdx = DAG.getNode(ISD::ADD, DL, Lo.getValueType(), Lo, Hi);
37335       VecVT = Rdx.getValueType();
37336     }
37337     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
37338 
37339     SDValue Hi = DAG.getVectorShuffle(
37340         MVT::v16i8, DL, Rdx, Rdx,
37341         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
37342     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
37343     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
37344                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
37345     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
37346     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
37347   }
37348 
37349   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
37350   bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
37351   if (!Subtarget.hasFastHorizontalOps() && !OptForSize)
37352     return SDValue();
37353 
37354   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
37355 
37356   // 256-bit horizontal instructions operate on 128-bit chunks rather than
37357   // across the whole vector, so we need an extract + hop preliminary stage.
37358   // This is the only step where the operands of the hop are not the same value.
37359   // TODO: We could extend this to handle 512-bit or even longer vectors.
37360   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
37361       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
37362     unsigned NumElts = VecVT.getVectorNumElements();
37363     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
37364     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
37365     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
37366     VecVT = Rdx.getValueType();
37367   }
37368   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
37369       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
37370     return SDValue();
37371 
37372   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
37373   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
37374   for (unsigned i = 0; i != ReductionSteps; ++i)
37375     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
37376 
37377   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
37378 }
37379 
37380 /// Detect vector gather/scatter index generation and convert it from being a
37381 /// bunch of shuffles and extracts into a somewhat faster sequence.
37382 /// For i686, the best sequence is apparently storing the value and loading
37383 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
combineExtractVectorElt(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37384 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
37385                                        TargetLowering::DAGCombinerInfo &DCI,
37386                                        const X86Subtarget &Subtarget) {
37387   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
37388     return NewOp;
37389 
37390   SDValue InputVector = N->getOperand(0);
37391   SDValue EltIdx = N->getOperand(1);
37392   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
37393 
37394   EVT SrcVT = InputVector.getValueType();
37395   EVT VT = N->getValueType(0);
37396   SDLoc dl(InputVector);
37397   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
37398   unsigned NumSrcElts = SrcVT.getVectorNumElements();
37399 
37400   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
37401     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
37402 
37403   // Integer Constant Folding.
37404   if (CIdx && VT.isInteger()) {
37405     APInt UndefVecElts;
37406     SmallVector<APInt, 16> EltBits;
37407     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
37408     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
37409                                       EltBits, true, false)) {
37410       uint64_t Idx = CIdx->getZExtValue();
37411       if (UndefVecElts[Idx])
37412         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
37413       return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
37414                              dl, VT);
37415     }
37416   }
37417 
37418   if (IsPextr) {
37419     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37420     if (TLI.SimplifyDemandedBits(
37421             SDValue(N, 0), APInt::getAllOnesValue(VT.getSizeInBits()), DCI))
37422       return SDValue(N, 0);
37423 
37424     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
37425     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
37426          InputVector.getOpcode() == X86ISD::PINSRW) &&
37427         InputVector.getOperand(2) == EltIdx) {
37428       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
37429              "Vector type mismatch");
37430       SDValue Scl = InputVector.getOperand(1);
37431       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
37432       return DAG.getZExtOrTrunc(Scl, dl, VT);
37433     }
37434 
37435     // TODO - Remove this once we can handle the implicit zero-extension of
37436     // X86ISD::PEXTRW/X86ISD::PEXTRB in combineHorizontalPredicateResult and
37437     // combineBasicSADPattern.
37438     return SDValue();
37439   }
37440 
37441   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
37442   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
37443       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
37444     SDValue MMXSrc = InputVector.getOperand(0);
37445 
37446     // The bitcast source is a direct mmx result.
37447     if (MMXSrc.getValueType() == MVT::x86mmx)
37448       return DAG.getBitcast(VT, InputVector);
37449   }
37450 
37451   // Detect mmx to i32 conversion through a v2i32 elt extract.
37452   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
37453       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
37454     SDValue MMXSrc = InputVector.getOperand(0);
37455 
37456     // The bitcast source is a direct mmx result.
37457     if (MMXSrc.getValueType() == MVT::x86mmx)
37458       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
37459   }
37460 
37461   // Check whether this extract is the root of a sum of absolute differences
37462   // pattern. This has to be done here because we really want it to happen
37463   // pre-legalization,
37464   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
37465     return SAD;
37466 
37467   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
37468   if (SDValue Cmp = combineHorizontalPredicateResult(N, DAG, Subtarget))
37469     return Cmp;
37470 
37471   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
37472   if (SDValue MinMax = combineHorizontalMinMaxResult(N, DAG, Subtarget))
37473     return MinMax;
37474 
37475   if (SDValue V = combineReductionToHorizontal(N, DAG, Subtarget))
37476     return V;
37477 
37478   if (SDValue V = scalarizeExtEltFP(N, DAG))
37479     return V;
37480 
37481   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
37482   // and then testing the relevant element.
37483   if (CIdx && SrcVT.getScalarType() == MVT::i1) {
37484     SmallVector<SDNode *, 16> BoolExtracts;
37485     auto IsBoolExtract = [&BoolExtracts](SDNode *Use) {
37486       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
37487           isa<ConstantSDNode>(Use->getOperand(1)) &&
37488           Use->getValueType(0) == MVT::i1) {
37489         BoolExtracts.push_back(Use);
37490         return true;
37491       }
37492       return false;
37493     };
37494     if (all_of(InputVector->uses(), IsBoolExtract) &&
37495         BoolExtracts.size() > 1) {
37496       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
37497       if (SDValue BC =
37498               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
37499         for (SDNode *Use : BoolExtracts) {
37500           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
37501           unsigned MaskIdx = Use->getConstantOperandVal(1);
37502           APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
37503           SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
37504           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
37505           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
37506           DCI.CombineTo(Use, Res);
37507         }
37508         return SDValue(N, 0);
37509       }
37510     }
37511   }
37512 
37513   return SDValue();
37514 }
37515 
37516 /// If a vector select has an operand that is -1 or 0, try to simplify the
37517 /// select to a bitwise logic operation.
37518 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
37519 static SDValue
combineVSelectWithAllOnesOrZeros(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37520 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
37521                                  TargetLowering::DAGCombinerInfo &DCI,
37522                                  const X86Subtarget &Subtarget) {
37523   SDValue Cond = N->getOperand(0);
37524   SDValue LHS = N->getOperand(1);
37525   SDValue RHS = N->getOperand(2);
37526   EVT VT = LHS.getValueType();
37527   EVT CondVT = Cond.getValueType();
37528   SDLoc DL(N);
37529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37530 
37531   if (N->getOpcode() != ISD::VSELECT)
37532     return SDValue();
37533 
37534   assert(CondVT.isVector() && "Vector select expects a vector selector!");
37535 
37536   // Check if the first operand is all zeros and Cond type is vXi1.
37537   // This situation only applies to avx512.
37538   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
37539   // TODO: Can we assert that both operands are not zeros (because that should
37540   //       get simplified at node creation time)?
37541   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
37542   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
37543 
37544   // If both inputs are 0/undef, create a complete zero vector.
37545   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
37546   if (TValIsAllZeros && FValIsAllZeros) {
37547     if (VT.isFloatingPoint())
37548       return DAG.getConstantFP(0.0, DL, VT);
37549     return DAG.getConstant(0, DL, VT);
37550   }
37551 
37552   if (TValIsAllZeros && !FValIsAllZeros && Subtarget.hasAVX512() &&
37553       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1) {
37554     // Invert the cond to not(cond) : xor(op,allones)=not(op)
37555     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
37556     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
37557     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
37558   }
37559 
37560   // To use the condition operand as a bitwise mask, it must have elements that
37561   // are the same size as the select elements. Ie, the condition operand must
37562   // have already been promoted from the IR select condition type <N x i1>.
37563   // Don't check if the types themselves are equal because that excludes
37564   // vector floating-point selects.
37565   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
37566     return SDValue();
37567 
37568   // Try to invert the condition if true value is not all 1s and false value is
37569   // not all 0s. Only do this if the condition has one use.
37570   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
37571   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
37572       // Check if the selector will be produced by CMPP*/PCMP*.
37573       Cond.getOpcode() == ISD::SETCC &&
37574       // Check if SETCC has already been promoted.
37575       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
37576           CondVT) {
37577     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
37578 
37579     if (TValIsAllZeros || FValIsAllOnes) {
37580       SDValue CC = Cond.getOperand(2);
37581       ISD::CondCode NewCC = ISD::getSetCCInverse(
37582           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
37583       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
37584                           NewCC);
37585       std::swap(LHS, RHS);
37586       TValIsAllOnes = FValIsAllOnes;
37587       FValIsAllZeros = TValIsAllZeros;
37588     }
37589   }
37590 
37591   // Cond value must be 'sign splat' to be converted to a logical op.
37592   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
37593     return SDValue();
37594 
37595   // vselect Cond, 111..., 000... -> Cond
37596   if (TValIsAllOnes && FValIsAllZeros)
37597     return DAG.getBitcast(VT, Cond);
37598 
37599   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(CondVT))
37600     return SDValue();
37601 
37602   // vselect Cond, 111..., X -> or Cond, X
37603   if (TValIsAllOnes) {
37604     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
37605     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
37606     return DAG.getBitcast(VT, Or);
37607   }
37608 
37609   // vselect Cond, X, 000... -> and Cond, X
37610   if (FValIsAllZeros) {
37611     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
37612     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
37613     return DAG.getBitcast(VT, And);
37614   }
37615 
37616   // vselect Cond, 000..., X -> andn Cond, X
37617   if (TValIsAllZeros) {
37618     MVT AndNVT = MVT::getVectorVT(MVT::i64, CondVT.getSizeInBits() / 64);
37619     SDValue CastCond = DAG.getBitcast(AndNVT, Cond);
37620     SDValue CastRHS = DAG.getBitcast(AndNVT, RHS);
37621     SDValue AndN = DAG.getNode(X86ISD::ANDNP, DL, AndNVT, CastCond, CastRHS);
37622     return DAG.getBitcast(VT, AndN);
37623   }
37624 
37625   return SDValue();
37626 }
37627 
37628 /// If both arms of a vector select are concatenated vectors, split the select,
37629 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
37630 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
37631 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
narrowVectorSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)37632 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
37633                                   const X86Subtarget &Subtarget) {
37634   unsigned Opcode = N->getOpcode();
37635   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
37636     return SDValue();
37637 
37638   // TODO: Split 512-bit vectors too?
37639   EVT VT = N->getValueType(0);
37640   if (!VT.is256BitVector())
37641     return SDValue();
37642 
37643   // TODO: Split as long as any 2 of the 3 operands are concatenated?
37644   SDValue Cond = N->getOperand(0);
37645   SDValue TVal = N->getOperand(1);
37646   SDValue FVal = N->getOperand(2);
37647   SmallVector<SDValue, 4> CatOpsT, CatOpsF;
37648   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
37649       !collectConcatOps(TVal.getNode(), CatOpsT) ||
37650       !collectConcatOps(FVal.getNode(), CatOpsF))
37651     return SDValue();
37652 
37653   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
37654                             ArrayRef<SDValue> Ops) {
37655     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
37656   };
37657   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
37658                           makeBlend, /*CheckBWI*/ false);
37659 }
37660 
combineSelectOfTwoConstants(SDNode * N,SelectionDAG & DAG)37661 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
37662   SDValue Cond = N->getOperand(0);
37663   SDValue LHS = N->getOperand(1);
37664   SDValue RHS = N->getOperand(2);
37665   SDLoc DL(N);
37666 
37667   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
37668   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
37669   if (!TrueC || !FalseC)
37670     return SDValue();
37671 
37672   // Don't do this for crazy integer types.
37673   EVT VT = N->getValueType(0);
37674   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
37675     return SDValue();
37676 
37677   // We're going to use the condition bit in math or logic ops. We could allow
37678   // this with a wider condition value (post-legalization it becomes an i8),
37679   // but if nothing is creating selects that late, it doesn't matter.
37680   if (Cond.getValueType() != MVT::i1)
37681     return SDValue();
37682 
37683   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
37684   // 3, 5, or 9 with i32/i64, so those get transformed too.
37685   // TODO: For constants that overflow or do not differ by power-of-2 or small
37686   // multiplier, convert to 'and' + 'add'.
37687   const APInt &TrueVal = TrueC->getAPIntValue();
37688   const APInt &FalseVal = FalseC->getAPIntValue();
37689   bool OV;
37690   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
37691   if (OV)
37692     return SDValue();
37693 
37694   APInt AbsDiff = Diff.abs();
37695   if (AbsDiff.isPowerOf2() ||
37696       ((VT == MVT::i32 || VT == MVT::i64) &&
37697        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
37698 
37699     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
37700     // of the condition can usually be folded into a compare predicate, but even
37701     // without that, the sequence should be cheaper than a CMOV alternative.
37702     if (TrueVal.slt(FalseVal)) {
37703       Cond = DAG.getNOT(DL, Cond, MVT::i1);
37704       std::swap(TrueC, FalseC);
37705     }
37706 
37707     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
37708     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
37709 
37710     // Multiply condition by the difference if non-one.
37711     if (!AbsDiff.isOneValue())
37712       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
37713 
37714     // Add the base if non-zero.
37715     if (!FalseC->isNullValue())
37716       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
37717 
37718     return R;
37719   }
37720 
37721   return SDValue();
37722 }
37723 
37724 /// If this is a *dynamic* select (non-constant condition) and we can match
37725 /// this node with one of the variable blend instructions, restructure the
37726 /// condition so that blends can use the high (sign) bit of each element.
37727 /// This function will also call SimplifyDemandedBits on already created
37728 /// BLENDV to perform additional simplifications.
combineVSelectToBLENDV(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37729 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
37730                                            TargetLowering::DAGCombinerInfo &DCI,
37731                                            const X86Subtarget &Subtarget) {
37732   SDValue Cond = N->getOperand(0);
37733   if ((N->getOpcode() != ISD::VSELECT &&
37734        N->getOpcode() != X86ISD::BLENDV) ||
37735       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
37736     return SDValue();
37737 
37738   // Don't optimize before the condition has been transformed to a legal type
37739   // and don't ever optimize vector selects that map to AVX512 mask-registers.
37740   unsigned BitWidth = Cond.getScalarValueSizeInBits();
37741   if (BitWidth < 8 || BitWidth > 64)
37742     return SDValue();
37743 
37744   // We can only handle the cases where VSELECT is directly legal on the
37745   // subtarget. We custom lower VSELECT nodes with constant conditions and
37746   // this makes it hard to see whether a dynamic VSELECT will correctly
37747   // lower, so we both check the operation's status and explicitly handle the
37748   // cases where a *dynamic* blend will fail even though a constant-condition
37749   // blend could be custom lowered.
37750   // FIXME: We should find a better way to handle this class of problems.
37751   // Potentially, we should combine constant-condition vselect nodes
37752   // pre-legalization into shuffles and not mark as many types as custom
37753   // lowered.
37754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37755   EVT VT = N->getValueType(0);
37756   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
37757     return SDValue();
37758   // FIXME: We don't support i16-element blends currently. We could and
37759   // should support them by making *all* the bits in the condition be set
37760   // rather than just the high bit and using an i8-element blend.
37761   if (VT.getVectorElementType() == MVT::i16)
37762     return SDValue();
37763   // Dynamic blending was only available from SSE4.1 onward.
37764   if (VT.is128BitVector() && !Subtarget.hasSSE41())
37765     return SDValue();
37766   // Byte blends are only available in AVX2
37767   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
37768     return SDValue();
37769   // There are no 512-bit blend instructions that use sign bits.
37770   if (VT.is512BitVector())
37771     return SDValue();
37772 
37773   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
37774     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
37775          UI != UE; ++UI)
37776       if ((UI->getOpcode() != ISD::VSELECT &&
37777            UI->getOpcode() != X86ISD::BLENDV) ||
37778           UI.getOperandNo() != 0)
37779         return false;
37780 
37781     return true;
37782   };
37783 
37784   if (OnlyUsedAsSelectCond(Cond)) {
37785     APInt DemandedMask(APInt::getSignMask(BitWidth));
37786     KnownBits Known;
37787     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
37788                                           !DCI.isBeforeLegalizeOps());
37789     if (!TLI.SimplifyDemandedBits(Cond, DemandedMask, Known, TLO, 0, true))
37790       return SDValue();
37791 
37792     // If we changed the computation somewhere in the DAG, this change will
37793     // affect all users of Cond. Update all the nodes so that we do not use
37794     // the generic VSELECT anymore. Otherwise, we may perform wrong
37795     // optimizations as we messed with the actual expectation for the vector
37796     // boolean values.
37797     for (SDNode *U : Cond->uses()) {
37798       if (U->getOpcode() == X86ISD::BLENDV)
37799         continue;
37800 
37801       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
37802                                Cond, U->getOperand(1), U->getOperand(2));
37803       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
37804       DCI.AddToWorklist(U);
37805     }
37806     DCI.CommitTargetLoweringOpt(TLO);
37807     return SDValue(N, 0);
37808   }
37809 
37810   // Otherwise we can still at least try to simplify multiple use bits.
37811   APInt DemandedMask(APInt::getSignMask(BitWidth));
37812   APInt DemandedElts(APInt::getAllOnesValue(VT.getVectorNumElements()));
37813   KnownBits Known;
37814   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
37815                                         !DCI.isBeforeLegalizeOps());
37816   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedMask,
37817                                                       DemandedElts, DAG, 0))
37818     return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
37819                        V, N->getOperand(1), N->getOperand(2));
37820 
37821   return SDValue();
37822 }
37823 
37824 // Try to match:
37825 //   (or (and (M, (sub 0, X)), (pandn M, X)))
37826 // which is a special case of:
37827 //   (select M, (sub 0, X), X)
37828 // Per:
37829 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
37830 // We know that, if fNegate is 0 or 1:
37831 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
37832 //
37833 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
37834 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
37835 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
37836 // This lets us transform our vselect to:
37837 //   (add (xor X, M), (and M, 1))
37838 // And further to:
37839 //   (sub (xor X, M), M)
combineLogicBlendIntoConditionalNegate(EVT VT,SDValue Mask,SDValue X,SDValue Y,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)37840 static SDValue combineLogicBlendIntoConditionalNegate(
37841     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
37842     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
37843   EVT MaskVT = Mask.getValueType();
37844   assert(MaskVT.isInteger() &&
37845          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
37846          "Mask must be zero/all-bits");
37847 
37848   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
37849     return SDValue();
37850   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
37851     return SDValue();
37852 
37853   auto IsNegV = [](SDNode *N, SDValue V) {
37854     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
37855            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
37856   };
37857 
37858   SDValue V;
37859   if (IsNegV(Y.getNode(), X))
37860     V = X;
37861   else if (IsNegV(X.getNode(), Y))
37862     V = Y;
37863   else
37864     return SDValue();
37865 
37866   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
37867   SDValue SubOp2 = Mask;
37868 
37869   // If the negate was on the false side of the select, then
37870   // the operands of the SUB need to be swapped. PR 27251.
37871   // This is because the pattern being matched above is
37872   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
37873   // but if the pattern matched was
37874   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
37875   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
37876   // pattern also needs to be a negation of the replacement pattern above.
37877   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
37878   // sub accomplishes the negation of the replacement pattern.
37879   if (V == Y)
37880     std::swap(SubOp1, SubOp2);
37881 
37882   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
37883   return DAG.getBitcast(VT, Res);
37884 }
37885 
37886 /// Do target-specific dag combines on SELECT and VSELECT nodes.
combineSelect(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37887 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
37888                              TargetLowering::DAGCombinerInfo &DCI,
37889                              const X86Subtarget &Subtarget) {
37890   SDLoc DL(N);
37891   SDValue Cond = N->getOperand(0);
37892   SDValue LHS = N->getOperand(1);
37893   SDValue RHS = N->getOperand(2);
37894 
37895   // Try simplification again because we use this function to optimize
37896   // BLENDV nodes that are not handled by the generic combiner.
37897   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
37898     return V;
37899 
37900   EVT VT = LHS.getValueType();
37901   EVT CondVT = Cond.getValueType();
37902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37903   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
37904 
37905   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
37906   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
37907   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
37908   if (CondVT.isVector() && CondVT.isInteger() &&
37909       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
37910       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
37911       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
37912     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
37913                                                            DL, DAG, Subtarget))
37914       return V;
37915 
37916   // Convert vselects with constant condition into shuffles.
37917   if (CondConstantVector && DCI.isBeforeLegalizeOps()) {
37918     SmallVector<int, 64> Mask;
37919     if (createShuffleMaskFromVSELECT(Mask, Cond))
37920       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
37921   }
37922 
37923   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
37924   // instructions match the semantics of the common C idiom x<y?x:y but not
37925   // x<=y?x:y, because of how they handle negative zero (which can be
37926   // ignored in unsafe-math mode).
37927   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
37928   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
37929       VT != MVT::f80 && VT != MVT::f128 &&
37930       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
37931       (Subtarget.hasSSE2() ||
37932        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
37933     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
37934 
37935     unsigned Opcode = 0;
37936     // Check for x CC y ? x : y.
37937     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
37938         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
37939       switch (CC) {
37940       default: break;
37941       case ISD::SETULT:
37942         // Converting this to a min would handle NaNs incorrectly, and swapping
37943         // the operands would cause it to handle comparisons between positive
37944         // and negative zero incorrectly.
37945         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
37946           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
37947               !(DAG.isKnownNeverZeroFloat(LHS) ||
37948                 DAG.isKnownNeverZeroFloat(RHS)))
37949             break;
37950           std::swap(LHS, RHS);
37951         }
37952         Opcode = X86ISD::FMIN;
37953         break;
37954       case ISD::SETOLE:
37955         // Converting this to a min would handle comparisons between positive
37956         // and negative zero incorrectly.
37957         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
37958             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
37959           break;
37960         Opcode = X86ISD::FMIN;
37961         break;
37962       case ISD::SETULE:
37963         // Converting this to a min would handle both negative zeros and NaNs
37964         // incorrectly, but we can swap the operands to fix both.
37965         std::swap(LHS, RHS);
37966         LLVM_FALLTHROUGH;
37967       case ISD::SETOLT:
37968       case ISD::SETLT:
37969       case ISD::SETLE:
37970         Opcode = X86ISD::FMIN;
37971         break;
37972 
37973       case ISD::SETOGE:
37974         // Converting this to a max would handle comparisons between positive
37975         // and negative zero incorrectly.
37976         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
37977             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
37978           break;
37979         Opcode = X86ISD::FMAX;
37980         break;
37981       case ISD::SETUGT:
37982         // Converting this to a max would handle NaNs incorrectly, and swapping
37983         // the operands would cause it to handle comparisons between positive
37984         // and negative zero incorrectly.
37985         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
37986           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
37987               !(DAG.isKnownNeverZeroFloat(LHS) ||
37988                 DAG.isKnownNeverZeroFloat(RHS)))
37989             break;
37990           std::swap(LHS, RHS);
37991         }
37992         Opcode = X86ISD::FMAX;
37993         break;
37994       case ISD::SETUGE:
37995         // Converting this to a max would handle both negative zeros and NaNs
37996         // incorrectly, but we can swap the operands to fix both.
37997         std::swap(LHS, RHS);
37998         LLVM_FALLTHROUGH;
37999       case ISD::SETOGT:
38000       case ISD::SETGT:
38001       case ISD::SETGE:
38002         Opcode = X86ISD::FMAX;
38003         break;
38004       }
38005     // Check for x CC y ? y : x -- a min/max with reversed arms.
38006     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
38007                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
38008       switch (CC) {
38009       default: break;
38010       case ISD::SETOGE:
38011         // Converting this to a min would handle comparisons between positive
38012         // and negative zero incorrectly, and swapping the operands would
38013         // cause it to handle NaNs incorrectly.
38014         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
38015             !(DAG.isKnownNeverZeroFloat(LHS) ||
38016               DAG.isKnownNeverZeroFloat(RHS))) {
38017           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
38018             break;
38019           std::swap(LHS, RHS);
38020         }
38021         Opcode = X86ISD::FMIN;
38022         break;
38023       case ISD::SETUGT:
38024         // Converting this to a min would handle NaNs incorrectly.
38025         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
38026           break;
38027         Opcode = X86ISD::FMIN;
38028         break;
38029       case ISD::SETUGE:
38030         // Converting this to a min would handle both negative zeros and NaNs
38031         // incorrectly, but we can swap the operands to fix both.
38032         std::swap(LHS, RHS);
38033         LLVM_FALLTHROUGH;
38034       case ISD::SETOGT:
38035       case ISD::SETGT:
38036       case ISD::SETGE:
38037         Opcode = X86ISD::FMIN;
38038         break;
38039 
38040       case ISD::SETULT:
38041         // Converting this to a max would handle NaNs incorrectly.
38042         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
38043           break;
38044         Opcode = X86ISD::FMAX;
38045         break;
38046       case ISD::SETOLE:
38047         // Converting this to a max would handle comparisons between positive
38048         // and negative zero incorrectly, and swapping the operands would
38049         // cause it to handle NaNs incorrectly.
38050         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
38051             !DAG.isKnownNeverZeroFloat(LHS) &&
38052             !DAG.isKnownNeverZeroFloat(RHS)) {
38053           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
38054             break;
38055           std::swap(LHS, RHS);
38056         }
38057         Opcode = X86ISD::FMAX;
38058         break;
38059       case ISD::SETULE:
38060         // Converting this to a max would handle both negative zeros and NaNs
38061         // incorrectly, but we can swap the operands to fix both.
38062         std::swap(LHS, RHS);
38063         LLVM_FALLTHROUGH;
38064       case ISD::SETOLT:
38065       case ISD::SETLT:
38066       case ISD::SETLE:
38067         Opcode = X86ISD::FMAX;
38068         break;
38069       }
38070     }
38071 
38072     if (Opcode)
38073       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
38074   }
38075 
38076   // Some mask scalar intrinsics rely on checking if only one bit is set
38077   // and implement it in C code like this:
38078   // A[0] = (U & 1) ? A[0] : W[0];
38079   // This creates some redundant instructions that break pattern matching.
38080   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
38081   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
38082       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
38083     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
38084     SDValue AndNode = Cond.getOperand(0);
38085     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
38086         isNullConstant(Cond.getOperand(1)) &&
38087         isOneConstant(AndNode.getOperand(1))) {
38088       // LHS and RHS swapped due to
38089       // setcc outputting 1 when AND resulted in 0 and vice versa.
38090       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
38091       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
38092     }
38093   }
38094 
38095   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
38096   // lowering on KNL. In this case we convert it to
38097   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
38098   // The same situation all vectors of i8 and i16 without BWI.
38099   // Make sure we extend these even before type legalization gets a chance to
38100   // split wide vectors.
38101   // Since SKX these selects have a proper lowering.
38102   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
38103       CondVT.getVectorElementType() == MVT::i1 &&
38104       (VT.getVectorElementType() == MVT::i8 ||
38105        VT.getVectorElementType() == MVT::i16)) {
38106     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
38107     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
38108   }
38109 
38110   // AVX512 - Extend select with zero to merge with target shuffle.
38111   // select(mask, extract_subvector(shuffle(x)), zero) -->
38112   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
38113   // TODO - support non target shuffles as well.
38114   if (Subtarget.hasAVX512() && CondVT.isVector() &&
38115       CondVT.getVectorElementType() == MVT::i1) {
38116     auto SelectableOp = [&TLI](SDValue Op) {
38117       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
38118              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
38119              isNullConstant(Op.getOperand(1)) &&
38120              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
38121              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
38122     };
38123 
38124     bool SelectableLHS = SelectableOp(LHS);
38125     bool SelectableRHS = SelectableOp(RHS);
38126     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
38127     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
38128 
38129     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
38130       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
38131                                 : RHS.getOperand(0).getValueType();
38132       unsigned NumSrcElts = SrcVT.getVectorNumElements();
38133       EVT SrcCondVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumSrcElts);
38134       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
38135                             VT.getSizeInBits());
38136       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
38137                             VT.getSizeInBits());
38138       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
38139                          DAG.getUNDEF(SrcCondVT), Cond,
38140                          DAG.getIntPtrConstant(0, DL));
38141       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
38142       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
38143     }
38144   }
38145 
38146   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
38147     return V;
38148 
38149   // Canonicalize max and min:
38150   // (x > y) ? x : y -> (x >= y) ? x : y
38151   // (x < y) ? x : y -> (x <= y) ? x : y
38152   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
38153   // the need for an extra compare
38154   // against zero. e.g.
38155   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
38156   // subl   %esi, %edi
38157   // testl  %edi, %edi
38158   // movl   $0, %eax
38159   // cmovgl %edi, %eax
38160   // =>
38161   // xorl   %eax, %eax
38162   // subl   %esi, $edi
38163   // cmovsl %eax, %edi
38164   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
38165       Cond.hasOneUse() &&
38166       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
38167       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
38168     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
38169     switch (CC) {
38170     default: break;
38171     case ISD::SETLT:
38172     case ISD::SETGT: {
38173       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
38174       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
38175                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
38176       return DAG.getSelect(DL, VT, Cond, LHS, RHS);
38177     }
38178     }
38179   }
38180 
38181   // Match VSELECTs into subs with unsigned saturation.
38182   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
38183       // psubus is available in SSE2 for i8 and i16 vectors.
38184       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
38185       isPowerOf2_32(VT.getVectorNumElements()) &&
38186       (VT.getVectorElementType() == MVT::i8 ||
38187        VT.getVectorElementType() == MVT::i16)) {
38188     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
38189 
38190     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
38191     // left side invert the predicate to simplify logic below.
38192     SDValue Other;
38193     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
38194       Other = RHS;
38195       CC = ISD::getSetCCInverse(CC, VT.getVectorElementType());
38196     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
38197       Other = LHS;
38198     }
38199 
38200     if (Other.getNode() && Other->getNumOperands() == 2 &&
38201         Other->getOperand(0) == Cond.getOperand(0)) {
38202       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
38203       SDValue CondRHS = Cond->getOperand(1);
38204 
38205       // Look for a general sub with unsigned saturation first.
38206       // x >= y ? x-y : 0 --> subus x, y
38207       // x >  y ? x-y : 0 --> subus x, y
38208       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
38209           Other->getOpcode() == ISD::SUB && OpRHS == CondRHS)
38210         return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
38211 
38212       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) {
38213         if (isa<BuildVectorSDNode>(CondRHS)) {
38214           // If the RHS is a constant we have to reverse the const
38215           // canonicalization.
38216           // x > C-1 ? x+-C : 0 --> subus x, C
38217           auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
38218             return (!Op && !Cond) ||
38219                    (Op && Cond &&
38220                     Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
38221           };
38222           if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
38223               ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
38224                                         /*AllowUndefs*/ true)) {
38225             OpRHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
38226                                 OpRHS);
38227             return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
38228           }
38229 
38230           // Another special case: If C was a sign bit, the sub has been
38231           // canonicalized into a xor.
38232           // FIXME: Would it be better to use computeKnownBits to determine
38233           //        whether it's safe to decanonicalize the xor?
38234           // x s< 0 ? x^C : 0 --> subus x, C
38235           if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
38236             if (CC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
38237                 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
38238                 OpRHSConst->getAPIntValue().isSignMask()) {
38239               // Note that we have to rebuild the RHS constant here to ensure we
38240               // don't rely on particular values of undef lanes.
38241               OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT);
38242               return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
38243             }
38244           }
38245         }
38246       }
38247     }
38248   }
38249 
38250   // Match VSELECTs into add with unsigned saturation.
38251   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
38252       // paddus is available in SSE2 for i8 and i16 vectors.
38253       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
38254       isPowerOf2_32(VT.getVectorNumElements()) &&
38255       (VT.getVectorElementType() == MVT::i8 ||
38256        VT.getVectorElementType() == MVT::i16)) {
38257     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
38258 
38259     SDValue CondLHS = Cond->getOperand(0);
38260     SDValue CondRHS = Cond->getOperand(1);
38261 
38262     // Check if one of the arms of the VSELECT is vector with all bits set.
38263     // If it's on the left side invert the predicate to simplify logic below.
38264     SDValue Other;
38265     if (ISD::isBuildVectorAllOnes(LHS.getNode())) {
38266       Other = RHS;
38267       CC = ISD::getSetCCInverse(CC, VT.getVectorElementType());
38268     } else if (ISD::isBuildVectorAllOnes(RHS.getNode())) {
38269       Other = LHS;
38270     }
38271 
38272     if (Other.getNode() && Other.getOpcode() == ISD::ADD) {
38273       SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
38274 
38275       // Canonicalize condition operands.
38276       if (CC == ISD::SETUGE) {
38277         std::swap(CondLHS, CondRHS);
38278         CC = ISD::SETULE;
38279       }
38280 
38281       // We can test against either of the addition operands.
38282       // x <= x+y ? x+y : ~0 --> addus x, y
38283       // x+y >= x ? x+y : ~0 --> addus x, y
38284       if (CC == ISD::SETULE && Other == CondRHS &&
38285           (OpLHS == CondLHS || OpRHS == CondLHS))
38286         return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
38287 
38288       if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) &&
38289           CondLHS == OpLHS) {
38290         // If the RHS is a constant we have to reverse the const
38291         // canonicalization.
38292         // x > ~C ? x+C : ~0 --> addus x, C
38293         auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
38294           return Cond->getAPIntValue() == ~Op->getAPIntValue();
38295         };
38296         if (CC == ISD::SETULE &&
38297             ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
38298           return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
38299       }
38300     }
38301   }
38302 
38303   // Early exit check
38304   if (!TLI.isTypeLegal(VT))
38305     return SDValue();
38306 
38307   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
38308     return V;
38309 
38310   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
38311     return V;
38312 
38313   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
38314     return V;
38315 
38316   // select(~Cond, X, Y) -> select(Cond, Y, X)
38317   if (CondVT.getScalarType() != MVT::i1)
38318     if (SDValue CondNot = IsNOT(Cond, DAG))
38319       return DAG.getNode(N->getOpcode(), DL, VT,
38320                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
38321 
38322   // Custom action for SELECT MMX
38323   if (VT == MVT::x86mmx) {
38324     LHS = DAG.getBitcast(MVT::i64, LHS);
38325     RHS = DAG.getBitcast(MVT::i64, RHS);
38326     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::i64, Cond, LHS, RHS);
38327     return DAG.getBitcast(VT, newSelect);
38328   }
38329 
38330   return SDValue();
38331 }
38332 
38333 /// Combine:
38334 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
38335 /// to:
38336 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
38337 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
38338 /// Note that this is only legal for some op/cc combinations.
combineSetCCAtomicArith(SDValue Cmp,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)38339 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
38340                                        SelectionDAG &DAG,
38341                                        const X86Subtarget &Subtarget) {
38342   // This combine only operates on CMP-like nodes.
38343   if (!(Cmp.getOpcode() == X86ISD::CMP ||
38344         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
38345     return SDValue();
38346 
38347   // Can't replace the cmp if it has more uses than the one we're looking at.
38348   // FIXME: We would like to be able to handle this, but would need to make sure
38349   // all uses were updated.
38350   if (!Cmp.hasOneUse())
38351     return SDValue();
38352 
38353   // This only applies to variations of the common case:
38354   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
38355   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
38356   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
38357   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
38358   // Using the proper condcodes (see below), overflow is checked for.
38359 
38360   // FIXME: We can generalize both constraints:
38361   // - XOR/OR/AND (if they were made to survive AtomicExpand)
38362   // - LHS != 1
38363   // if the result is compared.
38364 
38365   SDValue CmpLHS = Cmp.getOperand(0);
38366   SDValue CmpRHS = Cmp.getOperand(1);
38367 
38368   if (!CmpLHS.hasOneUse())
38369     return SDValue();
38370 
38371   unsigned Opc = CmpLHS.getOpcode();
38372   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
38373     return SDValue();
38374 
38375   SDValue OpRHS = CmpLHS.getOperand(2);
38376   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
38377   if (!OpRHSC)
38378     return SDValue();
38379 
38380   APInt Addend = OpRHSC->getAPIntValue();
38381   if (Opc == ISD::ATOMIC_LOAD_SUB)
38382     Addend = -Addend;
38383 
38384   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
38385   if (!CmpRHSC)
38386     return SDValue();
38387 
38388   APInt Comparison = CmpRHSC->getAPIntValue();
38389 
38390   // If the addend is the negation of the comparison value, then we can do
38391   // a full comparison by emitting the atomic arithmetic as a locked sub.
38392   if (Comparison == -Addend) {
38393     // The CC is fine, but we need to rewrite the LHS of the comparison as an
38394     // atomic sub.
38395     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
38396     auto AtomicSub = DAG.getAtomic(
38397         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpLHS.getValueType(),
38398         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
38399         /*RHS*/ DAG.getConstant(-Addend, SDLoc(CmpRHS), CmpRHS.getValueType()),
38400         AN->getMemOperand());
38401     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
38402     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
38403                                   DAG.getUNDEF(CmpLHS.getValueType()));
38404     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
38405     return LockOp;
38406   }
38407 
38408   // We can handle comparisons with zero in a number of cases by manipulating
38409   // the CC used.
38410   if (!Comparison.isNullValue())
38411     return SDValue();
38412 
38413   if (CC == X86::COND_S && Addend == 1)
38414     CC = X86::COND_LE;
38415   else if (CC == X86::COND_NS && Addend == 1)
38416     CC = X86::COND_G;
38417   else if (CC == X86::COND_G && Addend == -1)
38418     CC = X86::COND_GE;
38419   else if (CC == X86::COND_LE && Addend == -1)
38420     CC = X86::COND_L;
38421   else
38422     return SDValue();
38423 
38424   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
38425   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
38426                                 DAG.getUNDEF(CmpLHS.getValueType()));
38427   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
38428   return LockOp;
38429 }
38430 
38431 // Check whether a boolean test is testing a boolean value generated by
38432 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
38433 // code.
38434 //
38435 // Simplify the following patterns:
38436 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
38437 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
38438 // to (Op EFLAGS Cond)
38439 //
38440 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
38441 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
38442 // to (Op EFLAGS !Cond)
38443 //
38444 // where Op could be BRCOND or CMOV.
38445 //
checkBoolTestSetCCCombine(SDValue Cmp,X86::CondCode & CC)38446 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
38447   // This combine only operates on CMP-like nodes.
38448   if (!(Cmp.getOpcode() == X86ISD::CMP ||
38449         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
38450     return SDValue();
38451 
38452   // Quit if not used as a boolean value.
38453   if (CC != X86::COND_E && CC != X86::COND_NE)
38454     return SDValue();
38455 
38456   // Check CMP operands. One of them should be 0 or 1 and the other should be
38457   // an SetCC or extended from it.
38458   SDValue Op1 = Cmp.getOperand(0);
38459   SDValue Op2 = Cmp.getOperand(1);
38460 
38461   SDValue SetCC;
38462   const ConstantSDNode* C = nullptr;
38463   bool needOppositeCond = (CC == X86::COND_E);
38464   bool checkAgainstTrue = false; // Is it a comparison against 1?
38465 
38466   if ((C = dyn_cast<ConstantSDNode>(Op1)))
38467     SetCC = Op2;
38468   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
38469     SetCC = Op1;
38470   else // Quit if all operands are not constants.
38471     return SDValue();
38472 
38473   if (C->getZExtValue() == 1) {
38474     needOppositeCond = !needOppositeCond;
38475     checkAgainstTrue = true;
38476   } else if (C->getZExtValue() != 0)
38477     // Quit if the constant is neither 0 or 1.
38478     return SDValue();
38479 
38480   bool truncatedToBoolWithAnd = false;
38481   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
38482   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
38483          SetCC.getOpcode() == ISD::TRUNCATE ||
38484          SetCC.getOpcode() == ISD::AND) {
38485     if (SetCC.getOpcode() == ISD::AND) {
38486       int OpIdx = -1;
38487       if (isOneConstant(SetCC.getOperand(0)))
38488         OpIdx = 1;
38489       if (isOneConstant(SetCC.getOperand(1)))
38490         OpIdx = 0;
38491       if (OpIdx < 0)
38492         break;
38493       SetCC = SetCC.getOperand(OpIdx);
38494       truncatedToBoolWithAnd = true;
38495     } else
38496       SetCC = SetCC.getOperand(0);
38497   }
38498 
38499   switch (SetCC.getOpcode()) {
38500   case X86ISD::SETCC_CARRY:
38501     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
38502     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
38503     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
38504     // truncated to i1 using 'and'.
38505     if (checkAgainstTrue && !truncatedToBoolWithAnd)
38506       break;
38507     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
38508            "Invalid use of SETCC_CARRY!");
38509     LLVM_FALLTHROUGH;
38510   case X86ISD::SETCC:
38511     // Set the condition code or opposite one if necessary.
38512     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
38513     if (needOppositeCond)
38514       CC = X86::GetOppositeBranchCondition(CC);
38515     return SetCC.getOperand(1);
38516   case X86ISD::CMOV: {
38517     // Check whether false/true value has canonical one, i.e. 0 or 1.
38518     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
38519     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
38520     // Quit if true value is not a constant.
38521     if (!TVal)
38522       return SDValue();
38523     // Quit if false value is not a constant.
38524     if (!FVal) {
38525       SDValue Op = SetCC.getOperand(0);
38526       // Skip 'zext' or 'trunc' node.
38527       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
38528           Op.getOpcode() == ISD::TRUNCATE)
38529         Op = Op.getOperand(0);
38530       // A special case for rdrand/rdseed, where 0 is set if false cond is
38531       // found.
38532       if ((Op.getOpcode() != X86ISD::RDRAND &&
38533            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
38534         return SDValue();
38535     }
38536     // Quit if false value is not the constant 0 or 1.
38537     bool FValIsFalse = true;
38538     if (FVal && FVal->getZExtValue() != 0) {
38539       if (FVal->getZExtValue() != 1)
38540         return SDValue();
38541       // If FVal is 1, opposite cond is needed.
38542       needOppositeCond = !needOppositeCond;
38543       FValIsFalse = false;
38544     }
38545     // Quit if TVal is not the constant opposite of FVal.
38546     if (FValIsFalse && TVal->getZExtValue() != 1)
38547       return SDValue();
38548     if (!FValIsFalse && TVal->getZExtValue() != 0)
38549       return SDValue();
38550     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
38551     if (needOppositeCond)
38552       CC = X86::GetOppositeBranchCondition(CC);
38553     return SetCC.getOperand(3);
38554   }
38555   }
38556 
38557   return SDValue();
38558 }
38559 
38560 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
38561 /// Match:
38562 ///   (X86or (X86setcc) (X86setcc))
38563 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
checkBoolTestAndOrSetCCCombine(SDValue Cond,X86::CondCode & CC0,X86::CondCode & CC1,SDValue & Flags,bool & isAnd)38564 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
38565                                            X86::CondCode &CC1, SDValue &Flags,
38566                                            bool &isAnd) {
38567   if (Cond->getOpcode() == X86ISD::CMP) {
38568     if (!isNullConstant(Cond->getOperand(1)))
38569       return false;
38570 
38571     Cond = Cond->getOperand(0);
38572   }
38573 
38574   isAnd = false;
38575 
38576   SDValue SetCC0, SetCC1;
38577   switch (Cond->getOpcode()) {
38578   default: return false;
38579   case ISD::AND:
38580   case X86ISD::AND:
38581     isAnd = true;
38582     LLVM_FALLTHROUGH;
38583   case ISD::OR:
38584   case X86ISD::OR:
38585     SetCC0 = Cond->getOperand(0);
38586     SetCC1 = Cond->getOperand(1);
38587     break;
38588   };
38589 
38590   // Make sure we have SETCC nodes, using the same flags value.
38591   if (SetCC0.getOpcode() != X86ISD::SETCC ||
38592       SetCC1.getOpcode() != X86ISD::SETCC ||
38593       SetCC0->getOperand(1) != SetCC1->getOperand(1))
38594     return false;
38595 
38596   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
38597   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
38598   Flags = SetCC0->getOperand(1);
38599   return true;
38600 }
38601 
38602 // When legalizing carry, we create carries via add X, -1
38603 // If that comes from an actual carry, via setcc, we use the
38604 // carry directly.
combineCarryThroughADD(SDValue EFLAGS,SelectionDAG & DAG)38605 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
38606   if (EFLAGS.getOpcode() == X86ISD::ADD) {
38607     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
38608       SDValue Carry = EFLAGS.getOperand(0);
38609       while (Carry.getOpcode() == ISD::TRUNCATE ||
38610              Carry.getOpcode() == ISD::ZERO_EXTEND ||
38611              Carry.getOpcode() == ISD::SIGN_EXTEND ||
38612              Carry.getOpcode() == ISD::ANY_EXTEND ||
38613              (Carry.getOpcode() == ISD::AND &&
38614               isOneConstant(Carry.getOperand(1))))
38615         Carry = Carry.getOperand(0);
38616       if (Carry.getOpcode() == X86ISD::SETCC ||
38617           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
38618         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
38619         uint64_t CarryCC = Carry.getConstantOperandVal(0);
38620         SDValue CarryOp1 = Carry.getOperand(1);
38621         if (CarryCC == X86::COND_B)
38622           return CarryOp1;
38623         if (CarryCC == X86::COND_A) {
38624           // Try to convert COND_A into COND_B in an attempt to facilitate
38625           // materializing "setb reg".
38626           //
38627           // Do not flip "e > c", where "c" is a constant, because Cmp
38628           // instruction cannot take an immediate as its first operand.
38629           //
38630           if (CarryOp1.getOpcode() == X86ISD::SUB &&
38631               CarryOp1.getNode()->hasOneUse() &&
38632               CarryOp1.getValueType().isInteger() &&
38633               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
38634             SDValue SubCommute =
38635                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
38636                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
38637             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
38638           }
38639         }
38640         // If this is a check of the z flag of an add with 1, switch to the
38641         // C flag.
38642         if (CarryCC == X86::COND_E &&
38643             CarryOp1.getOpcode() == X86ISD::ADD &&
38644             isOneConstant(CarryOp1.getOperand(1)))
38645           return CarryOp1;
38646       }
38647     }
38648   }
38649 
38650   return SDValue();
38651 }
38652 
38653 /// Optimize an EFLAGS definition used according to the condition code \p CC
38654 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
38655 /// uses of chain values.
combineSetCCEFLAGS(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)38656 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
38657                                   SelectionDAG &DAG,
38658                                   const X86Subtarget &Subtarget) {
38659   if (CC == X86::COND_B)
38660     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
38661       return Flags;
38662 
38663   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
38664     return R;
38665   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
38666 }
38667 
38668 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
combineCMov(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38669 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
38670                            TargetLowering::DAGCombinerInfo &DCI,
38671                            const X86Subtarget &Subtarget) {
38672   SDLoc DL(N);
38673 
38674   SDValue FalseOp = N->getOperand(0);
38675   SDValue TrueOp = N->getOperand(1);
38676   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
38677   SDValue Cond = N->getOperand(3);
38678 
38679   // cmov X, X, ?, ? --> X
38680   if (TrueOp == FalseOp)
38681     return TrueOp;
38682 
38683   // Try to simplify the EFLAGS and condition code operands.
38684   // We can't always do this as FCMOV only supports a subset of X86 cond.
38685   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
38686     if (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC)) {
38687       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
38688                        Flags};
38689       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
38690     }
38691   }
38692 
38693   // If this is a select between two integer constants, try to do some
38694   // optimizations.  Note that the operands are ordered the opposite of SELECT
38695   // operands.
38696   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
38697     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
38698       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
38699       // larger than FalseC (the false value).
38700       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
38701         CC = X86::GetOppositeBranchCondition(CC);
38702         std::swap(TrueC, FalseC);
38703         std::swap(TrueOp, FalseOp);
38704       }
38705 
38706       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
38707       // This is efficient for any integer data type (including i8/i16) and
38708       // shift amount.
38709       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
38710         Cond = getSETCC(CC, Cond, DL, DAG);
38711 
38712         // Zero extend the condition if needed.
38713         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
38714 
38715         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
38716         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
38717                            DAG.getConstant(ShAmt, DL, MVT::i8));
38718         return Cond;
38719       }
38720 
38721       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
38722       // for any integer data type, including i8/i16.
38723       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
38724         Cond = getSETCC(CC, Cond, DL, DAG);
38725 
38726         // Zero extend the condition if needed.
38727         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
38728                            FalseC->getValueType(0), Cond);
38729         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
38730                            SDValue(FalseC, 0));
38731         return Cond;
38732       }
38733 
38734       // Optimize cases that will turn into an LEA instruction.  This requires
38735       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
38736       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
38737         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
38738         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
38739                "Implicit constant truncation");
38740 
38741         bool isFastMultiplier = false;
38742         if (Diff.ult(10)) {
38743           switch (Diff.getZExtValue()) {
38744           default: break;
38745           case 1:  // result = add base, cond
38746           case 2:  // result = lea base(    , cond*2)
38747           case 3:  // result = lea base(cond, cond*2)
38748           case 4:  // result = lea base(    , cond*4)
38749           case 5:  // result = lea base(cond, cond*4)
38750           case 8:  // result = lea base(    , cond*8)
38751           case 9:  // result = lea base(cond, cond*8)
38752             isFastMultiplier = true;
38753             break;
38754           }
38755         }
38756 
38757         if (isFastMultiplier) {
38758           Cond = getSETCC(CC, Cond, DL ,DAG);
38759           // Zero extend the condition if needed.
38760           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
38761                              Cond);
38762           // Scale the condition by the difference.
38763           if (Diff != 1)
38764             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
38765                                DAG.getConstant(Diff, DL, Cond.getValueType()));
38766 
38767           // Add the base if non-zero.
38768           if (FalseC->getAPIntValue() != 0)
38769             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
38770                                SDValue(FalseC, 0));
38771           return Cond;
38772         }
38773       }
38774     }
38775   }
38776 
38777   // Handle these cases:
38778   //   (select (x != c), e, c) -> select (x != c), e, x),
38779   //   (select (x == c), c, e) -> select (x == c), x, e)
38780   // where the c is an integer constant, and the "select" is the combination
38781   // of CMOV and CMP.
38782   //
38783   // The rationale for this change is that the conditional-move from a constant
38784   // needs two instructions, however, conditional-move from a register needs
38785   // only one instruction.
38786   //
38787   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
38788   //  some instruction-combining opportunities. This opt needs to be
38789   //  postponed as late as possible.
38790   //
38791   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
38792     // the DCI.xxxx conditions are provided to postpone the optimization as
38793     // late as possible.
38794 
38795     ConstantSDNode *CmpAgainst = nullptr;
38796     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
38797         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
38798         !isa<ConstantSDNode>(Cond.getOperand(0))) {
38799 
38800       if (CC == X86::COND_NE &&
38801           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
38802         CC = X86::GetOppositeBranchCondition(CC);
38803         std::swap(TrueOp, FalseOp);
38804       }
38805 
38806       if (CC == X86::COND_E &&
38807           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
38808         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
38809                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
38810         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
38811       }
38812     }
38813   }
38814 
38815   // Fold and/or of setcc's to double CMOV:
38816   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
38817   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
38818   //
38819   // This combine lets us generate:
38820   //   cmovcc1 (jcc1 if we don't have CMOV)
38821   //   cmovcc2 (same)
38822   // instead of:
38823   //   setcc1
38824   //   setcc2
38825   //   and/or
38826   //   cmovne (jne if we don't have CMOV)
38827   // When we can't use the CMOV instruction, it might increase branch
38828   // mispredicts.
38829   // When we can use CMOV, or when there is no mispredict, this improves
38830   // throughput and reduces register pressure.
38831   //
38832   if (CC == X86::COND_NE) {
38833     SDValue Flags;
38834     X86::CondCode CC0, CC1;
38835     bool isAndSetCC;
38836     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
38837       if (isAndSetCC) {
38838         std::swap(FalseOp, TrueOp);
38839         CC0 = X86::GetOppositeBranchCondition(CC0);
38840         CC1 = X86::GetOppositeBranchCondition(CC1);
38841       }
38842 
38843       SDValue LOps[] = {FalseOp, TrueOp,
38844                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
38845       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
38846       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
38847                        Flags};
38848       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
38849       return CMOV;
38850     }
38851   }
38852 
38853   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
38854   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
38855   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
38856   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
38857   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
38858       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
38859     SDValue Add = TrueOp;
38860     SDValue Const = FalseOp;
38861     // Canonicalize the condition code for easier matching and output.
38862     if (CC == X86::COND_E)
38863       std::swap(Add, Const);
38864 
38865     // We might have replaced the constant in the cmov with the LHS of the
38866     // compare. If so change it to the RHS of the compare.
38867     if (Const == Cond.getOperand(0))
38868       Const = Cond.getOperand(1);
38869 
38870     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
38871     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
38872         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
38873         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
38874          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
38875         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
38876       EVT VT = N->getValueType(0);
38877       // This should constant fold.
38878       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
38879       SDValue CMov =
38880           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
38881                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
38882       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
38883     }
38884   }
38885 
38886   return SDValue();
38887 }
38888 
38889 /// Different mul shrinking modes.
38890 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
38891 
canReduceVMulWidth(SDNode * N,SelectionDAG & DAG,ShrinkMode & Mode)38892 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
38893   EVT VT = N->getOperand(0).getValueType();
38894   if (VT.getScalarSizeInBits() != 32)
38895     return false;
38896 
38897   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
38898   unsigned SignBits[2] = {1, 1};
38899   bool IsPositive[2] = {false, false};
38900   for (unsigned i = 0; i < 2; i++) {
38901     SDValue Opd = N->getOperand(i);
38902 
38903     SignBits[i] = DAG.ComputeNumSignBits(Opd);
38904     IsPositive[i] = DAG.SignBitIsZero(Opd);
38905   }
38906 
38907   bool AllPositive = IsPositive[0] && IsPositive[1];
38908   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
38909   // When ranges are from -128 ~ 127, use MULS8 mode.
38910   if (MinSignBits >= 25)
38911     Mode = ShrinkMode::MULS8;
38912   // When ranges are from 0 ~ 255, use MULU8 mode.
38913   else if (AllPositive && MinSignBits >= 24)
38914     Mode = ShrinkMode::MULU8;
38915   // When ranges are from -32768 ~ 32767, use MULS16 mode.
38916   else if (MinSignBits >= 17)
38917     Mode = ShrinkMode::MULS16;
38918   // When ranges are from 0 ~ 65535, use MULU16 mode.
38919   else if (AllPositive && MinSignBits >= 16)
38920     Mode = ShrinkMode::MULU16;
38921   else
38922     return false;
38923   return true;
38924 }
38925 
38926 /// When the operands of vector mul are extended from smaller size values,
38927 /// like i8 and i16, the type of mul may be shrinked to generate more
38928 /// efficient code. Two typical patterns are handled:
38929 /// Pattern1:
38930 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
38931 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
38932 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
38933 ///     %5 = mul <N x i32> %2, %4
38934 ///
38935 /// Pattern2:
38936 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
38937 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
38938 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
38939 ///     %5 = mul <N x i32> %2, %4
38940 ///
38941 /// There are four mul shrinking modes:
38942 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
38943 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
38944 /// generate pmullw+sext32 for it (MULS8 mode).
38945 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
38946 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
38947 /// generate pmullw+zext32 for it (MULU8 mode).
38948 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
38949 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
38950 /// generate pmullw+pmulhw for it (MULS16 mode).
38951 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
38952 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
38953 /// generate pmullw+pmulhuw for it (MULU16 mode).
reduceVMULWidth(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38954 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
38955                                const X86Subtarget &Subtarget) {
38956   // Check for legality
38957   // pmullw/pmulhw are not supported by SSE.
38958   if (!Subtarget.hasSSE2())
38959     return SDValue();
38960 
38961   // Check for profitability
38962   // pmulld is supported since SSE41. It is better to use pmulld
38963   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
38964   // the expansion.
38965   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
38966   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
38967     return SDValue();
38968 
38969   ShrinkMode Mode;
38970   if (!canReduceVMulWidth(N, DAG, Mode))
38971     return SDValue();
38972 
38973   SDLoc DL(N);
38974   SDValue N0 = N->getOperand(0);
38975   SDValue N1 = N->getOperand(1);
38976   EVT VT = N->getOperand(0).getValueType();
38977   unsigned NumElts = VT.getVectorNumElements();
38978   if ((NumElts % 2) != 0)
38979     return SDValue();
38980 
38981   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
38982 
38983   // Shrink the operands of mul.
38984   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
38985   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
38986 
38987   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
38988   // lower part is needed.
38989   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
38990   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
38991     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
38992                                                    : ISD::SIGN_EXTEND,
38993                        DL, VT, MulLo);
38994 
38995   MVT ResVT = MVT::getVectorVT(MVT::i32, NumElts / 2);
38996   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
38997   // the higher part is also needed.
38998   SDValue MulHi =
38999       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
39000                   ReducedVT, NewN0, NewN1);
39001 
39002   // Repack the lower part and higher part result of mul into a wider
39003   // result.
39004   // Generate shuffle functioning as punpcklwd.
39005   SmallVector<int, 16> ShuffleMask(NumElts);
39006   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
39007     ShuffleMask[2 * i] = i;
39008     ShuffleMask[2 * i + 1] = i + NumElts;
39009   }
39010   SDValue ResLo =
39011       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
39012   ResLo = DAG.getBitcast(ResVT, ResLo);
39013   // Generate shuffle functioning as punpckhwd.
39014   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
39015     ShuffleMask[2 * i] = i + NumElts / 2;
39016     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
39017   }
39018   SDValue ResHi =
39019       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
39020   ResHi = DAG.getBitcast(ResVT, ResHi);
39021   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
39022 }
39023 
combineMulSpecial(uint64_t MulAmt,SDNode * N,SelectionDAG & DAG,EVT VT,const SDLoc & DL)39024 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
39025                                  EVT VT, const SDLoc &DL) {
39026 
39027   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
39028     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
39029                                  DAG.getConstant(Mult, DL, VT));
39030     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
39031                          DAG.getConstant(Shift, DL, MVT::i8));
39032     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
39033                          N->getOperand(0));
39034     return Result;
39035   };
39036 
39037   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
39038     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
39039                                  DAG.getConstant(Mul1, DL, VT));
39040     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
39041                          DAG.getConstant(Mul2, DL, VT));
39042     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
39043                          N->getOperand(0));
39044     return Result;
39045   };
39046 
39047   switch (MulAmt) {
39048   default:
39049     break;
39050   case 11:
39051     // mul x, 11 => add ((shl (mul x, 5), 1), x)
39052     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
39053   case 21:
39054     // mul x, 21 => add ((shl (mul x, 5), 2), x)
39055     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
39056   case 41:
39057     // mul x, 41 => add ((shl (mul x, 5), 3), x)
39058     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
39059   case 22:
39060     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
39061     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
39062                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
39063   case 19:
39064     // mul x, 19 => add ((shl (mul x, 9), 1), x)
39065     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
39066   case 37:
39067     // mul x, 37 => add ((shl (mul x, 9), 2), x)
39068     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
39069   case 73:
39070     // mul x, 73 => add ((shl (mul x, 9), 3), x)
39071     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
39072   case 13:
39073     // mul x, 13 => add ((shl (mul x, 3), 2), x)
39074     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
39075   case 23:
39076     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
39077     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
39078   case 26:
39079     // mul x, 26 => add ((mul (mul x, 5), 5), x)
39080     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
39081   case 28:
39082     // mul x, 28 => add ((mul (mul x, 9), 3), x)
39083     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
39084   case 29:
39085     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
39086     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
39087                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
39088   }
39089 
39090   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
39091   // by a single LEA.
39092   // First check if this a sum of two power of 2s because that's easy. Then
39093   // count how many zeros are up to the first bit.
39094   // TODO: We can do this even without LEA at a cost of two shifts and an add.
39095   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
39096     unsigned ScaleShift = countTrailingZeros(MulAmt);
39097     if (ScaleShift >= 1 && ScaleShift < 4) {
39098       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
39099       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39100                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
39101       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39102                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
39103       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
39104     }
39105   }
39106 
39107   return SDValue();
39108 }
39109 
39110 // If the upper 17 bits of each element are zero then we can use PMADDWD,
39111 // which is always at least as quick as PMULLD, except on KNL.
combineMulToPMADDWD(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39112 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
39113                                    const X86Subtarget &Subtarget) {
39114   if (!Subtarget.hasSSE2())
39115     return SDValue();
39116 
39117   if (Subtarget.isPMADDWDSlow())
39118     return SDValue();
39119 
39120   EVT VT = N->getValueType(0);
39121 
39122   // Only support vXi32 vectors.
39123   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
39124     return SDValue();
39125 
39126   // Make sure the vXi16 type is legal. This covers the AVX512 without BWI case.
39127   // Also allow v2i32 if it will be widened.
39128   MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
39129   if (VT != MVT::v2i32 && !DAG.getTargetLoweringInfo().isTypeLegal(WVT))
39130     return SDValue();
39131 
39132   SDValue N0 = N->getOperand(0);
39133   SDValue N1 = N->getOperand(1);
39134 
39135   // If we are zero extending two steps without SSE4.1, its better to reduce
39136   // the vmul width instead.
39137   if (!Subtarget.hasSSE41() &&
39138       (N0.getOpcode() == ISD::ZERO_EXTEND &&
39139        N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
39140       (N1.getOpcode() == ISD::ZERO_EXTEND &&
39141        N1.getOperand(0).getScalarValueSizeInBits() <= 8))
39142     return SDValue();
39143 
39144   APInt Mask17 = APInt::getHighBitsSet(32, 17);
39145   if (!DAG.MaskedValueIsZero(N1, Mask17) ||
39146       !DAG.MaskedValueIsZero(N0, Mask17))
39147     return SDValue();
39148 
39149   // Use SplitOpsAndApply to handle AVX splitting.
39150   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
39151                            ArrayRef<SDValue> Ops) {
39152     MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
39153     return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
39154   };
39155   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
39156                           { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
39157                           PMADDWDBuilder);
39158 }
39159 
combineMulToPMULDQ(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39160 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
39161                                   const X86Subtarget &Subtarget) {
39162   if (!Subtarget.hasSSE2())
39163     return SDValue();
39164 
39165   EVT VT = N->getValueType(0);
39166 
39167   // Only support vXi64 vectors.
39168   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
39169       VT.getVectorNumElements() < 2 ||
39170       !isPowerOf2_32(VT.getVectorNumElements()))
39171     return SDValue();
39172 
39173   SDValue N0 = N->getOperand(0);
39174   SDValue N1 = N->getOperand(1);
39175 
39176   // MULDQ returns the 64-bit result of the signed multiplication of the lower
39177   // 32-bits. We can lower with this if the sign bits stretch that far.
39178   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
39179       DAG.ComputeNumSignBits(N1) > 32) {
39180     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
39181                             ArrayRef<SDValue> Ops) {
39182       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
39183     };
39184     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
39185                             PMULDQBuilder, /*CheckBWI*/false);
39186   }
39187 
39188   // If the upper bits are zero we can use a single pmuludq.
39189   APInt Mask = APInt::getHighBitsSet(64, 32);
39190   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
39191     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
39192                              ArrayRef<SDValue> Ops) {
39193       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
39194     };
39195     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
39196                             PMULUDQBuilder, /*CheckBWI*/false);
39197   }
39198 
39199   return SDValue();
39200 }
39201 
39202 /// Optimize a single multiply with constant into two operations in order to
39203 /// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
combineMul(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39204 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
39205                           TargetLowering::DAGCombinerInfo &DCI,
39206                           const X86Subtarget &Subtarget) {
39207   EVT VT = N->getValueType(0);
39208 
39209   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
39210     return V;
39211 
39212   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
39213     return V;
39214 
39215   if (DCI.isBeforeLegalize() && VT.isVector())
39216     return reduceVMULWidth(N, DAG, Subtarget);
39217 
39218   if (!MulConstantOptimization)
39219     return SDValue();
39220   // An imul is usually smaller than the alternative sequence.
39221   if (DAG.getMachineFunction().getFunction().hasMinSize())
39222     return SDValue();
39223 
39224   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
39225     return SDValue();
39226 
39227   if (VT != MVT::i64 && VT != MVT::i32)
39228     return SDValue();
39229 
39230   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
39231   if (!C)
39232     return SDValue();
39233   if (isPowerOf2_64(C->getZExtValue()))
39234     return SDValue();
39235 
39236   int64_t SignMulAmt = C->getSExtValue();
39237   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
39238   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
39239 
39240   SDLoc DL(N);
39241   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
39242     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
39243                                  DAG.getConstant(AbsMulAmt, DL, VT));
39244     if (SignMulAmt < 0)
39245       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
39246                            NewMul);
39247 
39248     return NewMul;
39249   }
39250 
39251   uint64_t MulAmt1 = 0;
39252   uint64_t MulAmt2 = 0;
39253   if ((AbsMulAmt % 9) == 0) {
39254     MulAmt1 = 9;
39255     MulAmt2 = AbsMulAmt / 9;
39256   } else if ((AbsMulAmt % 5) == 0) {
39257     MulAmt1 = 5;
39258     MulAmt2 = AbsMulAmt / 5;
39259   } else if ((AbsMulAmt % 3) == 0) {
39260     MulAmt1 = 3;
39261     MulAmt2 = AbsMulAmt / 3;
39262   }
39263 
39264   SDValue NewMul;
39265   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
39266   if (MulAmt2 &&
39267       (isPowerOf2_64(MulAmt2) ||
39268        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
39269 
39270     if (isPowerOf2_64(MulAmt2) &&
39271         !(SignMulAmt >= 0 && N->hasOneUse() &&
39272           N->use_begin()->getOpcode() == ISD::ADD))
39273       // If second multiplifer is pow2, issue it first. We want the multiply by
39274       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
39275       // is an add. Only do this for positive multiply amounts since the
39276       // negate would prevent it from being used as an address mode anyway.
39277       std::swap(MulAmt1, MulAmt2);
39278 
39279     if (isPowerOf2_64(MulAmt1))
39280       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39281                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
39282     else
39283       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
39284                            DAG.getConstant(MulAmt1, DL, VT));
39285 
39286     if (isPowerOf2_64(MulAmt2))
39287       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
39288                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
39289     else
39290       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
39291                            DAG.getConstant(MulAmt2, DL, VT));
39292 
39293     // Negate the result.
39294     if (SignMulAmt < 0)
39295       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
39296                            NewMul);
39297   } else if (!Subtarget.slowLEA())
39298     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
39299 
39300   if (!NewMul) {
39301     assert(C->getZExtValue() != 0 &&
39302            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
39303            "Both cases that could cause potential overflows should have "
39304            "already been handled.");
39305     if (isPowerOf2_64(AbsMulAmt - 1)) {
39306       // (mul x, 2^N + 1) => (add (shl x, N), x)
39307       NewMul = DAG.getNode(
39308           ISD::ADD, DL, VT, N->getOperand(0),
39309           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39310                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
39311                                       MVT::i8)));
39312       // To negate, subtract the number from zero
39313       if (SignMulAmt < 0)
39314         NewMul = DAG.getNode(ISD::SUB, DL, VT,
39315                              DAG.getConstant(0, DL, VT), NewMul);
39316     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
39317       // (mul x, 2^N - 1) => (sub (shl x, N), x)
39318       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39319                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
39320                                            DL, MVT::i8));
39321       // To negate, reverse the operands of the subtract.
39322       if (SignMulAmt < 0)
39323         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
39324       else
39325         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
39326     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
39327       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
39328       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39329                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
39330                                            DL, MVT::i8));
39331       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
39332       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
39333     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
39334       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
39335       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
39336                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
39337                                            DL, MVT::i8));
39338       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
39339       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
39340     }
39341   }
39342 
39343   return NewMul;
39344 }
39345 
combineShiftLeft(SDNode * N,SelectionDAG & DAG)39346 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
39347   SDValue N0 = N->getOperand(0);
39348   SDValue N1 = N->getOperand(1);
39349   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
39350   EVT VT = N0.getValueType();
39351 
39352   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
39353   // since the result of setcc_c is all zero's or all ones.
39354   if (VT.isInteger() && !VT.isVector() &&
39355       N1C && N0.getOpcode() == ISD::AND &&
39356       N0.getOperand(1).getOpcode() == ISD::Constant) {
39357     SDValue N00 = N0.getOperand(0);
39358     APInt Mask = N0.getConstantOperandAPInt(1);
39359     Mask <<= N1C->getAPIntValue();
39360     bool MaskOK = false;
39361     // We can handle cases concerning bit-widening nodes containing setcc_c if
39362     // we carefully interrogate the mask to make sure we are semantics
39363     // preserving.
39364     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
39365     // of the underlying setcc_c operation if the setcc_c was zero extended.
39366     // Consider the following example:
39367     //   zext(setcc_c)                 -> i32 0x0000FFFF
39368     //   c1                            -> i32 0x0000FFFF
39369     //   c2                            -> i32 0x00000001
39370     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
39371     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
39372     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
39373       MaskOK = true;
39374     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
39375                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
39376       MaskOK = true;
39377     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
39378                 N00.getOpcode() == ISD::ANY_EXTEND) &&
39379                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
39380       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
39381     }
39382     if (MaskOK && Mask != 0) {
39383       SDLoc DL(N);
39384       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
39385     }
39386   }
39387 
39388   // Hardware support for vector shifts is sparse which makes us scalarize the
39389   // vector operations in many cases. Also, on sandybridge ADD is faster than
39390   // shl.
39391   // (shl V, 1) -> add V,V
39392   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
39393     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
39394       assert(N0.getValueType().isVector() && "Invalid vector shift type");
39395       // We shift all of the values by one. In many cases we do not have
39396       // hardware support for this operation. This is better expressed as an ADD
39397       // of two values.
39398       if (N1SplatC->isOne())
39399         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
39400     }
39401 
39402   return SDValue();
39403 }
39404 
combineShiftRightArithmetic(SDNode * N,SelectionDAG & DAG)39405 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG) {
39406   SDValue N0 = N->getOperand(0);
39407   SDValue N1 = N->getOperand(1);
39408   EVT VT = N0.getValueType();
39409   unsigned Size = VT.getSizeInBits();
39410 
39411   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
39412   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
39413   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
39414   // depending on sign of (SarConst - [56,48,32,24,16])
39415 
39416   // sexts in X86 are MOVs. The MOVs have the same code size
39417   // as above SHIFTs (only SHIFT on 1 has lower code size).
39418   // However the MOVs have 2 advantages to a SHIFT:
39419   // 1. MOVs can write to a register that differs from source
39420   // 2. MOVs accept memory operands
39421 
39422   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
39423       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
39424       N0.getOperand(1).getOpcode() != ISD::Constant)
39425     return SDValue();
39426 
39427   SDValue N00 = N0.getOperand(0);
39428   SDValue N01 = N0.getOperand(1);
39429   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
39430   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
39431   EVT CVT = N1.getValueType();
39432 
39433   if (SarConst.isNegative())
39434     return SDValue();
39435 
39436   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
39437     unsigned ShiftSize = SVT.getSizeInBits();
39438     // skipping types without corresponding sext/zext and
39439     // ShlConst that is not one of [56,48,32,24,16]
39440     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
39441       continue;
39442     SDLoc DL(N);
39443     SDValue NN =
39444         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
39445     SarConst = SarConst - (Size - ShiftSize);
39446     if (SarConst == 0)
39447       return NN;
39448     else if (SarConst.isNegative())
39449       return DAG.getNode(ISD::SHL, DL, VT, NN,
39450                          DAG.getConstant(-SarConst, DL, CVT));
39451     else
39452       return DAG.getNode(ISD::SRA, DL, VT, NN,
39453                          DAG.getConstant(SarConst, DL, CVT));
39454   }
39455   return SDValue();
39456 }
39457 
combineShiftRightLogical(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)39458 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
39459                                         TargetLowering::DAGCombinerInfo &DCI) {
39460   SDValue N0 = N->getOperand(0);
39461   SDValue N1 = N->getOperand(1);
39462   EVT VT = N0.getValueType();
39463 
39464   // Only do this on the last DAG combine as it can interfere with other
39465   // combines.
39466   if (!DCI.isAfterLegalizeDAG())
39467     return SDValue();
39468 
39469   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
39470   // TODO: This is a generic DAG combine that became an x86-only combine to
39471   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
39472   // and-not ('andn').
39473   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
39474     return SDValue();
39475 
39476   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
39477   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
39478   if (!ShiftC || !AndC)
39479     return SDValue();
39480 
39481   // If we can shrink the constant mask below 8-bits or 32-bits, then this
39482   // transform should reduce code size. It may also enable secondary transforms
39483   // from improved known-bits analysis or instruction selection.
39484   APInt MaskVal = AndC->getAPIntValue();
39485 
39486   // If this can be matched by a zero extend, don't optimize.
39487   if (MaskVal.isMask()) {
39488     unsigned TO = MaskVal.countTrailingOnes();
39489     if (TO >= 8 && isPowerOf2_32(TO))
39490       return SDValue();
39491   }
39492 
39493   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
39494   unsigned OldMaskSize = MaskVal.getMinSignedBits();
39495   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
39496   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
39497       (OldMaskSize > 32 && NewMaskSize <= 32)) {
39498     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
39499     SDLoc DL(N);
39500     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
39501     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
39502     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
39503   }
39504   return SDValue();
39505 }
39506 
combineVectorPack(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39507 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
39508                                  TargetLowering::DAGCombinerInfo &DCI,
39509                                  const X86Subtarget &Subtarget) {
39510   unsigned Opcode = N->getOpcode();
39511   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
39512          "Unexpected shift opcode");
39513 
39514   EVT VT = N->getValueType(0);
39515   SDValue N0 = N->getOperand(0);
39516   SDValue N1 = N->getOperand(1);
39517   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
39518   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
39519   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
39520          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
39521          "Unexpected PACKSS/PACKUS input type");
39522 
39523   bool IsSigned = (X86ISD::PACKSS == Opcode);
39524 
39525   // Constant Folding.
39526   APInt UndefElts0, UndefElts1;
39527   SmallVector<APInt, 32> EltBits0, EltBits1;
39528   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
39529       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
39530       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
39531       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
39532     unsigned NumLanes = VT.getSizeInBits() / 128;
39533     unsigned NumDstElts = VT.getVectorNumElements();
39534     unsigned NumSrcElts = NumDstElts / 2;
39535     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
39536     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
39537 
39538     APInt Undefs(NumDstElts, 0);
39539     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
39540     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
39541       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
39542         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
39543         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
39544         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
39545 
39546         if (UndefElts[SrcIdx]) {
39547           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
39548           continue;
39549         }
39550 
39551         APInt &Val = EltBits[SrcIdx];
39552         if (IsSigned) {
39553           // PACKSS: Truncate signed value with signed saturation.
39554           // Source values less than dst minint are saturated to minint.
39555           // Source values greater than dst maxint are saturated to maxint.
39556           if (Val.isSignedIntN(DstBitsPerElt))
39557             Val = Val.trunc(DstBitsPerElt);
39558           else if (Val.isNegative())
39559             Val = APInt::getSignedMinValue(DstBitsPerElt);
39560           else
39561             Val = APInt::getSignedMaxValue(DstBitsPerElt);
39562         } else {
39563           // PACKUS: Truncate signed value with unsigned saturation.
39564           // Source values less than zero are saturated to zero.
39565           // Source values greater than dst maxuint are saturated to maxuint.
39566           if (Val.isIntN(DstBitsPerElt))
39567             Val = Val.trunc(DstBitsPerElt);
39568           else if (Val.isNegative())
39569             Val = APInt::getNullValue(DstBitsPerElt);
39570           else
39571             Val = APInt::getAllOnesValue(DstBitsPerElt);
39572         }
39573         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
39574       }
39575     }
39576 
39577     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
39578   }
39579 
39580   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
39581   // truncate to create a larger truncate.
39582   if (Subtarget.hasAVX512() &&
39583       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
39584       N0.getOperand(0).getValueType() == MVT::v8i32) {
39585     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
39586         (!IsSigned &&
39587          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
39588       if (Subtarget.hasVLX())
39589         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
39590 
39591       // Widen input to v16i32 so we can truncate that.
39592       SDLoc dl(N);
39593       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
39594                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
39595       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
39596     }
39597   }
39598 
39599   // Attempt to combine as shuffle.
39600   SDValue Op(N, 0);
39601   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
39602     return Res;
39603 
39604   return SDValue();
39605 }
39606 
combineVectorShiftVar(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39607 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
39608                                      TargetLowering::DAGCombinerInfo &DCI,
39609                                      const X86Subtarget &Subtarget) {
39610   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
39611           X86ISD::VSRL == N->getOpcode()) &&
39612          "Unexpected shift opcode");
39613   EVT VT = N->getValueType(0);
39614   SDValue N0 = N->getOperand(0);
39615   SDValue N1 = N->getOperand(1);
39616 
39617   // Shift zero -> zero.
39618   if (ISD::isBuildVectorAllZeros(N0.getNode()))
39619     return DAG.getConstant(0, SDLoc(N), VT);
39620 
39621   // Detect constant shift amounts.
39622   APInt UndefElts;
39623   SmallVector<APInt, 32> EltBits;
39624   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
39625     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
39626     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
39627                                       EltBits[0].getZExtValue(), DAG);
39628   }
39629 
39630   APInt KnownUndef, KnownZero;
39631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39632   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
39633   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
39634                                      KnownZero, DCI))
39635     return SDValue(N, 0);
39636 
39637   return SDValue();
39638 }
39639 
combineVectorShiftImm(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39640 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
39641                                      TargetLowering::DAGCombinerInfo &DCI,
39642                                      const X86Subtarget &Subtarget) {
39643   unsigned Opcode = N->getOpcode();
39644   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
39645           X86ISD::VSRLI == Opcode) &&
39646          "Unexpected shift opcode");
39647   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
39648   EVT VT = N->getValueType(0);
39649   SDValue N0 = N->getOperand(0);
39650   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
39651   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
39652          "Unexpected value type");
39653   assert(N->getOperand(1).getValueType() == MVT::i8 &&
39654          "Unexpected shift amount type");
39655 
39656   // Out of range logical bit shifts are guaranteed to be zero.
39657   // Out of range arithmetic bit shifts splat the sign bit.
39658   unsigned ShiftVal = N->getConstantOperandVal(1);
39659   if (ShiftVal >= NumBitsPerElt) {
39660     if (LogicalShift)
39661       return DAG.getConstant(0, SDLoc(N), VT);
39662     else
39663       ShiftVal = NumBitsPerElt - 1;
39664   }
39665 
39666   // Shift N0 by zero -> N0.
39667   if (!ShiftVal)
39668     return N0;
39669 
39670   // Shift zero -> zero.
39671   if (ISD::isBuildVectorAllZeros(N0.getNode()))
39672     return DAG.getConstant(0, SDLoc(N), VT);
39673 
39674   // Fold (VSRAI (VSRAI X, C1), C2) --> (VSRAI X, (C1 + C2)) with (C1 + C2)
39675   // clamped to (NumBitsPerElt - 1).
39676   if (Opcode == X86ISD::VSRAI && N0.getOpcode() == X86ISD::VSRAI) {
39677     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
39678     unsigned NewShiftVal = ShiftVal + ShiftVal2;
39679     if (NewShiftVal >= NumBitsPerElt)
39680       NewShiftVal = NumBitsPerElt - 1;
39681     return DAG.getNode(X86ISD::VSRAI, SDLoc(N), VT, N0.getOperand(0),
39682                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
39683   }
39684 
39685   // We can decode 'whole byte' logical bit shifts as shuffles.
39686   if (LogicalShift && (ShiftVal % 8) == 0) {
39687     SDValue Op(N, 0);
39688     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
39689       return Res;
39690   }
39691 
39692   // Constant Folding.
39693   APInt UndefElts;
39694   SmallVector<APInt, 32> EltBits;
39695   if (N->isOnlyUserOf(N0.getNode()) &&
39696       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
39697     assert(EltBits.size() == VT.getVectorNumElements() &&
39698            "Unexpected shift value type");
39699     for (APInt &Elt : EltBits) {
39700       if (X86ISD::VSHLI == Opcode)
39701         Elt <<= ShiftVal;
39702       else if (X86ISD::VSRAI == Opcode)
39703         Elt.ashrInPlace(ShiftVal);
39704       else
39705         Elt.lshrInPlace(ShiftVal);
39706     }
39707     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
39708   }
39709 
39710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39711   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
39712                                APInt::getAllOnesValue(NumBitsPerElt), DCI))
39713     return SDValue(N, 0);
39714 
39715   return SDValue();
39716 }
39717 
combineVectorInsert(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39718 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
39719                                    TargetLowering::DAGCombinerInfo &DCI,
39720                                    const X86Subtarget &Subtarget) {
39721   EVT VT = N->getValueType(0);
39722   assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||
39723           (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16)) &&
39724          "Unexpected vector insertion");
39725 
39726   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
39727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39728   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
39729                                APInt::getAllOnesValue(NumBitsPerElt), DCI))
39730     return SDValue(N, 0);
39731 
39732   // Attempt to combine PINSRB/PINSRW patterns to a shuffle.
39733   SDValue Op(N, 0);
39734   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
39735     return Res;
39736 
39737   return SDValue();
39738 }
39739 
39740 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
39741 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
39742 /// OR -> CMPNEQSS.
combineCompareEqual(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39743 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
39744                                    TargetLowering::DAGCombinerInfo &DCI,
39745                                    const X86Subtarget &Subtarget) {
39746   unsigned opcode;
39747 
39748   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
39749   // we're requiring SSE2 for both.
39750   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
39751     SDValue N0 = N->getOperand(0);
39752     SDValue N1 = N->getOperand(1);
39753     SDValue CMP0 = N0.getOperand(1);
39754     SDValue CMP1 = N1.getOperand(1);
39755     SDLoc DL(N);
39756 
39757     // The SETCCs should both refer to the same CMP.
39758     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
39759       return SDValue();
39760 
39761     SDValue CMP00 = CMP0->getOperand(0);
39762     SDValue CMP01 = CMP0->getOperand(1);
39763     EVT     VT    = CMP00.getValueType();
39764 
39765     if (VT == MVT::f32 || VT == MVT::f64) {
39766       bool ExpectingFlags = false;
39767       // Check for any users that want flags:
39768       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
39769            !ExpectingFlags && UI != UE; ++UI)
39770         switch (UI->getOpcode()) {
39771         default:
39772         case ISD::BR_CC:
39773         case ISD::BRCOND:
39774         case ISD::SELECT:
39775           ExpectingFlags = true;
39776           break;
39777         case ISD::CopyToReg:
39778         case ISD::SIGN_EXTEND:
39779         case ISD::ZERO_EXTEND:
39780         case ISD::ANY_EXTEND:
39781           break;
39782         }
39783 
39784       if (!ExpectingFlags) {
39785         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
39786         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
39787 
39788         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
39789           X86::CondCode tmp = cc0;
39790           cc0 = cc1;
39791           cc1 = tmp;
39792         }
39793 
39794         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
39795             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
39796           // FIXME: need symbolic constants for these magic numbers.
39797           // See X86ATTInstPrinter.cpp:printSSECC().
39798           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
39799           if (Subtarget.hasAVX512()) {
39800             SDValue FSetCC =
39801                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
39802                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
39803             // Need to fill with zeros to ensure the bitcast will produce zeroes
39804             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
39805             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
39806                                       DAG.getConstant(0, DL, MVT::v16i1),
39807                                       FSetCC, DAG.getIntPtrConstant(0, DL));
39808             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
39809                                       N->getSimpleValueType(0));
39810           }
39811           SDValue OnesOrZeroesF =
39812               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
39813                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
39814 
39815           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
39816           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
39817 
39818           if (is64BitFP && !Subtarget.is64Bit()) {
39819             // On a 32-bit target, we cannot bitcast the 64-bit float to a
39820             // 64-bit integer, since that's not a legal type. Since
39821             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
39822             // bits, but can do this little dance to extract the lowest 32 bits
39823             // and work with those going forward.
39824             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
39825                                            OnesOrZeroesF);
39826             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
39827             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
39828                                         Vector32, DAG.getIntPtrConstant(0, DL));
39829             IntVT = MVT::i32;
39830           }
39831 
39832           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
39833           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
39834                                       DAG.getConstant(1, DL, IntVT));
39835           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
39836                                               ANDed);
39837           return OneBitOfTruth;
39838         }
39839       }
39840     }
39841   }
39842   return SDValue();
39843 }
39844 
39845 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
combineANDXORWithAllOnesIntoANDNP(SDNode * N,SelectionDAG & DAG)39846 static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
39847   assert(N->getOpcode() == ISD::AND);
39848 
39849   MVT VT = N->getSimpleValueType(0);
39850   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
39851     return SDValue();
39852 
39853   SDValue X, Y;
39854   SDValue N0 = N->getOperand(0);
39855   SDValue N1 = N->getOperand(1);
39856 
39857   if (SDValue Not = IsNOT(N0, DAG)) {
39858     X = Not;
39859     Y = N1;
39860   } else if (SDValue Not = IsNOT(N1, DAG)) {
39861     X = Not;
39862     Y = N0;
39863   } else
39864     return SDValue();
39865 
39866   X = DAG.getBitcast(VT, X);
39867   Y = DAG.getBitcast(VT, Y);
39868   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
39869 }
39870 
39871 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
39872 // register. In most cases we actually compare or select YMM-sized registers
39873 // and mixing the two types creates horrible code. This method optimizes
39874 // some of the transition sequences.
39875 // Even with AVX-512 this is still useful for removing casts around logical
39876 // operations on vXi1 mask types.
PromoteMaskArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39877 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
39878                                      const X86Subtarget &Subtarget) {
39879   EVT VT = N->getValueType(0);
39880   assert(VT.isVector() && "Expected vector type");
39881 
39882   assert((N->getOpcode() == ISD::ANY_EXTEND ||
39883           N->getOpcode() == ISD::ZERO_EXTEND ||
39884           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
39885 
39886   SDValue Narrow = N->getOperand(0);
39887   EVT NarrowVT = Narrow.getValueType();
39888 
39889   if (Narrow->getOpcode() != ISD::XOR &&
39890       Narrow->getOpcode() != ISD::AND &&
39891       Narrow->getOpcode() != ISD::OR)
39892     return SDValue();
39893 
39894   SDValue N0  = Narrow->getOperand(0);
39895   SDValue N1  = Narrow->getOperand(1);
39896   SDLoc DL(Narrow);
39897 
39898   // The Left side has to be a trunc.
39899   if (N0.getOpcode() != ISD::TRUNCATE)
39900     return SDValue();
39901 
39902   // The type of the truncated inputs.
39903   if (N0.getOperand(0).getValueType() != VT)
39904     return SDValue();
39905 
39906   // The right side has to be a 'trunc' or a constant vector.
39907   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
39908                   N1.getOperand(0).getValueType() == VT;
39909   if (!RHSTrunc &&
39910       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
39911     return SDValue();
39912 
39913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39914 
39915   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), VT))
39916     return SDValue();
39917 
39918   // Set N0 and N1 to hold the inputs to the new wide operation.
39919   N0 = N0.getOperand(0);
39920   if (RHSTrunc)
39921     N1 = N1.getOperand(0);
39922   else
39923     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
39924 
39925   // Generate the wide operation.
39926   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, VT, N0, N1);
39927   unsigned Opcode = N->getOpcode();
39928   switch (Opcode) {
39929   default: llvm_unreachable("Unexpected opcode");
39930   case ISD::ANY_EXTEND:
39931     return Op;
39932   case ISD::ZERO_EXTEND:
39933     return DAG.getZeroExtendInReg(Op, DL, NarrowVT.getScalarType());
39934   case ISD::SIGN_EXTEND:
39935     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
39936                        Op, DAG.getValueType(NarrowVT));
39937   }
39938 }
39939 
39940 /// If both input operands of a logic op are being cast from floating point
39941 /// types, try to convert this into a floating point logic node to avoid
39942 /// unnecessary moves from SSE to integer registers.
convertIntLogicToFPLogic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39943 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
39944                                         const X86Subtarget &Subtarget) {
39945   EVT VT = N->getValueType(0);
39946   SDValue N0 = N->getOperand(0);
39947   SDValue N1 = N->getOperand(1);
39948   SDLoc DL(N);
39949 
39950   if (N0.getOpcode() != ISD::BITCAST || N1.getOpcode() != ISD::BITCAST)
39951     return SDValue();
39952 
39953   SDValue N00 = N0.getOperand(0);
39954   SDValue N10 = N1.getOperand(0);
39955   EVT N00Type = N00.getValueType();
39956   EVT N10Type = N10.getValueType();
39957 
39958   // Ensure that both types are the same and are legal scalar fp types.
39959   if (N00Type != N10Type ||
39960       !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
39961         (Subtarget.hasSSE2() && N00Type == MVT::f64)))
39962     return SDValue();
39963 
39964   unsigned FPOpcode;
39965   switch (N->getOpcode()) {
39966   default: llvm_unreachable("Unexpected input node for FP logic conversion");
39967   case ISD::AND: FPOpcode = X86ISD::FAND; break;
39968   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
39969   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
39970   }
39971 
39972   SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
39973   return DAG.getBitcast(VT, FPLogic);
39974 }
39975 
39976 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
39977 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
39978 /// with a shift-right to eliminate loading the vector constant mask value.
combineAndMaskToShift(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39979 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
39980                                      const X86Subtarget &Subtarget) {
39981   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
39982   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
39983   EVT VT0 = Op0.getValueType();
39984   EVT VT1 = Op1.getValueType();
39985 
39986   if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
39987     return SDValue();
39988 
39989   APInt SplatVal;
39990   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
39991       !SplatVal.isMask())
39992     return SDValue();
39993 
39994   // Don't prevent creation of ANDN.
39995   if (isBitwiseNot(Op0))
39996     return SDValue();
39997 
39998   if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
39999     return SDValue();
40000 
40001   unsigned EltBitWidth = VT0.getScalarSizeInBits();
40002   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
40003     return SDValue();
40004 
40005   SDLoc DL(N);
40006   unsigned ShiftVal = SplatVal.countTrailingOnes();
40007   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
40008   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
40009   return DAG.getBitcast(N->getValueType(0), Shift);
40010 }
40011 
40012 // Get the index node from the lowered DAG of a GEP IR instruction with one
40013 // indexing dimension.
getIndexFromUnindexedLoad(LoadSDNode * Ld)40014 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
40015   if (Ld->isIndexed())
40016     return SDValue();
40017 
40018   SDValue Base = Ld->getBasePtr();
40019 
40020   if (Base.getOpcode() != ISD::ADD)
40021     return SDValue();
40022 
40023   SDValue ShiftedIndex = Base.getOperand(0);
40024 
40025   if (ShiftedIndex.getOpcode() != ISD::SHL)
40026     return SDValue();
40027 
40028   return ShiftedIndex.getOperand(0);
40029 
40030 }
40031 
hasBZHI(const X86Subtarget & Subtarget,MVT VT)40032 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
40033   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
40034     switch (VT.getSizeInBits()) {
40035     default: return false;
40036     case 64: return Subtarget.is64Bit() ? true : false;
40037     case 32: return true;
40038     }
40039   }
40040   return false;
40041 }
40042 
40043 // This function recognizes cases where X86 bzhi instruction can replace and
40044 // 'and-load' sequence.
40045 // In case of loading integer value from an array of constants which is defined
40046 // as follows:
40047 //
40048 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
40049 //
40050 // then applying a bitwise and on the result with another input.
40051 // It's equivalent to performing bzhi (zero high bits) on the input, with the
40052 // same index of the load.
combineAndLoadToBZHI(SDNode * Node,SelectionDAG & DAG,const X86Subtarget & Subtarget)40053 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
40054                                     const X86Subtarget &Subtarget) {
40055   MVT VT = Node->getSimpleValueType(0);
40056   SDLoc dl(Node);
40057 
40058   // Check if subtarget has BZHI instruction for the node's type
40059   if (!hasBZHI(Subtarget, VT))
40060     return SDValue();
40061 
40062   // Try matching the pattern for both operands.
40063   for (unsigned i = 0; i < 2; i++) {
40064     SDValue N = Node->getOperand(i);
40065     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
40066 
40067      // continue if the operand is not a load instruction
40068     if (!Ld)
40069       return SDValue();
40070 
40071     const Value *MemOp = Ld->getMemOperand()->getValue();
40072 
40073     if (!MemOp)
40074       return SDValue();
40075 
40076     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
40077       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
40078         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
40079 
40080           Constant *Init = GV->getInitializer();
40081           Type *Ty = Init->getType();
40082           if (!isa<ConstantDataArray>(Init) ||
40083               !Ty->getArrayElementType()->isIntegerTy() ||
40084               Ty->getArrayElementType()->getScalarSizeInBits() !=
40085                   VT.getSizeInBits() ||
40086               Ty->getArrayNumElements() >
40087                   Ty->getArrayElementType()->getScalarSizeInBits())
40088             continue;
40089 
40090           // Check if the array's constant elements are suitable to our case.
40091           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
40092           bool ConstantsMatch = true;
40093           for (uint64_t j = 0; j < ArrayElementCount; j++) {
40094             ConstantInt *Elem =
40095                 dyn_cast<ConstantInt>(Init->getAggregateElement(j));
40096             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
40097               ConstantsMatch = false;
40098               break;
40099             }
40100           }
40101           if (!ConstantsMatch)
40102             continue;
40103 
40104           // Do the transformation (For 32-bit type):
40105           // -> (and (load arr[idx]), inp)
40106           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
40107           //    that will be replaced with one bzhi instruction.
40108           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
40109           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
40110 
40111           // Get the Node which indexes into the array.
40112           SDValue Index = getIndexFromUnindexedLoad(Ld);
40113           if (!Index)
40114             return SDValue();
40115           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
40116 
40117           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
40118           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
40119 
40120           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
40121           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
40122 
40123           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
40124         }
40125       }
40126     }
40127   }
40128   return SDValue();
40129 }
40130 
40131 // Look for (and (ctpop X), 1) which is the IR form of __builtin_parity.
40132 // Turn it into series of XORs and a setnp.
combineParity(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40133 static SDValue combineParity(SDNode *N, SelectionDAG &DAG,
40134                              const X86Subtarget &Subtarget) {
40135   EVT VT = N->getValueType(0);
40136 
40137   // We only support 64-bit and 32-bit. 64-bit requires special handling
40138   // unless the 64-bit popcnt instruction is legal.
40139   if (VT != MVT::i32 && VT != MVT::i64)
40140     return SDValue();
40141 
40142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40143   if (TLI.isTypeLegal(VT) && TLI.isOperationLegal(ISD::CTPOP, VT))
40144     return SDValue();
40145 
40146   SDValue N0 = N->getOperand(0);
40147   SDValue N1 = N->getOperand(1);
40148 
40149   // LHS needs to be a single use CTPOP.
40150   if (N0.getOpcode() != ISD::CTPOP || !N0.hasOneUse())
40151     return SDValue();
40152 
40153   // RHS needs to be 1.
40154   if (!isOneConstant(N1))
40155     return SDValue();
40156 
40157   SDLoc DL(N);
40158   SDValue X = N0.getOperand(0);
40159 
40160   // If this is 64-bit, its always best to xor the two 32-bit pieces together
40161   // even if we have popcnt.
40162   if (VT == MVT::i64) {
40163     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
40164                              DAG.getNode(ISD::SRL, DL, VT, X,
40165                                          DAG.getConstant(32, DL, MVT::i8)));
40166     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
40167     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
40168     // Generate a 32-bit parity idiom. This will bring us back here if we need
40169     // to expand it too.
40170     SDValue Parity = DAG.getNode(ISD::AND, DL, MVT::i32,
40171                                  DAG.getNode(ISD::CTPOP, DL, MVT::i32, X),
40172                                  DAG.getConstant(1, DL, MVT::i32));
40173     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Parity);
40174   }
40175   assert(VT == MVT::i32 && "Unexpected VT!");
40176 
40177   // Xor the high and low 16-bits together using a 32-bit operation.
40178   SDValue Hi16 = DAG.getNode(ISD::SRL, DL, VT, X,
40179                              DAG.getConstant(16, DL, MVT::i8));
40180   X = DAG.getNode(ISD::XOR, DL, VT, X, Hi16);
40181 
40182   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
40183   // This should allow an h-reg to be used to save a shift.
40184   // FIXME: We only get an h-reg in 32-bit mode.
40185   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
40186                            DAG.getNode(ISD::SRL, DL, VT, X,
40187                                        DAG.getConstant(8, DL, MVT::i8)));
40188   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
40189   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
40190   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
40191 
40192   // Copy the inverse of the parity flag into a register with setcc.
40193   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
40194   // Zero extend to original type.
40195   return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0), Setnp);
40196 }
40197 
40198 
40199 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
40200 // Where C is a mask containing the same number of bits as the setcc and
40201 // where the setcc will freely 0 upper bits of k-register. We can replace the
40202 // undef in the concat with 0s and remove the AND. This mainly helps with
40203 // v2i1/v4i1 setcc being casted to scalar.
combineScalarAndWithMaskSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40204 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
40205                                              const X86Subtarget &Subtarget) {
40206   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
40207 
40208   EVT VT = N->getValueType(0);
40209 
40210   // Make sure this is an AND with constant. We will check the value of the
40211   // constant later.
40212   if (!isa<ConstantSDNode>(N->getOperand(1)))
40213     return SDValue();
40214 
40215   // This is implied by the ConstantSDNode.
40216   assert(!VT.isVector() && "Expected scalar VT!");
40217 
40218   if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
40219       !N->getOperand(0).hasOneUse() ||
40220       !N->getOperand(0).getOperand(0).hasOneUse())
40221     return SDValue();
40222 
40223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40224   SDValue Src = N->getOperand(0).getOperand(0);
40225   EVT SrcVT = Src.getValueType();
40226   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
40227       !TLI.isTypeLegal(SrcVT))
40228     return SDValue();
40229 
40230   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
40231     return SDValue();
40232 
40233   // We only care about the first subvector of the concat, we expect the
40234   // other subvectors to be ignored due to the AND if we make the change.
40235   SDValue SubVec = Src.getOperand(0);
40236   EVT SubVecVT = SubVec.getValueType();
40237 
40238   // First subvector should be a setcc with a legal result type. The RHS of the
40239   // AND should be a mask with this many bits.
40240   if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
40241       !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
40242     return SDValue();
40243 
40244   EVT SetccVT = SubVec.getOperand(0).getValueType();
40245   if (!TLI.isTypeLegal(SetccVT) ||
40246       !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
40247     return SDValue();
40248 
40249   if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
40250     return SDValue();
40251 
40252   // We passed all the checks. Rebuild the concat_vectors with zeroes
40253   // and cast it back to VT.
40254   SDLoc dl(N);
40255   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
40256                               DAG.getConstant(0, dl, SubVecVT));
40257   Ops[0] = SubVec;
40258   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
40259                                Ops);
40260   return DAG.getBitcast(VT, Concat);
40261 }
40262 
combineAnd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)40263 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
40264                           TargetLowering::DAGCombinerInfo &DCI,
40265                           const X86Subtarget &Subtarget) {
40266   EVT VT = N->getValueType(0);
40267 
40268   // If this is SSE1 only convert to FAND to avoid scalarization.
40269   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
40270     return DAG.getBitcast(
40271         MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
40272                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
40273                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
40274   }
40275 
40276   // Use a 32-bit and+zext if upper bits known zero.
40277   if (VT == MVT::i64 && Subtarget.is64Bit() &&
40278       !isa<ConstantSDNode>(N->getOperand(1))) {
40279     APInt HiMask = APInt::getHighBitsSet(64, 32);
40280     if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
40281         DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
40282       SDLoc dl(N);
40283       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
40284       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
40285       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
40286                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
40287     }
40288   }
40289 
40290   // This must be done before legalization has expanded the ctpop.
40291   if (SDValue V = combineParity(N, DAG, Subtarget))
40292     return V;
40293 
40294   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
40295   // TODO: Support multiple SrcOps.
40296   if (VT == MVT::i1) {
40297     SmallVector<SDValue, 2> SrcOps;
40298     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps) &&
40299         SrcOps.size() == 1) {
40300       SDLoc dl(N);
40301       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40302       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
40303       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40304       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
40305       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
40306         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
40307       if (Mask) {
40308         APInt AllBits = APInt::getAllOnesValue(NumElts);
40309         return DAG.getSetCC(dl, MVT::i1, Mask,
40310                             DAG.getConstant(AllBits, dl, MaskVT), ISD::SETEQ);
40311       }
40312     }
40313   }
40314 
40315   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
40316     return V;
40317 
40318   if (DCI.isBeforeLegalizeOps())
40319     return SDValue();
40320 
40321   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
40322     return R;
40323 
40324   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
40325     return FPLogic;
40326 
40327   if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
40328     return R;
40329 
40330   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
40331     return ShiftRight;
40332 
40333   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
40334     return R;
40335 
40336   // Attempt to recursively combine a bitmask AND with shuffles.
40337   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
40338     SDValue Op(N, 0);
40339     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
40340       return Res;
40341   }
40342 
40343   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
40344   if ((VT.getScalarSizeInBits() % 8) == 0 &&
40345       N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
40346       isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
40347     SDValue BitMask = N->getOperand(1);
40348     SDValue SrcVec = N->getOperand(0).getOperand(0);
40349     EVT SrcVecVT = SrcVec.getValueType();
40350 
40351     // Check that the constant bitmask masks whole bytes.
40352     APInt UndefElts;
40353     SmallVector<APInt, 64> EltBits;
40354     if (VT == SrcVecVT.getScalarType() &&
40355         N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
40356         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
40357         llvm::all_of(EltBits, [](APInt M) {
40358           return M.isNullValue() || M.isAllOnesValue();
40359         })) {
40360       unsigned NumElts = SrcVecVT.getVectorNumElements();
40361       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
40362       unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
40363 
40364       // Create a root shuffle mask from the byte mask and the extracted index.
40365       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
40366       for (unsigned i = 0; i != Scale; ++i) {
40367         if (UndefElts[i])
40368           continue;
40369         int VecIdx = Scale * Idx + i;
40370         ShuffleMask[VecIdx] =
40371             EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
40372       }
40373 
40374       if (SDValue Shuffle = combineX86ShufflesRecursively(
40375               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
40376               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
40377         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
40378                            N->getOperand(0).getOperand(1));
40379     }
40380   }
40381 
40382   return SDValue();
40383 }
40384 
40385 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
canonicalizeBitSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40386 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
40387                                      const X86Subtarget &Subtarget) {
40388   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
40389 
40390   MVT VT = N->getSimpleValueType(0);
40391   if (!VT.isVector() || (VT.getScalarSizeInBits() % 8) != 0)
40392     return SDValue();
40393 
40394   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
40395   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
40396   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
40397     return SDValue();
40398 
40399   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
40400   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
40401   bool UseVPTERNLOG = (Subtarget.hasAVX512() && VT.is512BitVector()) ||
40402                       Subtarget.hasVLX();
40403   if (!(Subtarget.hasXOP() || UseVPTERNLOG ||
40404         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
40405     return SDValue();
40406 
40407   // Attempt to extract constant byte masks.
40408   APInt UndefElts0, UndefElts1;
40409   SmallVector<APInt, 32> EltBits0, EltBits1;
40410   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
40411                                      false, false))
40412     return SDValue();
40413   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
40414                                      false, false))
40415     return SDValue();
40416 
40417   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
40418     // TODO - add UNDEF elts support.
40419     if (UndefElts0[i] || UndefElts1[i])
40420       return SDValue();
40421     if (EltBits0[i] != ~EltBits1[i])
40422       return SDValue();
40423   }
40424 
40425   SDLoc DL(N);
40426   SDValue X = N->getOperand(0);
40427   SDValue Y =
40428       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
40429                   DAG.getBitcast(VT, N1.getOperand(0)));
40430   return DAG.getNode(ISD::OR, DL, VT, X, Y);
40431 }
40432 
40433 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
matchLogicBlend(SDNode * N,SDValue & X,SDValue & Y,SDValue & Mask)40434 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
40435   if (N->getOpcode() != ISD::OR)
40436     return false;
40437 
40438   SDValue N0 = N->getOperand(0);
40439   SDValue N1 = N->getOperand(1);
40440 
40441   // Canonicalize AND to LHS.
40442   if (N1.getOpcode() == ISD::AND)
40443     std::swap(N0, N1);
40444 
40445   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
40446   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
40447     return false;
40448 
40449   Mask = N1.getOperand(0);
40450   X = N1.getOperand(1);
40451 
40452   // Check to see if the mask appeared in both the AND and ANDNP.
40453   if (N0.getOperand(0) == Mask)
40454     Y = N0.getOperand(1);
40455   else if (N0.getOperand(1) == Mask)
40456     Y = N0.getOperand(0);
40457   else
40458     return false;
40459 
40460   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
40461   // ANDNP combine allows other combines to happen that prevent matching.
40462   return true;
40463 }
40464 
40465 // Try to fold:
40466 //   (or (and (m, y), (pandn m, x)))
40467 // into:
40468 //   (vselect m, x, y)
40469 // As a special case, try to fold:
40470 //   (or (and (m, (sub 0, x)), (pandn m, x)))
40471 // into:
40472 //   (sub (xor X, M), M)
combineLogicBlendIntoPBLENDV(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40473 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
40474                                             const X86Subtarget &Subtarget) {
40475   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
40476 
40477   EVT VT = N->getValueType(0);
40478   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
40479         (VT.is256BitVector() && Subtarget.hasInt256())))
40480     return SDValue();
40481 
40482   SDValue X, Y, Mask;
40483   if (!matchLogicBlend(N, X, Y, Mask))
40484     return SDValue();
40485 
40486   // Validate that X, Y, and Mask are bitcasts, and see through them.
40487   Mask = peekThroughBitcasts(Mask);
40488   X = peekThroughBitcasts(X);
40489   Y = peekThroughBitcasts(Y);
40490 
40491   EVT MaskVT = Mask.getValueType();
40492   unsigned EltBits = MaskVT.getScalarSizeInBits();
40493 
40494   // TODO: Attempt to handle floating point cases as well?
40495   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
40496     return SDValue();
40497 
40498   SDLoc DL(N);
40499 
40500   // Attempt to combine to conditional negate: (sub (xor X, M), M)
40501   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
40502                                                            DAG, Subtarget))
40503     return Res;
40504 
40505   // PBLENDVB is only available on SSE 4.1.
40506   if (!Subtarget.hasSSE41())
40507     return SDValue();
40508 
40509   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
40510 
40511   X = DAG.getBitcast(BlendVT, X);
40512   Y = DAG.getBitcast(BlendVT, Y);
40513   Mask = DAG.getBitcast(BlendVT, Mask);
40514   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
40515   return DAG.getBitcast(VT, Mask);
40516 }
40517 
40518 // Helper function for combineOrCmpEqZeroToCtlzSrl
40519 // Transforms:
40520 //   seteq(cmp x, 0)
40521 //   into:
40522 //   srl(ctlz x), log2(bitsize(x))
40523 // Input pattern is checked by caller.
lowerX86CmpEqZeroToCtlzSrl(SDValue Op,EVT ExtTy,SelectionDAG & DAG)40524 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
40525                                           SelectionDAG &DAG) {
40526   SDValue Cmp = Op.getOperand(1);
40527   EVT VT = Cmp.getOperand(0).getValueType();
40528   unsigned Log2b = Log2_32(VT.getSizeInBits());
40529   SDLoc dl(Op);
40530   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
40531   // The result of the shift is true or false, and on X86, the 32-bit
40532   // encoding of shr and lzcnt is more desirable.
40533   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
40534   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
40535                             DAG.getConstant(Log2b, dl, MVT::i8));
40536   return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
40537 }
40538 
40539 // Try to transform:
40540 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
40541 //   into:
40542 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
40543 // Will also attempt to match more generic cases, eg:
40544 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
40545 // Only applies if the target supports the FastLZCNT feature.
combineOrCmpEqZeroToCtlzSrl(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)40546 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
40547                                            TargetLowering::DAGCombinerInfo &DCI,
40548                                            const X86Subtarget &Subtarget) {
40549   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
40550     return SDValue();
40551 
40552   auto isORCandidate = [](SDValue N) {
40553     return (N->getOpcode() == ISD::OR && N->hasOneUse());
40554   };
40555 
40556   // Check the zero extend is extending to 32-bit or more. The code generated by
40557   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
40558   // instructions to clear the upper bits.
40559   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
40560       !isORCandidate(N->getOperand(0)))
40561     return SDValue();
40562 
40563   // Check the node matches: setcc(eq, cmp 0)
40564   auto isSetCCCandidate = [](SDValue N) {
40565     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
40566            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
40567            N->getOperand(1).getOpcode() == X86ISD::CMP &&
40568            isNullConstant(N->getOperand(1).getOperand(1)) &&
40569            N->getOperand(1).getValueType().bitsGE(MVT::i32);
40570   };
40571 
40572   SDNode *OR = N->getOperand(0).getNode();
40573   SDValue LHS = OR->getOperand(0);
40574   SDValue RHS = OR->getOperand(1);
40575 
40576   // Save nodes matching or(or, setcc(eq, cmp 0)).
40577   SmallVector<SDNode *, 2> ORNodes;
40578   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
40579           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
40580     ORNodes.push_back(OR);
40581     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
40582     LHS = OR->getOperand(0);
40583     RHS = OR->getOperand(1);
40584   }
40585 
40586   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
40587   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
40588       !isORCandidate(SDValue(OR, 0)))
40589     return SDValue();
40590 
40591   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
40592   // to
40593   // or(srl(ctlz),srl(ctlz)).
40594   // The dag combiner can then fold it into:
40595   // srl(or(ctlz, ctlz)).
40596   EVT VT = OR->getValueType(0);
40597   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
40598   SDValue Ret, NewRHS;
40599   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
40600     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
40601 
40602   if (!Ret)
40603     return SDValue();
40604 
40605   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
40606   while (ORNodes.size() > 0) {
40607     OR = ORNodes.pop_back_val();
40608     LHS = OR->getOperand(0);
40609     RHS = OR->getOperand(1);
40610     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
40611     if (RHS->getOpcode() == ISD::OR)
40612       std::swap(LHS, RHS);
40613     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
40614     if (!NewRHS)
40615       return SDValue();
40616     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
40617   }
40618 
40619   if (Ret)
40620     Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
40621 
40622   return Ret;
40623 }
40624 
combineOrShiftToFunnelShift(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40625 static SDValue combineOrShiftToFunnelShift(SDNode *N, SelectionDAG &DAG,
40626                                            const X86Subtarget &Subtarget) {
40627   assert(N->getOpcode() == ISD::OR && "Expected ISD::OR node");
40628   SDValue N0 = N->getOperand(0);
40629   SDValue N1 = N->getOperand(1);
40630   EVT VT = N->getValueType(0);
40631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40632 
40633   if (!TLI.isOperationLegalOrCustom(ISD::FSHL, VT) ||
40634       !TLI.isOperationLegalOrCustom(ISD::FSHR, VT))
40635     return SDValue();
40636 
40637   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
40638   bool OptForSize = DAG.shouldOptForSize();
40639   unsigned Bits = VT.getScalarSizeInBits();
40640 
40641   // SHLD/SHRD instructions have lower register pressure, but on some
40642   // platforms they have higher latency than the equivalent
40643   // series of shifts/or that would otherwise be generated.
40644   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
40645   // have higher latencies and we are not optimizing for size.
40646   if (!OptForSize && Subtarget.isSHLDSlow())
40647     return SDValue();
40648 
40649   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
40650     std::swap(N0, N1);
40651   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
40652     return SDValue();
40653   if (!N0.hasOneUse() || !N1.hasOneUse())
40654     return SDValue();
40655 
40656   EVT ShiftVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
40657 
40658   SDValue ShAmt0 = N0.getOperand(1);
40659   if (ShAmt0.getValueType() != ShiftVT)
40660     return SDValue();
40661   SDValue ShAmt1 = N1.getOperand(1);
40662   if (ShAmt1.getValueType() != ShiftVT)
40663     return SDValue();
40664 
40665   // Peek through any modulo shift masks.
40666   SDValue ShMsk0;
40667   if (ShAmt0.getOpcode() == ISD::AND &&
40668       isa<ConstantSDNode>(ShAmt0.getOperand(1)) &&
40669       ShAmt0.getConstantOperandAPInt(1) == (Bits - 1)) {
40670     ShMsk0 = ShAmt0;
40671     ShAmt0 = ShAmt0.getOperand(0);
40672   }
40673   SDValue ShMsk1;
40674   if (ShAmt1.getOpcode() == ISD::AND &&
40675       isa<ConstantSDNode>(ShAmt1.getOperand(1)) &&
40676       ShAmt1.getConstantOperandAPInt(1) == (Bits - 1)) {
40677     ShMsk1 = ShAmt1;
40678     ShAmt1 = ShAmt1.getOperand(0);
40679   }
40680 
40681   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
40682     ShAmt0 = ShAmt0.getOperand(0);
40683   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
40684     ShAmt1 = ShAmt1.getOperand(0);
40685 
40686   SDLoc DL(N);
40687   unsigned Opc = ISD::FSHL;
40688   SDValue Op0 = N0.getOperand(0);
40689   SDValue Op1 = N1.getOperand(0);
40690   if (ShAmt0.getOpcode() == ISD::SUB || ShAmt0.getOpcode() == ISD::XOR) {
40691     Opc = ISD::FSHR;
40692     std::swap(Op0, Op1);
40693     std::swap(ShAmt0, ShAmt1);
40694     std::swap(ShMsk0, ShMsk1);
40695   }
40696 
40697   auto GetFunnelShift = [&DAG, &DL, VT, Opc, &ShiftVT](SDValue Op0, SDValue Op1,
40698                                                        SDValue Amt) {
40699     if (Opc == ISD::FSHR)
40700       std::swap(Op0, Op1);
40701     return DAG.getNode(Opc, DL, VT, Op0, Op1,
40702                        DAG.getNode(ISD::TRUNCATE, DL, ShiftVT, Amt));
40703   };
40704 
40705   // OR( SHL( X, C ), SRL( Y, 32 - C ) ) -> FSHL( X, Y, C )
40706   // OR( SRL( X, C ), SHL( Y, 32 - C ) ) -> FSHR( Y, X, C )
40707   // OR( SHL( X, C ), SRL( SRL( Y, 1 ), XOR( C, 31 ) ) ) -> FSHL( X, Y, C )
40708   // OR( SRL( X, C ), SHL( SHL( Y, 1 ), XOR( C, 31 ) ) ) -> FSHR( Y, X, C )
40709   // OR( SHL( X, AND( C, 31 ) ), SRL( Y, AND( 0 - C, 31 ) ) ) -> FSHL( X, Y, C )
40710   // OR( SRL( X, AND( C, 31 ) ), SHL( Y, AND( 0 - C, 31 ) ) ) -> FSHR( Y, X, C )
40711   if (ShAmt1.getOpcode() == ISD::SUB) {
40712     SDValue Sum = ShAmt1.getOperand(0);
40713     if (auto *SumC = dyn_cast<ConstantSDNode>(Sum)) {
40714       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
40715       if (ShAmt1Op1.getOpcode() == ISD::AND &&
40716           isa<ConstantSDNode>(ShAmt1Op1.getOperand(1)) &&
40717           ShAmt1Op1.getConstantOperandAPInt(1) == (Bits - 1)) {
40718         ShMsk1 = ShAmt1Op1;
40719         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
40720       }
40721       if (ShAmt1Op1.getOpcode() == ISD::TRUNCATE)
40722         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
40723       if ((SumC->getAPIntValue() == Bits ||
40724            (SumC->getAPIntValue() == 0 && ShMsk1)) &&
40725           ShAmt1Op1 == ShAmt0)
40726         return GetFunnelShift(Op0, Op1, ShAmt0);
40727     }
40728   } else if (auto *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
40729     auto *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
40730     if (ShAmt0C && (ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue()) == Bits)
40731       return GetFunnelShift(Op0, Op1, ShAmt0);
40732   } else if (ShAmt1.getOpcode() == ISD::XOR) {
40733     SDValue Mask = ShAmt1.getOperand(1);
40734     if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
40735       unsigned InnerShift = (ISD::FSHL == Opc ? ISD::SRL : ISD::SHL);
40736       SDValue ShAmt1Op0 = ShAmt1.getOperand(0);
40737       if (ShAmt1Op0.getOpcode() == ISD::TRUNCATE)
40738         ShAmt1Op0 = ShAmt1Op0.getOperand(0);
40739       if (MaskC->getSExtValue() == (Bits - 1) &&
40740           (ShAmt1Op0 == ShAmt0 || ShAmt1Op0 == ShMsk0)) {
40741         if (Op1.getOpcode() == InnerShift &&
40742             isa<ConstantSDNode>(Op1.getOperand(1)) &&
40743             Op1.getConstantOperandAPInt(1).isOneValue()) {
40744           return GetFunnelShift(Op0, Op1.getOperand(0), ShAmt0);
40745         }
40746         // Test for ADD( Y, Y ) as an equivalent to SHL( Y, 1 ).
40747         if (InnerShift == ISD::SHL && Op1.getOpcode() == ISD::ADD &&
40748             Op1.getOperand(0) == Op1.getOperand(1)) {
40749           return GetFunnelShift(Op0, Op1.getOperand(0), ShAmt0);
40750         }
40751       }
40752     }
40753   }
40754 
40755   return SDValue();
40756 }
40757 
combineOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)40758 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
40759                          TargetLowering::DAGCombinerInfo &DCI,
40760                          const X86Subtarget &Subtarget) {
40761   SDValue N0 = N->getOperand(0);
40762   SDValue N1 = N->getOperand(1);
40763   EVT VT = N->getValueType(0);
40764 
40765   // If this is SSE1 only convert to FOR to avoid scalarization.
40766   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
40767     return DAG.getBitcast(MVT::v4i32,
40768                           DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
40769                                       DAG.getBitcast(MVT::v4f32, N0),
40770                                       DAG.getBitcast(MVT::v4f32, N1)));
40771   }
40772 
40773   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
40774   // TODO: Support multiple SrcOps.
40775   if (VT == MVT::i1) {
40776     SmallVector<SDValue, 2> SrcOps;
40777     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps) &&
40778         SrcOps.size() == 1) {
40779       SDLoc dl(N);
40780       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40781       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
40782       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40783       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
40784       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
40785         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
40786       if (Mask) {
40787         APInt AllBits = APInt::getNullValue(NumElts);
40788         return DAG.getSetCC(dl, MVT::i1, Mask,
40789                             DAG.getConstant(AllBits, dl, MaskVT), ISD::SETNE);
40790       }
40791     }
40792   }
40793 
40794   if (DCI.isBeforeLegalizeOps())
40795     return SDValue();
40796 
40797   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
40798     return R;
40799 
40800   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
40801     return FPLogic;
40802 
40803   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
40804     return R;
40805 
40806   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
40807     return R;
40808 
40809   if (SDValue R = combineOrShiftToFunnelShift(N, DAG, Subtarget))
40810     return R;
40811 
40812   // Attempt to recursively combine an OR of shuffles.
40813   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
40814     SDValue Op(N, 0);
40815     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
40816       return Res;
40817   }
40818 
40819   return SDValue();
40820 }
40821 
40822 /// Try to turn tests against the signbit in the form of:
40823 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
40824 /// into:
40825 ///   SETGT(X, -1)
foldXorTruncShiftIntoCmp(SDNode * N,SelectionDAG & DAG)40826 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
40827   // This is only worth doing if the output type is i8 or i1.
40828   EVT ResultType = N->getValueType(0);
40829   if (ResultType != MVT::i8 && ResultType != MVT::i1)
40830     return SDValue();
40831 
40832   SDValue N0 = N->getOperand(0);
40833   SDValue N1 = N->getOperand(1);
40834 
40835   // We should be performing an xor against a truncated shift.
40836   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
40837     return SDValue();
40838 
40839   // Make sure we are performing an xor against one.
40840   if (!isOneConstant(N1))
40841     return SDValue();
40842 
40843   // SetCC on x86 zero extends so only act on this if it's a logical shift.
40844   SDValue Shift = N0.getOperand(0);
40845   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
40846     return SDValue();
40847 
40848   // Make sure we are truncating from one of i16, i32 or i64.
40849   EVT ShiftTy = Shift.getValueType();
40850   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
40851     return SDValue();
40852 
40853   // Make sure the shift amount extracts the sign bit.
40854   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
40855       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
40856     return SDValue();
40857 
40858   // Create a greater-than comparison against -1.
40859   // N.B. Using SETGE against 0 works but we want a canonical looking
40860   // comparison, using SETGT matches up with what TranslateX86CC.
40861   SDLoc DL(N);
40862   SDValue ShiftOp = Shift.getOperand(0);
40863   EVT ShiftOpTy = ShiftOp.getValueType();
40864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40865   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
40866                                                *DAG.getContext(), ResultType);
40867   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
40868                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
40869   if (SetCCResultType != ResultType)
40870     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
40871   return Cond;
40872 }
40873 
40874 /// Turn vector tests of the signbit in the form of:
40875 ///   xor (sra X, elt_size(X)-1), -1
40876 /// into:
40877 ///   pcmpgt X, -1
40878 ///
40879 /// This should be called before type legalization because the pattern may not
40880 /// persist after that.
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40881 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
40882                                          const X86Subtarget &Subtarget) {
40883   EVT VT = N->getValueType(0);
40884   if (!VT.isSimple())
40885     return SDValue();
40886 
40887   switch (VT.getSimpleVT().SimpleTy) {
40888   default: return SDValue();
40889   case MVT::v16i8:
40890   case MVT::v8i16:
40891   case MVT::v4i32:
40892   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
40893   case MVT::v32i8:
40894   case MVT::v16i16:
40895   case MVT::v8i32:
40896   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
40897   }
40898 
40899   // There must be a shift right algebraic before the xor, and the xor must be a
40900   // 'not' operation.
40901   SDValue Shift = N->getOperand(0);
40902   SDValue Ones = N->getOperand(1);
40903   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
40904       !ISD::isBuildVectorAllOnes(Ones.getNode()))
40905     return SDValue();
40906 
40907   // The shift should be smearing the sign bit across each vector element.
40908   auto *ShiftAmt =
40909       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
40910   if (!ShiftAmt ||
40911       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
40912     return SDValue();
40913 
40914   // Create a greater-than comparison against -1. We don't use the more obvious
40915   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
40916   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
40917 }
40918 
40919 /// Detect patterns of truncation with unsigned saturation:
40920 ///
40921 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
40922 ///   Return the source value x to be truncated or SDValue() if the pattern was
40923 ///   not matched.
40924 ///
40925 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
40926 ///   where C1 >= 0 and C2 is unsigned max of destination type.
40927 ///
40928 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
40929 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
40930 ///
40931 ///   These two patterns are equivalent to:
40932 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
40933 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
40934 ///   pattern was not matched.
detectUSatPattern(SDValue In,EVT VT,SelectionDAG & DAG,const SDLoc & DL)40935 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
40936                                  const SDLoc &DL) {
40937   EVT InVT = In.getValueType();
40938 
40939   // Saturation with truncation. We truncate from InVT to VT.
40940   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
40941          "Unexpected types for truncate operation");
40942 
40943   // Match min/max and return limit value as a parameter.
40944   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
40945     if (V.getOpcode() == Opcode &&
40946         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
40947       return V.getOperand(0);
40948     return SDValue();
40949   };
40950 
40951   APInt C1, C2;
40952   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
40953     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
40954     // the element size of the destination type.
40955     if (C2.isMask(VT.getScalarSizeInBits()))
40956       return UMin;
40957 
40958   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
40959     if (MatchMinMax(SMin, ISD::SMAX, C1))
40960       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
40961         return SMin;
40962 
40963   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
40964     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
40965       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
40966           C2.uge(C1)) {
40967         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
40968       }
40969 
40970   return SDValue();
40971 }
40972 
40973 /// Detect patterns of truncation with signed saturation:
40974 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
40975 ///                  signed_max_of_dest_type)) to dest_type)
40976 /// or:
40977 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
40978 ///                  signed_min_of_dest_type)) to dest_type).
40979 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
40980 /// Return the source value to be truncated or SDValue() if the pattern was not
40981 /// matched.
detectSSatPattern(SDValue In,EVT VT,bool MatchPackUS=false)40982 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
40983   unsigned NumDstBits = VT.getScalarSizeInBits();
40984   unsigned NumSrcBits = In.getScalarValueSizeInBits();
40985   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
40986 
40987   auto MatchMinMax = [](SDValue V, unsigned Opcode,
40988                         const APInt &Limit) -> SDValue {
40989     APInt C;
40990     if (V.getOpcode() == Opcode &&
40991         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
40992       return V.getOperand(0);
40993     return SDValue();
40994   };
40995 
40996   APInt SignedMax, SignedMin;
40997   if (MatchPackUS) {
40998     SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
40999     SignedMin = APInt(NumSrcBits, 0);
41000   } else {
41001     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
41002     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
41003   }
41004 
41005   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
41006     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
41007       return SMax;
41008 
41009   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
41010     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
41011       return SMin;
41012 
41013   return SDValue();
41014 }
41015 
combineTruncateWithSat(SDValue In,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)41016 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
41017                                       SelectionDAG &DAG,
41018                                       const X86Subtarget &Subtarget) {
41019   if (!Subtarget.hasSSE2() || !VT.isVector())
41020     return SDValue();
41021 
41022   EVT SVT = VT.getVectorElementType();
41023   EVT InVT = In.getValueType();
41024   EVT InSVT = InVT.getVectorElementType();
41025 
41026   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
41027   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
41028   // and concatenate at the same time. Then we can use a final vpmovuswb to
41029   // clip to 0-255.
41030   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
41031       InVT == MVT::v16i32 && VT == MVT::v16i8) {
41032     if (auto USatVal = detectSSatPattern(In, VT, true)) {
41033       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
41034       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
41035                                            DL, DAG, Subtarget);
41036       assert(Mid && "Failed to pack!");
41037       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
41038     }
41039   }
41040 
41041   // vXi32 truncate instructions are available with AVX512F.
41042   // vXi16 truncate instructions are only available with AVX512BW.
41043   // For 256-bit or smaller vectors, we require VLX.
41044   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
41045   // If the result type is 256-bits or larger and we have disable 512-bit
41046   // registers, we should go ahead and use the pack instructions if possible.
41047   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
41048                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
41049                       (InVT.getSizeInBits() > 128) &&
41050                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
41051                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
41052 
41053   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
41054       VT.getSizeInBits() >= 64 &&
41055       (SVT == MVT::i8 || SVT == MVT::i16) &&
41056       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
41057     if (auto USatVal = detectSSatPattern(In, VT, true)) {
41058       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
41059       // Only do this when the result is at least 64 bits or we'll leaving
41060       // dangling PACKSSDW nodes.
41061       if (SVT == MVT::i8 && InSVT == MVT::i32) {
41062         EVT MidVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
41063                                      VT.getVectorNumElements());
41064         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
41065                                              DAG, Subtarget);
41066         assert(Mid && "Failed to pack!");
41067         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
41068                                            Subtarget);
41069         assert(V && "Failed to pack!");
41070         return V;
41071       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
41072         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
41073                                       Subtarget);
41074     }
41075     if (auto SSatVal = detectSSatPattern(In, VT))
41076       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
41077                                     Subtarget);
41078   }
41079 
41080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41081   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
41082       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI())) {
41083     unsigned TruncOpc = 0;
41084     SDValue SatVal;
41085     if (auto SSatVal = detectSSatPattern(In, VT)) {
41086       SatVal = SSatVal;
41087       TruncOpc = X86ISD::VTRUNCS;
41088     } else if (auto USatVal = detectUSatPattern(In, VT, DAG, DL)) {
41089       SatVal = USatVal;
41090       TruncOpc = X86ISD::VTRUNCUS;
41091     }
41092     if (SatVal) {
41093       unsigned ResElts = VT.getVectorNumElements();
41094       // If the input type is less than 512 bits and we don't have VLX, we need
41095       // to widen to 512 bits.
41096       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
41097         unsigned NumConcats = 512 / InVT.getSizeInBits();
41098         ResElts *= NumConcats;
41099         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
41100         ConcatOps[0] = SatVal;
41101         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
41102                                 NumConcats * InVT.getVectorNumElements());
41103         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
41104       }
41105       // Widen the result if its narrower than 128 bits.
41106       if (ResElts * SVT.getSizeInBits() < 128)
41107         ResElts = 128 / SVT.getSizeInBits();
41108       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
41109       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
41110       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
41111                          DAG.getIntPtrConstant(0, DL));
41112     }
41113   }
41114 
41115   return SDValue();
41116 }
41117 
41118 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
41119 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
41120 /// X86ISD::AVG instruction.
detectAVGPattern(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)41121 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
41122                                 const X86Subtarget &Subtarget,
41123                                 const SDLoc &DL) {
41124   if (!VT.isVector())
41125     return SDValue();
41126   EVT InVT = In.getValueType();
41127   unsigned NumElems = VT.getVectorNumElements();
41128 
41129   EVT ScalarVT = VT.getVectorElementType();
41130   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
41131         NumElems >= 2 && isPowerOf2_32(NumElems)))
41132     return SDValue();
41133 
41134   // InScalarVT is the intermediate type in AVG pattern and it should be greater
41135   // than the original input type (i8/i16).
41136   EVT InScalarVT = InVT.getVectorElementType();
41137   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
41138     return SDValue();
41139 
41140   if (!Subtarget.hasSSE2())
41141     return SDValue();
41142 
41143   // Detect the following pattern:
41144   //
41145   //   %1 = zext <N x i8> %a to <N x i32>
41146   //   %2 = zext <N x i8> %b to <N x i32>
41147   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
41148   //   %4 = add nuw nsw <N x i32> %3, %2
41149   //   %5 = lshr <N x i32> %N, <i32 1 x N>
41150   //   %6 = trunc <N x i32> %5 to <N x i8>
41151   //
41152   // In AVX512, the last instruction can also be a trunc store.
41153   if (In.getOpcode() != ISD::SRL)
41154     return SDValue();
41155 
41156   // A lambda checking the given SDValue is a constant vector and each element
41157   // is in the range [Min, Max].
41158   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
41159     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
41160     if (!BV || !BV->isConstant())
41161       return false;
41162     for (SDValue Op : V->ops()) {
41163       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
41164       if (!C)
41165         return false;
41166       const APInt &Val = C->getAPIntValue();
41167       if (Val.ult(Min) || Val.ugt(Max))
41168         return false;
41169     }
41170     return true;
41171   };
41172 
41173   // Check if each element of the vector is right-shifted by one.
41174   auto LHS = In.getOperand(0);
41175   auto RHS = In.getOperand(1);
41176   if (!IsConstVectorInRange(RHS, 1, 1))
41177     return SDValue();
41178   if (LHS.getOpcode() != ISD::ADD)
41179     return SDValue();
41180 
41181   // Detect a pattern of a + b + 1 where the order doesn't matter.
41182   SDValue Operands[3];
41183   Operands[0] = LHS.getOperand(0);
41184   Operands[1] = LHS.getOperand(1);
41185 
41186   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41187                        ArrayRef<SDValue> Ops) {
41188     return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
41189   };
41190 
41191   // Take care of the case when one of the operands is a constant vector whose
41192   // element is in the range [1, 256].
41193   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
41194       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
41195       Operands[0].getOperand(0).getValueType() == VT) {
41196     // The pattern is detected. Subtract one from the constant vector, then
41197     // demote it and emit X86ISD::AVG instruction.
41198     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
41199     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
41200     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
41201     return SplitOpsAndApply(DAG, Subtarget, DL, VT,
41202                             { Operands[0].getOperand(0), Operands[1] },
41203                             AVGBuilder);
41204   }
41205 
41206   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
41207   // Match the or case only if its 'add-like' - can be replaced by an add.
41208   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
41209     if (ISD::ADD == V.getOpcode()) {
41210       Op0 = V.getOperand(0);
41211       Op1 = V.getOperand(1);
41212       return true;
41213     }
41214     if (ISD::ZERO_EXTEND != V.getOpcode())
41215       return false;
41216     V = V.getOperand(0);
41217     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
41218         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
41219       return false;
41220     Op0 = V.getOperand(0);
41221     Op1 = V.getOperand(1);
41222     return true;
41223   };
41224 
41225   SDValue Op0, Op1;
41226   if (FindAddLike(Operands[0], Op0, Op1))
41227     std::swap(Operands[0], Operands[1]);
41228   else if (!FindAddLike(Operands[1], Op0, Op1))
41229     return SDValue();
41230   Operands[2] = Op0;
41231   Operands[1] = Op1;
41232 
41233   // Now we have three operands of two additions. Check that one of them is a
41234   // constant vector with ones, and the other two can be promoted from i8/i16.
41235   for (int i = 0; i < 3; ++i) {
41236     if (!IsConstVectorInRange(Operands[i], 1, 1))
41237       continue;
41238     std::swap(Operands[i], Operands[2]);
41239 
41240     // Check if Operands[0] and Operands[1] are results of type promotion.
41241     for (int j = 0; j < 2; ++j)
41242       if (Operands[j].getValueType() != VT) {
41243         if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
41244             Operands[j].getOperand(0).getValueType() != VT)
41245           return SDValue();
41246         Operands[j] = Operands[j].getOperand(0);
41247       }
41248 
41249     // The pattern is detected, emit X86ISD::AVG instruction(s).
41250     return SplitOpsAndApply(DAG, Subtarget, DL, VT, {Operands[0], Operands[1]},
41251                             AVGBuilder);
41252   }
41253 
41254   return SDValue();
41255 }
41256 
combineLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41257 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
41258                            TargetLowering::DAGCombinerInfo &DCI,
41259                            const X86Subtarget &Subtarget) {
41260   LoadSDNode *Ld = cast<LoadSDNode>(N);
41261   EVT RegVT = Ld->getValueType(0);
41262   EVT MemVT = Ld->getMemoryVT();
41263   SDLoc dl(Ld);
41264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41265 
41266   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
41267   // into two 16-byte operations. Also split non-temporal aligned loads on
41268   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
41269   ISD::LoadExtType Ext = Ld->getExtensionType();
41270   bool Fast;
41271   unsigned Alignment = Ld->getAlignment();
41272   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
41273       Ext == ISD::NON_EXTLOAD &&
41274       ((Ld->isNonTemporal() && !Subtarget.hasInt256() && Alignment >= 16) ||
41275        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
41276                                *Ld->getMemOperand(), &Fast) &&
41277         !Fast))) {
41278     unsigned NumElems = RegVT.getVectorNumElements();
41279     if (NumElems < 2)
41280       return SDValue();
41281 
41282     unsigned HalfAlign = 16;
41283     SDValue Ptr1 = Ld->getBasePtr();
41284     SDValue Ptr2 = DAG.getMemBasePlusOffset(Ptr1, HalfAlign, dl);
41285     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
41286                                   NumElems / 2);
41287     SDValue Load1 =
41288         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
41289                     Alignment, Ld->getMemOperand()->getFlags());
41290     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
41291                                 Ld->getPointerInfo().getWithOffset(HalfAlign),
41292                                 MinAlign(Alignment, HalfAlign),
41293                                 Ld->getMemOperand()->getFlags());
41294     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
41295                              Load1.getValue(1), Load2.getValue(1));
41296 
41297     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
41298     return DCI.CombineTo(N, NewVec, TF, true);
41299   }
41300 
41301   // Bool vector load - attempt to cast to an integer, as we have good
41302   // (vXiY *ext(vXi1 bitcast(iX))) handling.
41303   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
41304       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
41305     unsigned NumElts = RegVT.getVectorNumElements();
41306     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
41307     if (TLI.isTypeLegal(IntVT)) {
41308       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
41309                                     Ld->getPointerInfo(), Alignment,
41310                                     Ld->getMemOperand()->getFlags());
41311       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
41312       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
41313     }
41314   }
41315 
41316   return SDValue();
41317 }
41318 
41319 /// If V is a build vector of boolean constants and exactly one of those
41320 /// constants is true, return the operand index of that true element.
41321 /// Otherwise, return -1.
getOneTrueElt(SDValue V)41322 static int getOneTrueElt(SDValue V) {
41323   // This needs to be a build vector of booleans.
41324   // TODO: Checking for the i1 type matches the IR definition for the mask,
41325   // but the mask check could be loosened to i8 or other types. That might
41326   // also require checking more than 'allOnesValue'; eg, the x86 HW
41327   // instructions only require that the MSB is set for each mask element.
41328   // The ISD::MSTORE comments/definition do not specify how the mask operand
41329   // is formatted.
41330   auto *BV = dyn_cast<BuildVectorSDNode>(V);
41331   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
41332     return -1;
41333 
41334   int TrueIndex = -1;
41335   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
41336   for (unsigned i = 0; i < NumElts; ++i) {
41337     const SDValue &Op = BV->getOperand(i);
41338     if (Op.isUndef())
41339       continue;
41340     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
41341     if (!ConstNode)
41342       return -1;
41343     if (ConstNode->getAPIntValue().isAllOnesValue()) {
41344       // If we already found a one, this is too many.
41345       if (TrueIndex >= 0)
41346         return -1;
41347       TrueIndex = i;
41348     }
41349   }
41350   return TrueIndex;
41351 }
41352 
41353 /// Given a masked memory load/store operation, return true if it has one mask
41354 /// bit set. If it has one mask bit set, then also return the memory address of
41355 /// the scalar element to load/store, the vector index to insert/extract that
41356 /// scalar element, and the alignment for the scalar memory access.
getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode * MaskedOp,SelectionDAG & DAG,SDValue & Addr,SDValue & Index,unsigned & Alignment)41357 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
41358                                          SelectionDAG &DAG, SDValue &Addr,
41359                                          SDValue &Index, unsigned &Alignment) {
41360   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
41361   if (TrueMaskElt < 0)
41362     return false;
41363 
41364   // Get the address of the one scalar element that is specified by the mask
41365   // using the appropriate offset from the base pointer.
41366   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
41367   Addr = MaskedOp->getBasePtr();
41368   if (TrueMaskElt != 0) {
41369     unsigned Offset = TrueMaskElt * EltVT.getStoreSize();
41370     Addr = DAG.getMemBasePlusOffset(Addr, Offset, SDLoc(MaskedOp));
41371   }
41372 
41373   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
41374   Alignment = MinAlign(MaskedOp->getAlignment(), EltVT.getStoreSize());
41375   return true;
41376 }
41377 
41378 /// If exactly one element of the mask is set for a non-extending masked load,
41379 /// it is a scalar load and vector insert.
41380 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
41381 /// mask have already been optimized in IR, so we don't bother with those here.
41382 static SDValue
reduceMaskedLoadToScalarLoad(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)41383 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
41384                              TargetLowering::DAGCombinerInfo &DCI) {
41385   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
41386   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
41387   // However, some target hooks may need to be added to know when the transform
41388   // is profitable. Endianness would also have to be considered.
41389 
41390   SDValue Addr, VecIndex;
41391   unsigned Alignment;
41392   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment))
41393     return SDValue();
41394 
41395   // Load the one scalar element that is specified by the mask using the
41396   // appropriate offset from the base pointer.
41397   SDLoc DL(ML);
41398   EVT VT = ML->getValueType(0);
41399   EVT EltVT = VT.getVectorElementType();
41400   SDValue Load =
41401       DAG.getLoad(EltVT, DL, ML->getChain(), Addr, ML->getPointerInfo(),
41402                   Alignment, ML->getMemOperand()->getFlags());
41403 
41404   // Insert the loaded element into the appropriate place in the vector.
41405   SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
41406                                ML->getPassThru(), Load, VecIndex);
41407   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
41408 }
41409 
41410 static SDValue
combineMaskedLoadConstantMask(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)41411 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
41412                               TargetLowering::DAGCombinerInfo &DCI) {
41413   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
41414   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
41415     return SDValue();
41416 
41417   SDLoc DL(ML);
41418   EVT VT = ML->getValueType(0);
41419 
41420   // If we are loading the first and last elements of a vector, it is safe and
41421   // always faster to load the whole vector. Replace the masked load with a
41422   // vector load and select.
41423   unsigned NumElts = VT.getVectorNumElements();
41424   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
41425   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
41426   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
41427   if (LoadFirstElt && LoadLastElt) {
41428     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
41429                                 ML->getMemOperand());
41430     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
41431                                   ML->getPassThru());
41432     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
41433   }
41434 
41435   // Convert a masked load with a constant mask into a masked load and a select.
41436   // This allows the select operation to use a faster kind of select instruction
41437   // (for example, vblendvps -> vblendps).
41438 
41439   // Don't try this if the pass-through operand is already undefined. That would
41440   // cause an infinite loop because that's what we're about to create.
41441   if (ML->getPassThru().isUndef())
41442     return SDValue();
41443 
41444   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
41445     return SDValue();
41446 
41447   // The new masked load has an undef pass-through operand. The select uses the
41448   // original pass-through operand.
41449   SDValue NewML = DAG.getMaskedLoad(
41450       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
41451       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
41452       ML->getAddressingMode(), ML->getExtensionType());
41453   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
41454                                 ML->getPassThru());
41455 
41456   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
41457 }
41458 
combineMaskedLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41459 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
41460                                  TargetLowering::DAGCombinerInfo &DCI,
41461                                  const X86Subtarget &Subtarget) {
41462   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
41463 
41464   // TODO: Expanding load with constant mask may be optimized as well.
41465   if (Mld->isExpandingLoad())
41466     return SDValue();
41467 
41468   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
41469     if (SDValue ScalarLoad = reduceMaskedLoadToScalarLoad(Mld, DAG, DCI))
41470       return ScalarLoad;
41471     // TODO: Do some AVX512 subsets benefit from this transform?
41472     if (!Subtarget.hasAVX512())
41473       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
41474         return Blend;
41475   }
41476 
41477   return SDValue();
41478 }
41479 
41480 /// If exactly one element of the mask is set for a non-truncating masked store,
41481 /// it is a vector extract and scalar store.
41482 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
41483 /// mask have already been optimized in IR, so we don't bother with those here.
reduceMaskedStoreToScalarStore(MaskedStoreSDNode * MS,SelectionDAG & DAG)41484 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
41485                                               SelectionDAG &DAG) {
41486   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
41487   // However, some target hooks may need to be added to know when the transform
41488   // is profitable. Endianness would also have to be considered.
41489 
41490   SDValue Addr, VecIndex;
41491   unsigned Alignment;
41492   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment))
41493     return SDValue();
41494 
41495   // Extract the one scalar element that is actually being stored.
41496   SDLoc DL(MS);
41497   EVT VT = MS->getValue().getValueType();
41498   EVT EltVT = VT.getVectorElementType();
41499   SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
41500                                 MS->getValue(), VecIndex);
41501 
41502   // Store that element at the appropriate offset from the base pointer.
41503   return DAG.getStore(MS->getChain(), DL, Extract, Addr, MS->getPointerInfo(),
41504                       Alignment, MS->getMemOperand()->getFlags());
41505 }
41506 
combineMaskedStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41507 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
41508                                   TargetLowering::DAGCombinerInfo &DCI,
41509                                   const X86Subtarget &Subtarget) {
41510   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
41511   if (Mst->isCompressingStore())
41512     return SDValue();
41513 
41514   EVT VT = Mst->getValue().getValueType();
41515   SDLoc dl(Mst);
41516   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41517 
41518   if (Mst->isTruncatingStore())
41519     return SDValue();
41520 
41521   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG))
41522     return ScalarStore;
41523 
41524   // If the mask value has been legalized to a non-boolean vector, try to
41525   // simplify ops leading up to it. We only demand the MSB of each lane.
41526   SDValue Mask = Mst->getMask();
41527   if (Mask.getScalarValueSizeInBits() != 1) {
41528     APInt DemandedMask(APInt::getSignMask(VT.getScalarSizeInBits()));
41529     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
41530       return SDValue(N, 0);
41531   }
41532 
41533   SDValue Value = Mst->getValue();
41534   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
41535       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
41536                             Mst->getMemoryVT())) {
41537     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
41538                               Mst->getBasePtr(), Mst->getOffset(), Mask,
41539                               Mst->getMemoryVT(), Mst->getMemOperand(),
41540                               Mst->getAddressingMode(), true);
41541   }
41542 
41543   return SDValue();
41544 }
41545 
combineStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41546 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
41547                             TargetLowering::DAGCombinerInfo &DCI,
41548                             const X86Subtarget &Subtarget) {
41549   StoreSDNode *St = cast<StoreSDNode>(N);
41550   EVT StVT = St->getMemoryVT();
41551   SDLoc dl(St);
41552   unsigned Alignment = St->getAlignment();
41553   SDValue StoredVal = St->getValue();
41554   EVT VT = StoredVal.getValueType();
41555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41556 
41557   // Convert a store of vXi1 into a store of iX and a bitcast.
41558   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
41559       VT.getVectorElementType() == MVT::i1) {
41560 
41561     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
41562     StoredVal = DAG.getBitcast(NewVT, StoredVal);
41563 
41564     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
41565                         St->getPointerInfo(), St->getAlignment(),
41566                         St->getMemOperand()->getFlags());
41567   }
41568 
41569   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
41570   // This will avoid a copy to k-register.
41571   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
41572       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
41573       StoredVal.getOperand(0).getValueType() == MVT::i8) {
41574     return DAG.getStore(St->getChain(), dl, StoredVal.getOperand(0),
41575                         St->getBasePtr(), St->getPointerInfo(),
41576                         St->getAlignment(), St->getMemOperand()->getFlags());
41577   }
41578 
41579   // Widen v2i1/v4i1 stores to v8i1.
41580   if ((VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
41581       Subtarget.hasAVX512()) {
41582     unsigned NumConcats = 8 / VT.getVectorNumElements();
41583     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(VT));
41584     Ops[0] = StoredVal;
41585     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
41586     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
41587                         St->getPointerInfo(), St->getAlignment(),
41588                         St->getMemOperand()->getFlags());
41589   }
41590 
41591   // Turn vXi1 stores of constants into a scalar store.
41592   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
41593        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
41594       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
41595     // If its a v64i1 store without 64-bit support, we need two stores.
41596     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
41597       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
41598                                       StoredVal->ops().slice(0, 32));
41599       Lo = combinevXi1ConstantToInteger(Lo, DAG);
41600       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
41601                                       StoredVal->ops().slice(32, 32));
41602       Hi = combinevXi1ConstantToInteger(Hi, DAG);
41603 
41604       SDValue Ptr0 = St->getBasePtr();
41605       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 4, dl);
41606 
41607       SDValue Ch0 =
41608           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
41609                        Alignment, St->getMemOperand()->getFlags());
41610       SDValue Ch1 =
41611           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
41612                        St->getPointerInfo().getWithOffset(4),
41613                        MinAlign(Alignment, 4U),
41614                        St->getMemOperand()->getFlags());
41615       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
41616     }
41617 
41618     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
41619     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
41620                         St->getPointerInfo(), St->getAlignment(),
41621                         St->getMemOperand()->getFlags());
41622   }
41623 
41624   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
41625   // Sandy Bridge, perform two 16-byte stores.
41626   bool Fast;
41627   if (VT.is256BitVector() && StVT == VT &&
41628       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
41629                              *St->getMemOperand(), &Fast) &&
41630       !Fast) {
41631     unsigned NumElems = VT.getVectorNumElements();
41632     if (NumElems < 2)
41633       return SDValue();
41634 
41635     return splitVectorStore(St, DAG);
41636   }
41637 
41638   // Split under-aligned vector non-temporal stores.
41639   if (St->isNonTemporal() && StVT == VT && Alignment < VT.getStoreSize()) {
41640     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
41641     // vectors or the legalizer can scalarize it to use MOVNTI.
41642     if (VT.is256BitVector() || VT.is512BitVector()) {
41643       unsigned NumElems = VT.getVectorNumElements();
41644       if (NumElems < 2)
41645         return SDValue();
41646       return splitVectorStore(St, DAG);
41647     }
41648 
41649     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
41650     // to use MOVNTI.
41651     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
41652       MVT NTVT = Subtarget.hasSSE4A()
41653                      ? MVT::v2f64
41654                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
41655       return scalarizeVectorStore(St, NTVT, DAG);
41656     }
41657   }
41658 
41659   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
41660   // supported, but avx512f is by extending to v16i32 and truncating.
41661   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
41662       St->getValue().getOpcode() == ISD::TRUNCATE &&
41663       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
41664       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
41665       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
41666     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32, St->getValue());
41667     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
41668                              MVT::v16i8, St->getMemOperand());
41669   }
41670 
41671   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
41672   if (!St->isTruncatingStore() && StoredVal.hasOneUse() &&
41673       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
41674        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
41675       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
41676     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
41677     return EmitTruncSStore(IsSigned, St->getChain(),
41678                            dl, StoredVal.getOperand(0), St->getBasePtr(),
41679                            VT, St->getMemOperand(), DAG);
41680   }
41681 
41682   // Optimize trunc store (of multiple scalars) to shuffle and store.
41683   // First, pack all of the elements in one place. Next, store to memory
41684   // in fewer chunks.
41685   if (St->isTruncatingStore() && VT.isVector()) {
41686     // Check if we can detect an AVG pattern from the truncation. If yes,
41687     // replace the trunc store by a normal store with the result of X86ISD::AVG
41688     // instruction.
41689     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
41690       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
41691                                          Subtarget, dl))
41692         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
41693                             St->getPointerInfo(), St->getAlignment(),
41694                             St->getMemOperand()->getFlags());
41695 
41696     if (TLI.isTruncStoreLegal(VT, StVT)) {
41697       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
41698         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
41699                                dl, Val, St->getBasePtr(),
41700                                St->getMemoryVT(), St->getMemOperand(), DAG);
41701       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
41702                                           DAG, dl))
41703         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
41704                                dl, Val, St->getBasePtr(),
41705                                St->getMemoryVT(), St->getMemOperand(), DAG);
41706     }
41707 
41708     return SDValue();
41709   }
41710 
41711   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
41712   // the FP state in cases where an emms may be missing.
41713   // A preferable solution to the general problem is to figure out the right
41714   // places to insert EMMS.  This qualifies as a quick hack.
41715 
41716   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
41717   if (VT.getSizeInBits() != 64)
41718     return SDValue();
41719 
41720   const Function &F = DAG.getMachineFunction().getFunction();
41721   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
41722   bool F64IsLegal =
41723       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
41724   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
41725       isa<LoadSDNode>(St->getValue()) &&
41726       cast<LoadSDNode>(St->getValue())->isSimple() &&
41727       St->getChain().hasOneUse() && St->isSimple()) {
41728     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
41729 
41730     if (!ISD::isNormalLoad(Ld))
41731       return SDValue();
41732 
41733     // Avoid the transformation if there are multiple uses of the loaded value.
41734     if (!Ld->hasNUsesOfValue(1, 0))
41735       return SDValue();
41736 
41737     SDLoc LdDL(Ld);
41738     SDLoc StDL(N);
41739     // Lower to a single movq load/store pair.
41740     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
41741                                 Ld->getBasePtr(), Ld->getMemOperand());
41742 
41743     // Make sure new load is placed in same chain order.
41744     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
41745     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
41746                         St->getMemOperand());
41747   }
41748 
41749   // This is similar to the above case, but here we handle a scalar 64-bit
41750   // integer store that is extracted from a vector on a 32-bit target.
41751   // If we have SSE2, then we can treat it like a floating-point double
41752   // to get past legalization. The execution dependencies fixup pass will
41753   // choose the optimal machine instruction for the store if this really is
41754   // an integer or v2f32 rather than an f64.
41755   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
41756       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
41757     SDValue OldExtract = St->getOperand(1);
41758     SDValue ExtOp0 = OldExtract.getOperand(0);
41759     unsigned VecSize = ExtOp0.getValueSizeInBits();
41760     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
41761     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
41762     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
41763                                      BitCast, OldExtract.getOperand(1));
41764     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
41765                         St->getPointerInfo(), St->getAlignment(),
41766                         St->getMemOperand()->getFlags());
41767   }
41768 
41769   return SDValue();
41770 }
41771 
41772 /// Return 'true' if this vector operation is "horizontal"
41773 /// and return the operands for the horizontal operation in LHS and RHS.  A
41774 /// horizontal operation performs the binary operation on successive elements
41775 /// of its first operand, then on successive elements of its second operand,
41776 /// returning the resulting values in a vector.  For example, if
41777 ///   A = < float a0, float a1, float a2, float a3 >
41778 /// and
41779 ///   B = < float b0, float b1, float b2, float b3 >
41780 /// then the result of doing a horizontal operation on A and B is
41781 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
41782 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
41783 /// A horizontal-op B, for some already available A and B, and if so then LHS is
41784 /// set to A, RHS to B, and the routine returns 'true'.
isHorizontalBinOp(SDValue & LHS,SDValue & RHS,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool IsCommutative)41785 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, SelectionDAG &DAG,
41786                               const X86Subtarget &Subtarget,
41787                               bool IsCommutative) {
41788   // If either operand is undef, bail out. The binop should be simplified.
41789   if (LHS.isUndef() || RHS.isUndef())
41790     return false;
41791 
41792   // Look for the following pattern:
41793   //   A = < float a0, float a1, float a2, float a3 >
41794   //   B = < float b0, float b1, float b2, float b3 >
41795   // and
41796   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
41797   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
41798   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
41799   // which is A horizontal-op B.
41800 
41801   MVT VT = LHS.getSimpleValueType();
41802   assert((VT.is128BitVector() || VT.is256BitVector()) &&
41803          "Unsupported vector type for horizontal add/sub");
41804   unsigned NumElts = VT.getVectorNumElements();
41805 
41806   // TODO - can we make a general helper method that does all of this for us?
41807   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
41808                         SmallVectorImpl<int> &ShuffleMask) {
41809     if (Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
41810       if (!Op.getOperand(0).isUndef())
41811         N0 = Op.getOperand(0);
41812       if (!Op.getOperand(1).isUndef())
41813         N1 = Op.getOperand(1);
41814       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
41815       ShuffleMask.append(Mask.begin(), Mask.end());
41816       return;
41817     }
41818     bool UseSubVector = false;
41819     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41820         Op.getOperand(0).getValueType().is256BitVector() &&
41821         llvm::isNullConstant(Op.getOperand(1))) {
41822       Op = Op.getOperand(0);
41823       UseSubVector = true;
41824     }
41825     bool IsUnary;
41826     SmallVector<SDValue, 2> SrcOps;
41827     SmallVector<int, 16> SrcShuffleMask;
41828     SDValue BC = peekThroughBitcasts(Op);
41829     if (isTargetShuffle(BC.getOpcode()) &&
41830         getTargetShuffleMask(BC.getNode(), BC.getSimpleValueType(), false,
41831                              SrcOps, SrcShuffleMask, IsUnary)) {
41832       if (!UseSubVector && SrcShuffleMask.size() == NumElts &&
41833           SrcOps.size() <= 2) {
41834         N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
41835         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
41836         ShuffleMask.append(SrcShuffleMask.begin(), SrcShuffleMask.end());
41837       }
41838       if (UseSubVector && (SrcShuffleMask.size() == (NumElts * 2)) &&
41839           SrcOps.size() == 1) {
41840         N0 = extract128BitVector(SrcOps[0], 0, DAG, SDLoc(Op));
41841         N1 = extract128BitVector(SrcOps[0], NumElts, DAG, SDLoc(Op));
41842         ArrayRef<int> Mask = ArrayRef<int>(SrcShuffleMask).slice(0, NumElts);
41843         ShuffleMask.append(Mask.begin(), Mask.end());
41844       }
41845     }
41846   };
41847 
41848   // View LHS in the form
41849   //   LHS = VECTOR_SHUFFLE A, B, LMask
41850   // If LHS is not a shuffle, then pretend it is the identity shuffle:
41851   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
41852   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
41853   SDValue A, B;
41854   SmallVector<int, 16> LMask;
41855   GetShuffle(LHS, A, B, LMask);
41856 
41857   // Likewise, view RHS in the form
41858   //   RHS = VECTOR_SHUFFLE C, D, RMask
41859   SDValue C, D;
41860   SmallVector<int, 16> RMask;
41861   GetShuffle(RHS, C, D, RMask);
41862 
41863   // At least one of the operands should be a vector shuffle.
41864   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
41865   if (NumShuffles == 0)
41866     return false;
41867 
41868   if (LMask.empty()) {
41869     A = LHS;
41870     for (unsigned i = 0; i != NumElts; ++i)
41871       LMask.push_back(i);
41872   }
41873 
41874   if (RMask.empty()) {
41875     C = RHS;
41876     for (unsigned i = 0; i != NumElts; ++i)
41877       RMask.push_back(i);
41878   }
41879 
41880   // If A and B occur in reverse order in RHS, then canonicalize by commuting
41881   // RHS operands and shuffle mask.
41882   if (A != C) {
41883     std::swap(C, D);
41884     ShuffleVectorSDNode::commuteMask(RMask);
41885   }
41886   // Check that the shuffles are both shuffling the same vectors.
41887   if (!(A == C && B == D))
41888     return false;
41889 
41890   // LHS and RHS are now:
41891   //   LHS = shuffle A, B, LMask
41892   //   RHS = shuffle A, B, RMask
41893   // Check that the masks correspond to performing a horizontal operation.
41894   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
41895   // so we just repeat the inner loop if this is a 256-bit op.
41896   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
41897   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
41898   assert((NumEltsPer128BitChunk % 2 == 0) &&
41899          "Vector type should have an even number of elements in each lane");
41900   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
41901     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
41902       // Ignore undefined components.
41903       int LIdx = LMask[i + j], RIdx = RMask[i + j];
41904       if (LIdx < 0 || RIdx < 0 ||
41905           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
41906           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
41907         continue;
41908 
41909       // The  low half of the 128-bit result must choose from A.
41910       // The high half of the 128-bit result must choose from B,
41911       // unless B is undef. In that case, we are always choosing from A.
41912       unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
41913       unsigned Src = B.getNode() ? i >= NumEltsPer64BitChunk : 0;
41914 
41915       // Check that successive elements are being operated on. If not, this is
41916       // not a horizontal operation.
41917       int Index = 2 * (i % NumEltsPer64BitChunk) + NumElts * Src + j;
41918       if (!(LIdx == Index && RIdx == Index + 1) &&
41919           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
41920         return false;
41921     }
41922   }
41923 
41924   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
41925   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
41926 
41927   if (!shouldUseHorizontalOp(LHS == RHS && NumShuffles < 2, DAG, Subtarget))
41928     return false;
41929 
41930   LHS = DAG.getBitcast(VT, LHS);
41931   RHS = DAG.getBitcast(VT, RHS);
41932   return true;
41933 }
41934 
41935 /// Do target-specific dag combines on floating-point adds/subs.
combineFaddFsub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41936 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
41937                                const X86Subtarget &Subtarget) {
41938   EVT VT = N->getValueType(0);
41939   SDValue LHS = N->getOperand(0);
41940   SDValue RHS = N->getOperand(1);
41941   bool IsFadd = N->getOpcode() == ISD::FADD;
41942   auto HorizOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
41943   assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode");
41944 
41945   // Try to synthesize horizontal add/sub from adds/subs of shuffles.
41946   if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
41947        (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
41948       isHorizontalBinOp(LHS, RHS, DAG, Subtarget, IsFadd))
41949     return DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
41950 
41951   return SDValue();
41952 }
41953 
41954 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
41955 /// the codegen.
41956 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
41957 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
41958 ///       anything that is guaranteed to be transformed by DAGCombiner.
combineTruncatedArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)41959 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
41960                                           const X86Subtarget &Subtarget,
41961                                           const SDLoc &DL) {
41962   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
41963   SDValue Src = N->getOperand(0);
41964   unsigned SrcOpcode = Src.getOpcode();
41965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41966 
41967   EVT VT = N->getValueType(0);
41968   EVT SrcVT = Src.getValueType();
41969 
41970   auto IsFreeTruncation = [VT](SDValue Op) {
41971     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
41972 
41973     // See if this has been extended from a smaller/equal size to
41974     // the truncation size, allowing a truncation to combine with the extend.
41975     unsigned Opcode = Op.getOpcode();
41976     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
41977          Opcode == ISD::ZERO_EXTEND) &&
41978         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
41979       return true;
41980 
41981     // See if this is a single use constant which can be constant folded.
41982     // NOTE: We don't peek throught bitcasts here because there is currently
41983     // no support for constant folding truncate+bitcast+vector_of_constants. So
41984     // we'll just send up with a truncate on both operands which will
41985     // get turned back into (truncate (binop)) causing an infinite loop.
41986     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
41987   };
41988 
41989   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
41990     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
41991     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
41992     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
41993   };
41994 
41995   // Don't combine if the operation has other uses.
41996   if (!Src.hasOneUse())
41997     return SDValue();
41998 
41999   // Only support vector truncation for now.
42000   // TODO: i64 scalar math would benefit as well.
42001   if (!VT.isVector())
42002     return SDValue();
42003 
42004   // In most cases its only worth pre-truncating if we're only facing the cost
42005   // of one truncation.
42006   // i.e. if one of the inputs will constant fold or the input is repeated.
42007   switch (SrcOpcode) {
42008   case ISD::AND:
42009   case ISD::XOR:
42010   case ISD::OR: {
42011     SDValue Op0 = Src.getOperand(0);
42012     SDValue Op1 = Src.getOperand(1);
42013     if (TLI.isOperationLegalOrPromote(SrcOpcode, VT) &&
42014         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
42015       return TruncateArithmetic(Op0, Op1);
42016     break;
42017   }
42018 
42019   case ISD::MUL:
42020     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
42021     // better to truncate if we have the chance.
42022     if (SrcVT.getScalarType() == MVT::i64 &&
42023         TLI.isOperationLegal(SrcOpcode, VT) &&
42024         !TLI.isOperationLegal(SrcOpcode, SrcVT))
42025       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
42026     LLVM_FALLTHROUGH;
42027   case ISD::ADD: {
42028     SDValue Op0 = Src.getOperand(0);
42029     SDValue Op1 = Src.getOperand(1);
42030     if (TLI.isOperationLegal(SrcOpcode, VT) &&
42031         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
42032       return TruncateArithmetic(Op0, Op1);
42033     break;
42034   }
42035   case ISD::SUB: {
42036     // TODO: ISD::SUB We are conservative and require both sides to be freely
42037     // truncatable to avoid interfering with combineSubToSubus.
42038     SDValue Op0 = Src.getOperand(0);
42039     SDValue Op1 = Src.getOperand(1);
42040     if (TLI.isOperationLegal(SrcOpcode, VT) &&
42041         (Op0 == Op1 || (IsFreeTruncation(Op0) && IsFreeTruncation(Op1))))
42042       return TruncateArithmetic(Op0, Op1);
42043     break;
42044   }
42045   }
42046 
42047   return SDValue();
42048 }
42049 
42050 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
42051 /// e.g. trunc <8 x i32> X to <8 x i16> -->
42052 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
42053 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
combineVectorTruncationWithPACKUS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)42054 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
42055                                                  const X86Subtarget &Subtarget,
42056                                                  SelectionDAG &DAG) {
42057   SDValue In = N->getOperand(0);
42058   EVT InVT = In.getValueType();
42059   EVT OutVT = N->getValueType(0);
42060 
42061   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
42062                                     OutVT.getScalarSizeInBits());
42063   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
42064   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
42065 }
42066 
42067 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
combineVectorTruncationWithPACKSS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)42068 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
42069                                                  const X86Subtarget &Subtarget,
42070                                                  SelectionDAG &DAG) {
42071   SDValue In = N->getOperand(0);
42072   EVT InVT = In.getValueType();
42073   EVT OutVT = N->getValueType(0);
42074   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
42075                    DAG.getValueType(OutVT));
42076   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
42077 }
42078 
42079 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
42080 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
42081 /// legalization the truncation will be translated into a BUILD_VECTOR with each
42082 /// element that is extracted from a vector and then truncated, and it is
42083 /// difficult to do this optimization based on them.
combineVectorTruncation(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42084 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
42085                                        const X86Subtarget &Subtarget) {
42086   EVT OutVT = N->getValueType(0);
42087   if (!OutVT.isVector())
42088     return SDValue();
42089 
42090   SDValue In = N->getOperand(0);
42091   if (!In.getValueType().isSimple())
42092     return SDValue();
42093 
42094   EVT InVT = In.getValueType();
42095   unsigned NumElems = OutVT.getVectorNumElements();
42096 
42097   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
42098   // SSE2, and we need to take care of it specially.
42099   // AVX512 provides vpmovdb.
42100   if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
42101     return SDValue();
42102 
42103   EVT OutSVT = OutVT.getVectorElementType();
42104   EVT InSVT = InVT.getVectorElementType();
42105   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
42106         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
42107         NumElems >= 8))
42108     return SDValue();
42109 
42110   // SSSE3's pshufb results in less instructions in the cases below.
42111   if (Subtarget.hasSSSE3() && NumElems == 8 &&
42112       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
42113        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
42114     return SDValue();
42115 
42116   SDLoc DL(N);
42117   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
42118   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
42119   // truncate 2 x v4i32 to v8i16.
42120   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
42121     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
42122   if (InSVT == MVT::i32)
42123     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
42124 
42125   return SDValue();
42126 }
42127 
42128 /// This function transforms vector truncation of 'extended sign-bits' or
42129 /// 'extended zero-bits' values.
42130 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
combineVectorSignBitsTruncation(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)42131 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
42132                                                SelectionDAG &DAG,
42133                                                const X86Subtarget &Subtarget) {
42134   // Requires SSE2.
42135   if (!Subtarget.hasSSE2())
42136     return SDValue();
42137 
42138   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
42139     return SDValue();
42140 
42141   SDValue In = N->getOperand(0);
42142   if (!In.getValueType().isSimple())
42143     return SDValue();
42144 
42145   MVT VT = N->getValueType(0).getSimpleVT();
42146   MVT SVT = VT.getScalarType();
42147 
42148   MVT InVT = In.getValueType().getSimpleVT();
42149   MVT InSVT = InVT.getScalarType();
42150 
42151   // Check we have a truncation suited for PACKSS/PACKUS.
42152   if (!VT.is128BitVector() && !VT.is256BitVector())
42153     return SDValue();
42154   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
42155     return SDValue();
42156   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
42157     return SDValue();
42158 
42159   // AVX512 has fast truncate, but if the input is already going to be split,
42160   // there's no harm in trying pack.
42161   if (Subtarget.hasAVX512() &&
42162       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
42163         InVT.is512BitVector()))
42164     return SDValue();
42165 
42166   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
42167   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
42168 
42169   // Use PACKUS if the input has zero-bits that extend all the way to the
42170   // packed/truncated value. e.g. masks, zext_in_reg, etc.
42171   KnownBits Known = DAG.computeKnownBits(In);
42172   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
42173   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
42174     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
42175 
42176   // Use PACKSS if the input has sign-bits that extend all the way to the
42177   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
42178   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
42179   if (NumSignBits > (InSVT.getSizeInBits() - NumPackedSignBits))
42180     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
42181 
42182   return SDValue();
42183 }
42184 
42185 // Try to form a MULHU or MULHS node by looking for
42186 // (trunc (srl (mul ext, ext), 16))
42187 // TODO: This is X86 specific because we want to be able to handle wide types
42188 // before type legalization. But we can only do it if the vector will be
42189 // legalized via widening/splitting. Type legalization can't handle promotion
42190 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
42191 // combiner.
combinePMULH(SDValue Src,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)42192 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
42193                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
42194   // First instruction should be a right shift of a multiply.
42195   if (Src.getOpcode() != ISD::SRL ||
42196       Src.getOperand(0).getOpcode() != ISD::MUL)
42197     return SDValue();
42198 
42199   if (!Subtarget.hasSSE2())
42200     return SDValue();
42201 
42202   // Only handle vXi16 types that are at least 128-bits unless they will be
42203   // widened.
42204   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
42205     return SDValue();
42206 
42207   // Input type should be vXi32.
42208   EVT InVT = Src.getValueType();
42209   if (InVT.getVectorElementType() != MVT::i32)
42210     return SDValue();
42211 
42212   // Need a shift by 16.
42213   APInt ShiftAmt;
42214   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
42215       ShiftAmt != 16)
42216     return SDValue();
42217 
42218   SDValue LHS = Src.getOperand(0).getOperand(0);
42219   SDValue RHS = Src.getOperand(0).getOperand(1);
42220 
42221   unsigned ExtOpc = LHS.getOpcode();
42222   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
42223       RHS.getOpcode() != ExtOpc)
42224     return SDValue();
42225 
42226   // Peek through the extends.
42227   LHS = LHS.getOperand(0);
42228   RHS = RHS.getOperand(0);
42229 
42230   // Ensure the input types match.
42231   if (LHS.getValueType() != VT || RHS.getValueType() != VT)
42232     return SDValue();
42233 
42234   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
42235   return DAG.getNode(Opc, DL, VT, LHS, RHS);
42236 }
42237 
42238 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
42239 // from one vector with signed bytes from another vector, adds together
42240 // adjacent pairs of 16-bit products, and saturates the result before
42241 // truncating to 16-bits.
42242 //
42243 // Which looks something like this:
42244 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
42245 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
detectPMADDUBSW(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)42246 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
42247                                const X86Subtarget &Subtarget,
42248                                const SDLoc &DL) {
42249   if (!VT.isVector() || !Subtarget.hasSSSE3())
42250     return SDValue();
42251 
42252   unsigned NumElems = VT.getVectorNumElements();
42253   EVT ScalarVT = VT.getVectorElementType();
42254   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
42255     return SDValue();
42256 
42257   SDValue SSatVal = detectSSatPattern(In, VT);
42258   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
42259     return SDValue();
42260 
42261   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
42262   // of multiplies from even/odd elements.
42263   SDValue N0 = SSatVal.getOperand(0);
42264   SDValue N1 = SSatVal.getOperand(1);
42265 
42266   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
42267     return SDValue();
42268 
42269   SDValue N00 = N0.getOperand(0);
42270   SDValue N01 = N0.getOperand(1);
42271   SDValue N10 = N1.getOperand(0);
42272   SDValue N11 = N1.getOperand(1);
42273 
42274   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
42275   // Canonicalize zero_extend to LHS.
42276   if (N01.getOpcode() == ISD::ZERO_EXTEND)
42277     std::swap(N00, N01);
42278   if (N11.getOpcode() == ISD::ZERO_EXTEND)
42279     std::swap(N10, N11);
42280 
42281   // Ensure we have a zero_extend and a sign_extend.
42282   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
42283       N01.getOpcode() != ISD::SIGN_EXTEND ||
42284       N10.getOpcode() != ISD::ZERO_EXTEND ||
42285       N11.getOpcode() != ISD::SIGN_EXTEND)
42286     return SDValue();
42287 
42288   // Peek through the extends.
42289   N00 = N00.getOperand(0);
42290   N01 = N01.getOperand(0);
42291   N10 = N10.getOperand(0);
42292   N11 = N11.getOperand(0);
42293 
42294   // Ensure the extend is from vXi8.
42295   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
42296       N01.getValueType().getVectorElementType() != MVT::i8 ||
42297       N10.getValueType().getVectorElementType() != MVT::i8 ||
42298       N11.getValueType().getVectorElementType() != MVT::i8)
42299     return SDValue();
42300 
42301   // All inputs should be build_vectors.
42302   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
42303       N01.getOpcode() != ISD::BUILD_VECTOR ||
42304       N10.getOpcode() != ISD::BUILD_VECTOR ||
42305       N11.getOpcode() != ISD::BUILD_VECTOR)
42306     return SDValue();
42307 
42308   // N00/N10 are zero extended. N01/N11 are sign extended.
42309 
42310   // For each element, we need to ensure we have an odd element from one vector
42311   // multiplied by the odd element of another vector and the even element from
42312   // one of the same vectors being multiplied by the even element from the
42313   // other vector. So we need to make sure for each element i, this operator
42314   // is being performed:
42315   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
42316   SDValue ZExtIn, SExtIn;
42317   for (unsigned i = 0; i != NumElems; ++i) {
42318     SDValue N00Elt = N00.getOperand(i);
42319     SDValue N01Elt = N01.getOperand(i);
42320     SDValue N10Elt = N10.getOperand(i);
42321     SDValue N11Elt = N11.getOperand(i);
42322     // TODO: Be more tolerant to undefs.
42323     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42324         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42325         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42326         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
42327       return SDValue();
42328     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
42329     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
42330     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
42331     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
42332     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
42333       return SDValue();
42334     unsigned IdxN00 = ConstN00Elt->getZExtValue();
42335     unsigned IdxN01 = ConstN01Elt->getZExtValue();
42336     unsigned IdxN10 = ConstN10Elt->getZExtValue();
42337     unsigned IdxN11 = ConstN11Elt->getZExtValue();
42338     // Add is commutative so indices can be reordered.
42339     if (IdxN00 > IdxN10) {
42340       std::swap(IdxN00, IdxN10);
42341       std::swap(IdxN01, IdxN11);
42342     }
42343     // N0 indices be the even element. N1 indices must be the next odd element.
42344     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
42345         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
42346       return SDValue();
42347     SDValue N00In = N00Elt.getOperand(0);
42348     SDValue N01In = N01Elt.getOperand(0);
42349     SDValue N10In = N10Elt.getOperand(0);
42350     SDValue N11In = N11Elt.getOperand(0);
42351     // First time we find an input capture it.
42352     if (!ZExtIn) {
42353       ZExtIn = N00In;
42354       SExtIn = N01In;
42355     }
42356     if (ZExtIn != N00In || SExtIn != N01In ||
42357         ZExtIn != N10In || SExtIn != N11In)
42358       return SDValue();
42359   }
42360 
42361   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42362                          ArrayRef<SDValue> Ops) {
42363     // Shrink by adding truncate nodes and let DAGCombine fold with the
42364     // sources.
42365     EVT InVT = Ops[0].getValueType();
42366     assert(InVT.getScalarType() == MVT::i8 &&
42367            "Unexpected scalar element type");
42368     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
42369     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
42370                                  InVT.getVectorNumElements() / 2);
42371     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
42372   };
42373   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
42374                           PMADDBuilder);
42375 }
42376 
combineTruncate(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42377 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
42378                                const X86Subtarget &Subtarget) {
42379   EVT VT = N->getValueType(0);
42380   SDValue Src = N->getOperand(0);
42381   SDLoc DL(N);
42382 
42383   // Attempt to pre-truncate inputs to arithmetic ops instead.
42384   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
42385     return V;
42386 
42387   // Try to detect AVG pattern first.
42388   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
42389     return Avg;
42390 
42391   // Try to detect PMADD
42392   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
42393     return PMAdd;
42394 
42395   // Try to combine truncation with signed/unsigned saturation.
42396   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
42397     return Val;
42398 
42399   // Try to combine PMULHUW/PMULHW for vXi16.
42400   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
42401     return V;
42402 
42403   // The bitcast source is a direct mmx result.
42404   // Detect bitcasts between i32 to x86mmx
42405   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
42406     SDValue BCSrc = Src.getOperand(0);
42407     if (BCSrc.getValueType() == MVT::x86mmx)
42408       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
42409   }
42410 
42411   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
42412   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
42413     return V;
42414 
42415   return combineVectorTruncation(N, DAG, Subtarget);
42416 }
42417 
combineVTRUNC(SDNode * N,SelectionDAG & DAG)42418 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG) {
42419   EVT VT = N->getValueType(0);
42420   SDValue In = N->getOperand(0);
42421   SDLoc DL(N);
42422 
42423   if (auto SSatVal = detectSSatPattern(In, VT))
42424     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
42425   if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
42426     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
42427 
42428   return SDValue();
42429 }
42430 
42431 /// Returns the negated value if the node \p N flips sign of FP value.
42432 ///
42433 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
42434 /// or FSUB(0, x)
42435 /// AVX512F does not have FXOR, so FNEG is lowered as
42436 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
42437 /// In this case we go though all bitcasts.
42438 /// This also recognizes splat of a negated value and returns the splat of that
42439 /// value.
isFNEG(SelectionDAG & DAG,SDNode * N,unsigned Depth=0)42440 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
42441   if (N->getOpcode() == ISD::FNEG)
42442     return N->getOperand(0);
42443 
42444   // Don't recurse exponentially.
42445   if (Depth > SelectionDAG::MaxRecursionDepth)
42446     return SDValue();
42447 
42448   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
42449 
42450   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
42451   EVT VT = Op->getValueType(0);
42452 
42453   // Make sure the element size doesn't change.
42454   if (VT.getScalarSizeInBits() != ScalarSize)
42455     return SDValue();
42456 
42457   unsigned Opc = Op.getOpcode();
42458   switch (Opc) {
42459   case ISD::VECTOR_SHUFFLE: {
42460     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
42461     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
42462     if (!Op.getOperand(1).isUndef())
42463       return SDValue();
42464     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
42465       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
42466         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
42467                                     cast<ShuffleVectorSDNode>(Op)->getMask());
42468     break;
42469   }
42470   case ISD::INSERT_VECTOR_ELT: {
42471     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
42472     // -V, INDEX).
42473     SDValue InsVector = Op.getOperand(0);
42474     SDValue InsVal = Op.getOperand(1);
42475     if (!InsVector.isUndef())
42476       return SDValue();
42477     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
42478       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
42479         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
42480                            NegInsVal, Op.getOperand(2));
42481     break;
42482   }
42483   case ISD::FSUB:
42484   case ISD::XOR:
42485   case X86ISD::FXOR: {
42486     SDValue Op1 = Op.getOperand(1);
42487     SDValue Op0 = Op.getOperand(0);
42488 
42489     // For XOR and FXOR, we want to check if constant
42490     // bits of Op1 are sign bit masks. For FSUB, we
42491     // have to check if constant bits of Op0 are sign
42492     // bit masks and hence we swap the operands.
42493     if (Opc == ISD::FSUB)
42494       std::swap(Op0, Op1);
42495 
42496     APInt UndefElts;
42497     SmallVector<APInt, 16> EltBits;
42498     // Extract constant bits and see if they are all
42499     // sign bit masks. Ignore the undef elements.
42500     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
42501                                       /* AllowWholeUndefs */ true,
42502                                       /* AllowPartialUndefs */ false)) {
42503       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
42504         if (!UndefElts[I] && !EltBits[I].isSignMask())
42505           return SDValue();
42506 
42507       return peekThroughBitcasts(Op0);
42508     }
42509   }
42510   }
42511 
42512   return SDValue();
42513 }
42514 
negateFMAOpcode(unsigned Opcode,bool NegMul,bool NegAcc,bool NegRes)42515 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
42516                                 bool NegRes) {
42517   if (NegMul) {
42518     switch (Opcode) {
42519     default: llvm_unreachable("Unexpected opcode");
42520     case ISD::FMA:             Opcode = X86ISD::FNMADD;       break;
42521     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMADD_RND;   break;
42522     case X86ISD::FMSUB:        Opcode = X86ISD::FNMSUB;       break;
42523     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
42524     case X86ISD::FNMADD:       Opcode = ISD::FMA;             break;
42525     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMADD_RND;    break;
42526     case X86ISD::FNMSUB:       Opcode = X86ISD::FMSUB;        break;
42527     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMSUB_RND;    break;
42528     }
42529   }
42530 
42531   if (NegAcc) {
42532     switch (Opcode) {
42533     default: llvm_unreachable("Unexpected opcode");
42534     case ISD::FMA:             Opcode = X86ISD::FMSUB;        break;
42535     case X86ISD::FMADD_RND:    Opcode = X86ISD::FMSUB_RND;    break;
42536     case X86ISD::FMSUB:        Opcode = ISD::FMA;             break;
42537     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FMADD_RND;    break;
42538     case X86ISD::FNMADD:       Opcode = X86ISD::FNMSUB;       break;
42539     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FNMSUB_RND;   break;
42540     case X86ISD::FNMSUB:       Opcode = X86ISD::FNMADD;       break;
42541     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FNMADD_RND;   break;
42542     case X86ISD::FMADDSUB:     Opcode = X86ISD::FMSUBADD;     break;
42543     case X86ISD::FMADDSUB_RND: Opcode = X86ISD::FMSUBADD_RND; break;
42544     case X86ISD::FMSUBADD:     Opcode = X86ISD::FMADDSUB;     break;
42545     case X86ISD::FMSUBADD_RND: Opcode = X86ISD::FMADDSUB_RND; break;
42546     }
42547   }
42548 
42549   if (NegRes) {
42550     switch (Opcode) {
42551     default: llvm_unreachable("Unexpected opcode");
42552     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
42553     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
42554     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
42555     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
42556     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
42557     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
42558     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
42559     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
42560     }
42561   }
42562 
42563   return Opcode;
42564 }
42565 
42566 /// Do target-specific dag combines on floating point negations.
combineFneg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42567 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
42568                            const X86Subtarget &Subtarget) {
42569   EVT OrigVT = N->getValueType(0);
42570   SDValue Arg = isFNEG(DAG, N);
42571   if (!Arg)
42572     return SDValue();
42573 
42574   EVT VT = Arg.getValueType();
42575   EVT SVT = VT.getScalarType();
42576   SDLoc DL(N);
42577 
42578   // Let legalize expand this if it isn't a legal type yet.
42579   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
42580     return SDValue();
42581 
42582   // If we're negating a FMUL node on a target with FMA, then we can avoid the
42583   // use of a constant by performing (-0 - A*B) instead.
42584   // FIXME: Check rounding control flags as well once it becomes available.
42585   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
42586       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
42587     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
42588     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
42589                                   Arg.getOperand(1), Zero);
42590     return DAG.getBitcast(OrigVT, NewNode);
42591   }
42592 
42593   // If we're negating an FMA node, then we can adjust the
42594   // instruction to include the extra negation.
42595   if (Arg.hasOneUse() && Subtarget.hasAnyFMA()) {
42596     switch (Arg.getOpcode()) {
42597     case ISD::FMA:
42598     case X86ISD::FMSUB:
42599     case X86ISD::FNMADD:
42600     case X86ISD::FNMSUB:
42601     case X86ISD::FMADD_RND:
42602     case X86ISD::FMSUB_RND:
42603     case X86ISD::FNMADD_RND:
42604     case X86ISD::FNMSUB_RND: {
42605       // We can't handle scalar intrinsic node here because it would only
42606       // invert one element and not the whole vector. But we could try to handle
42607       // a negation of the lower element only.
42608       unsigned NewOpcode = negateFMAOpcode(Arg.getOpcode(), false, false, true);
42609       return DAG.getBitcast(OrigVT, DAG.getNode(NewOpcode, DL, VT, Arg->ops()));
42610     }
42611     }
42612   }
42613 
42614   return SDValue();
42615 }
42616 
isNegatibleForFree(SDValue Op,SelectionDAG & DAG,bool LegalOperations,bool ForCodeSize,unsigned Depth) const42617 char X86TargetLowering::isNegatibleForFree(SDValue Op, SelectionDAG &DAG,
42618                                            bool LegalOperations,
42619                                            bool ForCodeSize,
42620                                            unsigned Depth) const {
42621   // fneg patterns are removable even if they have multiple uses.
42622   if (isFNEG(DAG, Op.getNode(), Depth))
42623     return 2;
42624 
42625   // Don't recurse exponentially.
42626   if (Depth > SelectionDAG::MaxRecursionDepth)
42627     return 0;
42628 
42629   EVT VT = Op.getValueType();
42630   EVT SVT = VT.getScalarType();
42631   switch (Op.getOpcode()) {
42632   case ISD::FMA:
42633   case X86ISD::FMSUB:
42634   case X86ISD::FNMADD:
42635   case X86ISD::FNMSUB:
42636   case X86ISD::FMADD_RND:
42637   case X86ISD::FMSUB_RND:
42638   case X86ISD::FNMADD_RND:
42639   case X86ISD::FNMSUB_RND: {
42640     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
42641         !(SVT == MVT::f32 || SVT == MVT::f64) || !LegalOperations)
42642       break;
42643 
42644     // This is always negatible for free but we might be able to remove some
42645     // extra operand negations as well.
42646     for (int i = 0; i != 3; ++i) {
42647       char V = isNegatibleForFree(Op.getOperand(i), DAG, LegalOperations,
42648                                   ForCodeSize, Depth + 1);
42649       if (V == 2)
42650         return V;
42651     }
42652     return 1;
42653   }
42654   }
42655 
42656   return TargetLowering::isNegatibleForFree(Op, DAG, LegalOperations,
42657                                             ForCodeSize, Depth);
42658 }
42659 
getNegatedExpression(SDValue Op,SelectionDAG & DAG,bool LegalOperations,bool ForCodeSize,unsigned Depth) const42660 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
42661                                                 bool LegalOperations,
42662                                                 bool ForCodeSize,
42663                                                 unsigned Depth) const {
42664   // fneg patterns are removable even if they have multiple uses.
42665   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth))
42666     return DAG.getBitcast(Op.getValueType(), Arg);
42667 
42668   EVT VT = Op.getValueType();
42669   EVT SVT = VT.getScalarType();
42670   unsigned Opc = Op.getOpcode();
42671   switch (Opc) {
42672   case ISD::FMA:
42673   case X86ISD::FMSUB:
42674   case X86ISD::FNMADD:
42675   case X86ISD::FNMSUB:
42676   case X86ISD::FMADD_RND:
42677   case X86ISD::FMSUB_RND:
42678   case X86ISD::FNMADD_RND:
42679   case X86ISD::FNMSUB_RND: {
42680     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
42681         !(SVT == MVT::f32 || SVT == MVT::f64) || !LegalOperations)
42682       break;
42683 
42684     // This is always negatible for free but we might be able to remove some
42685     // extra operand negations as well.
42686     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
42687     for (int i = 0; i != 3; ++i) {
42688       char V = isNegatibleForFree(Op.getOperand(i), DAG, LegalOperations,
42689                                   ForCodeSize, Depth + 1);
42690       if (V == 2)
42691         NewOps[i] = getNegatedExpression(Op.getOperand(i), DAG, LegalOperations,
42692                                          ForCodeSize, Depth + 1);
42693     }
42694 
42695     bool NegA = !!NewOps[0];
42696     bool NegB = !!NewOps[1];
42697     bool NegC = !!NewOps[2];
42698     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
42699 
42700     // Fill in the non-negated ops with the original values.
42701     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
42702       if (!NewOps[i])
42703         NewOps[i] = Op.getOperand(i);
42704     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
42705   }
42706   }
42707 
42708   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
42709                                               ForCodeSize, Depth);
42710 }
42711 
lowerX86FPLogicOp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42712 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
42713                                  const X86Subtarget &Subtarget) {
42714   MVT VT = N->getSimpleValueType(0);
42715   // If we have integer vector types available, use the integer opcodes.
42716   if (!VT.isVector() || !Subtarget.hasSSE2())
42717     return SDValue();
42718 
42719   SDLoc dl(N);
42720 
42721   unsigned IntBits = VT.getScalarSizeInBits();
42722   MVT IntSVT = MVT::getIntegerVT(IntBits);
42723   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
42724 
42725   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
42726   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
42727   unsigned IntOpcode;
42728   switch (N->getOpcode()) {
42729   default: llvm_unreachable("Unexpected FP logic op");
42730   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
42731   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
42732   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
42733   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
42734   }
42735   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
42736   return DAG.getBitcast(VT, IntOp);
42737 }
42738 
42739 
42740 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
foldXor1SetCC(SDNode * N,SelectionDAG & DAG)42741 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
42742   if (N->getOpcode() != ISD::XOR)
42743     return SDValue();
42744 
42745   SDValue LHS = N->getOperand(0);
42746   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
42747     return SDValue();
42748 
42749   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
42750       X86::CondCode(LHS->getConstantOperandVal(0)));
42751   SDLoc DL(N);
42752   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
42753 }
42754 
combineXor(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42755 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
42756                           TargetLowering::DAGCombinerInfo &DCI,
42757                           const X86Subtarget &Subtarget) {
42758   // If this is SSE1 only convert to FXOR to avoid scalarization.
42759   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() &&
42760       N->getValueType(0) == MVT::v4i32) {
42761     return DAG.getBitcast(
42762         MVT::v4i32, DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
42763                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
42764                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
42765   }
42766 
42767   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
42768     return Cmp;
42769 
42770   if (DCI.isBeforeLegalizeOps())
42771     return SDValue();
42772 
42773   if (SDValue SetCC = foldXor1SetCC(N, DAG))
42774     return SetCC;
42775 
42776   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
42777     return RV;
42778 
42779   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
42780     return FPLogic;
42781 
42782   return combineFneg(N, DAG, Subtarget);
42783 }
42784 
combineBEXTR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42785 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
42786                             TargetLowering::DAGCombinerInfo &DCI,
42787                             const X86Subtarget &Subtarget) {
42788   SDValue Op0 = N->getOperand(0);
42789   SDValue Op1 = N->getOperand(1);
42790   EVT VT = N->getValueType(0);
42791   unsigned NumBits = VT.getSizeInBits();
42792 
42793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42794 
42795   // TODO - Constant Folding.
42796   if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
42797     // Reduce Cst1 to the bottom 16-bits.
42798     // NOTE: SimplifyDemandedBits won't do this for constants.
42799     const APInt &Val1 = Cst1->getAPIntValue();
42800     APInt MaskedVal1 = Val1 & 0xFFFF;
42801     if (MaskedVal1 != Val1)
42802       return DAG.getNode(X86ISD::BEXTR, SDLoc(N), VT, Op0,
42803                          DAG.getConstant(MaskedVal1, SDLoc(N), VT));
42804   }
42805 
42806   // Only bottom 16-bits of the control bits are required.
42807   APInt DemandedMask(APInt::getLowBitsSet(NumBits, 16));
42808   if (TLI.SimplifyDemandedBits(Op1, DemandedMask, DCI))
42809     return SDValue(N, 0);
42810 
42811   return SDValue();
42812 }
42813 
isNullFPScalarOrVectorConst(SDValue V)42814 static bool isNullFPScalarOrVectorConst(SDValue V) {
42815   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
42816 }
42817 
42818 /// If a value is a scalar FP zero or a vector FP zero (potentially including
42819 /// undefined elements), return a zero constant that may be used to fold away
42820 /// that value. In the case of a vector, the returned constant will not contain
42821 /// undefined elements even if the input parameter does. This makes it suitable
42822 /// to be used as a replacement operand with operations (eg, bitwise-and) where
42823 /// an undef should not propagate.
getNullFPConstForNullVal(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)42824 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
42825                                         const X86Subtarget &Subtarget) {
42826   if (!isNullFPScalarOrVectorConst(V))
42827     return SDValue();
42828 
42829   if (V.getValueType().isVector())
42830     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
42831 
42832   return V;
42833 }
42834 
combineFAndFNotToFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42835 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
42836                                       const X86Subtarget &Subtarget) {
42837   SDValue N0 = N->getOperand(0);
42838   SDValue N1 = N->getOperand(1);
42839   EVT VT = N->getValueType(0);
42840   SDLoc DL(N);
42841 
42842   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
42843   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
42844         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
42845         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
42846     return SDValue();
42847 
42848   auto isAllOnesConstantFP = [](SDValue V) {
42849     if (V.getSimpleValueType().isVector())
42850       return ISD::isBuildVectorAllOnes(V.getNode());
42851     auto *C = dyn_cast<ConstantFPSDNode>(V);
42852     return C && C->getConstantFPValue()->isAllOnesValue();
42853   };
42854 
42855   // fand (fxor X, -1), Y --> fandn X, Y
42856   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
42857     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
42858 
42859   // fand X, (fxor Y, -1) --> fandn Y, X
42860   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
42861     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
42862 
42863   return SDValue();
42864 }
42865 
42866 /// Do target-specific dag combines on X86ISD::FAND nodes.
combineFAnd(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42867 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
42868                            const X86Subtarget &Subtarget) {
42869   // FAND(0.0, x) -> 0.0
42870   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
42871     return V;
42872 
42873   // FAND(x, 0.0) -> 0.0
42874   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
42875     return V;
42876 
42877   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
42878     return V;
42879 
42880   return lowerX86FPLogicOp(N, DAG, Subtarget);
42881 }
42882 
42883 /// Do target-specific dag combines on X86ISD::FANDN nodes.
combineFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42884 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
42885                             const X86Subtarget &Subtarget) {
42886   // FANDN(0.0, x) -> x
42887   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
42888     return N->getOperand(1);
42889 
42890   // FANDN(x, 0.0) -> 0.0
42891   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
42892     return V;
42893 
42894   return lowerX86FPLogicOp(N, DAG, Subtarget);
42895 }
42896 
42897 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
combineFOr(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42898 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
42899                           const X86Subtarget &Subtarget) {
42900   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
42901 
42902   // F[X]OR(0.0, x) -> x
42903   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
42904     return N->getOperand(1);
42905 
42906   // F[X]OR(x, 0.0) -> x
42907   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
42908     return N->getOperand(0);
42909 
42910   if (SDValue NewVal = combineFneg(N, DAG, Subtarget))
42911     return NewVal;
42912 
42913   return lowerX86FPLogicOp(N, DAG, Subtarget);
42914 }
42915 
42916 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
combineFMinFMax(SDNode * N,SelectionDAG & DAG)42917 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
42918   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
42919 
42920   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
42921   if (!DAG.getTarget().Options.NoNaNsFPMath ||
42922       !DAG.getTarget().Options.NoSignedZerosFPMath)
42923     return SDValue();
42924 
42925   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
42926   // into FMINC and FMAXC, which are Commutative operations.
42927   unsigned NewOp = 0;
42928   switch (N->getOpcode()) {
42929     default: llvm_unreachable("unknown opcode");
42930     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
42931     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
42932   }
42933 
42934   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
42935                      N->getOperand(0), N->getOperand(1));
42936 }
42937 
combineFMinNumFMaxNum(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42938 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
42939                                      const X86Subtarget &Subtarget) {
42940   if (Subtarget.useSoftFloat())
42941     return SDValue();
42942 
42943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42944 
42945   EVT VT = N->getValueType(0);
42946   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
42947         (Subtarget.hasSSE2() && VT == MVT::f64) ||
42948         (VT.isVector() && TLI.isTypeLegal(VT))))
42949     return SDValue();
42950 
42951   SDValue Op0 = N->getOperand(0);
42952   SDValue Op1 = N->getOperand(1);
42953   SDLoc DL(N);
42954   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
42955 
42956   // If we don't have to respect NaN inputs, this is a direct translation to x86
42957   // min/max instructions.
42958   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
42959     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
42960 
42961   // If one of the operands is known non-NaN use the native min/max instructions
42962   // with the non-NaN input as second operand.
42963   if (DAG.isKnownNeverNaN(Op1))
42964     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
42965   if (DAG.isKnownNeverNaN(Op0))
42966     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
42967 
42968   // If we have to respect NaN inputs, this takes at least 3 instructions.
42969   // Favor a library call when operating on a scalar and minimizing code size.
42970   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
42971     return SDValue();
42972 
42973   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
42974                                          VT);
42975 
42976   // There are 4 possibilities involving NaN inputs, and these are the required
42977   // outputs:
42978   //                   Op1
42979   //               Num     NaN
42980   //            ----------------
42981   //       Num  |  Max  |  Op0 |
42982   // Op0        ----------------
42983   //       NaN  |  Op1  |  NaN |
42984   //            ----------------
42985   //
42986   // The SSE FP max/min instructions were not designed for this case, but rather
42987   // to implement:
42988   //   Min = Op1 < Op0 ? Op1 : Op0
42989   //   Max = Op1 > Op0 ? Op1 : Op0
42990   //
42991   // So they always return Op0 if either input is a NaN. However, we can still
42992   // use those instructions for fmaxnum by selecting away a NaN input.
42993 
42994   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
42995   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
42996   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
42997 
42998   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
42999   // are NaN, the NaN value of Op1 is the result.
43000   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
43001 }
43002 
combineX86INT_TO_FP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43003 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
43004                                    TargetLowering::DAGCombinerInfo &DCI) {
43005   EVT VT = N->getValueType(0);
43006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43007 
43008   APInt KnownUndef, KnownZero;
43009   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
43010   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
43011                                      KnownZero, DCI))
43012     return SDValue(N, 0);
43013 
43014   // Convert a full vector load into vzload when not all bits are needed.
43015   SDValue In = N->getOperand(0);
43016   MVT InVT = In.getSimpleValueType();
43017   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
43018       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
43019     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
43020     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
43021     // Unless the load is volatile or atomic.
43022     if (LN->isSimple()) {
43023       SDLoc dl(N);
43024       unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
43025       MVT MemVT = MVT::getIntegerVT(NumBits);
43026       MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
43027       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
43028       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
43029       SDValue VZLoad =
43030           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, MemVT,
43031                                   LN->getPointerInfo(),
43032                                   LN->getAlignment(),
43033                                   LN->getMemOperand()->getFlags());
43034       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
43035                                     DAG.getBitcast(InVT, VZLoad));
43036       DCI.CombineTo(N, Convert);
43037       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
43038       return SDValue(N, 0);
43039     }
43040   }
43041 
43042   return SDValue();
43043 }
43044 
combineCVTP2I_CVTTP2I(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43045 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
43046                                      TargetLowering::DAGCombinerInfo &DCI) {
43047   // FIXME: Handle strict fp nodes.
43048   EVT VT = N->getValueType(0);
43049 
43050   // Convert a full vector load into vzload when not all bits are needed.
43051   SDValue In = N->getOperand(0);
43052   MVT InVT = In.getSimpleValueType();
43053   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
43054       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
43055     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
43056     LoadSDNode *LN = cast<LoadSDNode>(In);
43057     // Unless the load is volatile or atomic.
43058     if (LN->isSimple()) {
43059       SDLoc dl(N);
43060       unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
43061       MVT MemVT = MVT::getFloatingPointVT(NumBits);
43062       MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
43063       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
43064       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
43065       SDValue VZLoad =
43066           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, MemVT,
43067                                   LN->getPointerInfo(),
43068                                   LN->getAlignment(),
43069                                   LN->getMemOperand()->getFlags());
43070       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
43071                                     DAG.getBitcast(InVT, VZLoad));
43072       DCI.CombineTo(N, Convert);
43073       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
43074       return SDValue(N, 0);
43075     }
43076   }
43077 
43078   return SDValue();
43079 }
43080 
43081 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
combineAndnp(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43082 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
43083                             TargetLowering::DAGCombinerInfo &DCI,
43084                             const X86Subtarget &Subtarget) {
43085   MVT VT = N->getSimpleValueType(0);
43086 
43087   // ANDNP(0, x) -> x
43088   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
43089     return N->getOperand(1);
43090 
43091   // ANDNP(x, 0) -> 0
43092   if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
43093     return DAG.getConstant(0, SDLoc(N), VT);
43094 
43095   // Turn ANDNP back to AND if input is inverted.
43096   if (SDValue Not = IsNOT(N->getOperand(0), DAG))
43097     return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not),
43098                        N->getOperand(1));
43099 
43100   // Attempt to recursively combine a bitmask ANDNP with shuffles.
43101   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
43102     SDValue Op(N, 0);
43103     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43104       return Res;
43105   }
43106 
43107   return SDValue();
43108 }
43109 
combineBT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43110 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
43111                          TargetLowering::DAGCombinerInfo &DCI) {
43112   SDValue N0 = N->getOperand(0);
43113   SDValue N1 = N->getOperand(1);
43114 
43115   // BT ignores high bits in the bit index operand.
43116   unsigned BitWidth = N1.getValueSizeInBits();
43117   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
43118   if (SDValue DemandedN1 = DAG.GetDemandedBits(N1, DemandedMask))
43119     return DAG.getNode(X86ISD::BT, SDLoc(N), MVT::i32, N0, DemandedN1);
43120 
43121   return SDValue();
43122 }
43123 
43124 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
combineSextInRegCmov(SDNode * N,SelectionDAG & DAG)43125 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
43126   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
43127 
43128   EVT DstVT = N->getValueType(0);
43129 
43130   SDValue N0 = N->getOperand(0);
43131   SDValue N1 = N->getOperand(1);
43132   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
43133 
43134   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
43135     return SDValue();
43136 
43137   // Look through single use any_extends / truncs.
43138   SDValue IntermediateBitwidthOp;
43139   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
43140       N0.hasOneUse()) {
43141     IntermediateBitwidthOp = N0;
43142     N0 = N0.getOperand(0);
43143   }
43144 
43145   // See if we have a single use cmov.
43146   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
43147     return SDValue();
43148 
43149   SDValue CMovOp0 = N0.getOperand(0);
43150   SDValue CMovOp1 = N0.getOperand(1);
43151 
43152   // Make sure both operands are constants.
43153   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
43154       !isa<ConstantSDNode>(CMovOp1.getNode()))
43155     return SDValue();
43156 
43157   SDLoc DL(N);
43158 
43159   // If we looked through an any_extend/trunc above, add one to the constants.
43160   if (IntermediateBitwidthOp) {
43161     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
43162     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
43163     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
43164   }
43165 
43166   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
43167   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
43168 
43169   EVT CMovVT = DstVT;
43170   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
43171   if (DstVT == MVT::i16) {
43172     CMovVT = MVT::i32;
43173     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
43174     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
43175   }
43176 
43177   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
43178                              N0.getOperand(2), N0.getOperand(3));
43179 
43180   if (CMovVT != DstVT)
43181     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
43182 
43183   return CMov;
43184 }
43185 
combineSignExtendInReg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)43186 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
43187                                       const X86Subtarget &Subtarget) {
43188   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
43189 
43190   if (SDValue V = combineSextInRegCmov(N, DAG))
43191     return V;
43192 
43193   EVT VT = N->getValueType(0);
43194   SDValue N0 = N->getOperand(0);
43195   SDValue N1 = N->getOperand(1);
43196   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
43197   SDLoc dl(N);
43198 
43199   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
43200   // both SSE and AVX2 since there is no sign-extended shift right
43201   // operation on a vector with 64-bit elements.
43202   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
43203   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
43204   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
43205       N0.getOpcode() == ISD::SIGN_EXTEND)) {
43206     SDValue N00 = N0.getOperand(0);
43207 
43208     // EXTLOAD has a better solution on AVX2,
43209     // it may be replaced with X86ISD::VSEXT node.
43210     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
43211       if (!ISD::isNormalLoad(N00.getNode()))
43212         return SDValue();
43213 
43214     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
43215         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
43216                                   N00, N1);
43217       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
43218     }
43219   }
43220   return SDValue();
43221 }
43222 
43223 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
43224 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
43225 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
43226 /// opportunities to combine math ops, use an LEA, or use a complex addressing
43227 /// mode. This can eliminate extend, add, and shift instructions.
promoteExtBeforeAdd(SDNode * Ext,SelectionDAG & DAG,const X86Subtarget & Subtarget)43228 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
43229                                    const X86Subtarget &Subtarget) {
43230   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
43231       Ext->getOpcode() != ISD::ZERO_EXTEND)
43232     return SDValue();
43233 
43234   // TODO: This should be valid for other integer types.
43235   EVT VT = Ext->getValueType(0);
43236   if (VT != MVT::i64)
43237     return SDValue();
43238 
43239   SDValue Add = Ext->getOperand(0);
43240   if (Add.getOpcode() != ISD::ADD)
43241     return SDValue();
43242 
43243   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
43244   bool NSW = Add->getFlags().hasNoSignedWrap();
43245   bool NUW = Add->getFlags().hasNoUnsignedWrap();
43246 
43247   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
43248   // into the 'zext'
43249   if ((Sext && !NSW) || (!Sext && !NUW))
43250     return SDValue();
43251 
43252   // Having a constant operand to the 'add' ensures that we are not increasing
43253   // the instruction count because the constant is extended for free below.
43254   // A constant operand can also become the displacement field of an LEA.
43255   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
43256   if (!AddOp1)
43257     return SDValue();
43258 
43259   // Don't make the 'add' bigger if there's no hope of combining it with some
43260   // other 'add' or 'shl' instruction.
43261   // TODO: It may be profitable to generate simpler LEA instructions in place
43262   // of single 'add' instructions, but the cost model for selecting an LEA
43263   // currently has a high threshold.
43264   bool HasLEAPotential = false;
43265   for (auto *User : Ext->uses()) {
43266     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
43267       HasLEAPotential = true;
43268       break;
43269     }
43270   }
43271   if (!HasLEAPotential)
43272     return SDValue();
43273 
43274   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
43275   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
43276   SDValue AddOp0 = Add.getOperand(0);
43277   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
43278   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
43279 
43280   // The wider add is guaranteed to not wrap because both operands are
43281   // sign-extended.
43282   SDNodeFlags Flags;
43283   Flags.setNoSignedWrap(NSW);
43284   Flags.setNoUnsignedWrap(NUW);
43285   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
43286 }
43287 
43288 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
43289 // operands and the result of CMOV is not used anywhere else - promote CMOV
43290 // itself instead of promoting its result. This could be beneficial, because:
43291 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
43292 //        (or more) pseudo-CMOVs only when they go one-after-another and
43293 //        getting rid of result extension code after CMOV will help that.
43294 //     2) Promotion of constant CMOV arguments is free, hence the
43295 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
43296 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
43297 //        promotion is also good in terms of code-size.
43298 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
43299 //         promotion).
combineToExtendCMOV(SDNode * Extend,SelectionDAG & DAG)43300 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
43301   SDValue CMovN = Extend->getOperand(0);
43302   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
43303     return SDValue();
43304 
43305   EVT TargetVT = Extend->getValueType(0);
43306   unsigned ExtendOpcode = Extend->getOpcode();
43307   SDLoc DL(Extend);
43308 
43309   EVT VT = CMovN.getValueType();
43310   SDValue CMovOp0 = CMovN.getOperand(0);
43311   SDValue CMovOp1 = CMovN.getOperand(1);
43312 
43313   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
43314       !isa<ConstantSDNode>(CMovOp1.getNode()))
43315     return SDValue();
43316 
43317   // Only extend to i32 or i64.
43318   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
43319     return SDValue();
43320 
43321   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
43322   // are free.
43323   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
43324     return SDValue();
43325 
43326   // If this a zero extend to i64, we should only extend to i32 and use a free
43327   // zero extend to finish.
43328   EVT ExtendVT = TargetVT;
43329   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
43330     ExtendVT = MVT::i32;
43331 
43332   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
43333   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
43334 
43335   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
43336                             CMovN.getOperand(2), CMovN.getOperand(3));
43337 
43338   // Finish extending if needed.
43339   if (ExtendVT != TargetVT)
43340     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
43341 
43342   return Res;
43343 }
43344 
43345 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
43346 // This is more or less the reverse of combineBitcastvxi1.
43347 static SDValue
combineToExtendBoolVectorInReg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43348 combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
43349                                TargetLowering::DAGCombinerInfo &DCI,
43350                                const X86Subtarget &Subtarget) {
43351   unsigned Opcode = N->getOpcode();
43352   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
43353       Opcode != ISD::ANY_EXTEND)
43354     return SDValue();
43355   if (!DCI.isBeforeLegalizeOps())
43356     return SDValue();
43357   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
43358     return SDValue();
43359 
43360   SDValue N0 = N->getOperand(0);
43361   EVT VT = N->getValueType(0);
43362   EVT SVT = VT.getScalarType();
43363   EVT InSVT = N0.getValueType().getScalarType();
43364   unsigned EltSizeInBits = SVT.getSizeInBits();
43365 
43366   // Input type must be extending a bool vector (bit-casted from a scalar
43367   // integer) to legal integer types.
43368   if (!VT.isVector())
43369     return SDValue();
43370   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
43371     return SDValue();
43372   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
43373     return SDValue();
43374 
43375   SDValue N00 = N0.getOperand(0);
43376   EVT SclVT = N0.getOperand(0).getValueType();
43377   if (!SclVT.isScalarInteger())
43378     return SDValue();
43379 
43380   SDLoc DL(N);
43381   SDValue Vec;
43382   SmallVector<int, 32> ShuffleMask;
43383   unsigned NumElts = VT.getVectorNumElements();
43384   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
43385 
43386   // Broadcast the scalar integer to the vector elements.
43387   if (NumElts > EltSizeInBits) {
43388     // If the scalar integer is greater than the vector element size, then we
43389     // must split it down into sub-sections for broadcasting. For example:
43390     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
43391     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
43392     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
43393     unsigned Scale = NumElts / EltSizeInBits;
43394     EVT BroadcastVT =
43395         EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
43396     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
43397     Vec = DAG.getBitcast(VT, Vec);
43398 
43399     for (unsigned i = 0; i != Scale; ++i)
43400       ShuffleMask.append(EltSizeInBits, i);
43401   } else {
43402     // For smaller scalar integers, we can simply any-extend it to the vector
43403     // element size (we don't care about the upper bits) and broadcast it to all
43404     // elements.
43405     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
43406     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
43407     ShuffleMask.append(NumElts, 0);
43408   }
43409   Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
43410 
43411   // Now, mask the relevant bit in each element.
43412   SmallVector<SDValue, 32> Bits;
43413   for (unsigned i = 0; i != NumElts; ++i) {
43414     int BitIdx = (i % EltSizeInBits);
43415     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
43416     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
43417   }
43418   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
43419   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
43420 
43421   // Compare against the bitmask and extend the result.
43422   EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
43423   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
43424   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
43425 
43426   // For SEXT, this is now done, otherwise shift the result down for
43427   // zero-extension.
43428   if (Opcode == ISD::SIGN_EXTEND)
43429     return Vec;
43430   return DAG.getNode(ISD::SRL, DL, VT, Vec,
43431                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
43432 }
43433 
43434 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
43435 // result type.
combineExtSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)43436 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
43437                                const X86Subtarget &Subtarget) {
43438   SDValue N0 = N->getOperand(0);
43439   EVT VT = N->getValueType(0);
43440   SDLoc dl(N);
43441 
43442   // Only do this combine with AVX512 for vector extends.
43443   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
43444     return SDValue();
43445 
43446   // Only combine legal element types.
43447   EVT SVT = VT.getVectorElementType();
43448   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
43449       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
43450     return SDValue();
43451 
43452   // We can only do this if the vector size in 256 bits or less.
43453   unsigned Size = VT.getSizeInBits();
43454   if (Size > 256)
43455     return SDValue();
43456 
43457   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
43458   // that's the only integer compares with we have.
43459   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
43460   if (ISD::isUnsignedIntSetCC(CC))
43461     return SDValue();
43462 
43463   // Only do this combine if the extension will be fully consumed by the setcc.
43464   EVT N00VT = N0.getOperand(0).getValueType();
43465   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
43466   if (Size != MatchingVecType.getSizeInBits())
43467     return SDValue();
43468 
43469   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
43470 
43471   if (N->getOpcode() == ISD::ZERO_EXTEND)
43472     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType().getScalarType());
43473 
43474   return Res;
43475 }
43476 
combineSext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43477 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
43478                            TargetLowering::DAGCombinerInfo &DCI,
43479                            const X86Subtarget &Subtarget) {
43480   SDValue N0 = N->getOperand(0);
43481   EVT VT = N->getValueType(0);
43482   EVT InVT = N0.getValueType();
43483   SDLoc DL(N);
43484 
43485   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
43486     return NewCMov;
43487 
43488   if (!DCI.isBeforeLegalizeOps())
43489     return SDValue();
43490 
43491   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
43492     return V;
43493 
43494   if (InVT == MVT::i1 && N0.getOpcode() == ISD::XOR &&
43495       isAllOnesConstant(N0.getOperand(1)) && N0.hasOneUse()) {
43496     // Invert and sign-extend a boolean is the same as zero-extend and subtract
43497     // 1 because 0 becomes -1 and 1 becomes 0. The subtract is efficiently
43498     // lowered with an LEA or a DEC. This is the same as: select Bool, 0, -1.
43499     // sext (xor Bool, -1) --> sub (zext Bool), 1
43500     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
43501     return DAG.getNode(ISD::SUB, DL, VT, Zext, DAG.getConstant(1, DL, VT));
43502   }
43503 
43504   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
43505     return V;
43506 
43507   if (VT.isVector())
43508     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
43509       return R;
43510 
43511   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
43512     return NewAdd;
43513 
43514   return SDValue();
43515 }
43516 
combineFMA(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43517 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
43518                           TargetLowering::DAGCombinerInfo &DCI,
43519                           const X86Subtarget &Subtarget) {
43520   SDLoc dl(N);
43521   EVT VT = N->getValueType(0);
43522 
43523   // Let legalize expand this if it isn't a legal type yet.
43524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43525   if (!TLI.isTypeLegal(VT))
43526     return SDValue();
43527 
43528   EVT ScalarVT = VT.getScalarType();
43529   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
43530     return SDValue();
43531 
43532   SDValue A = N->getOperand(0);
43533   SDValue B = N->getOperand(1);
43534   SDValue C = N->getOperand(2);
43535 
43536   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
43537     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
43538     bool LegalOperations = !DCI.isBeforeLegalizeOps();
43539     if (TLI.isNegatibleForFree(V, DAG, LegalOperations, CodeSize) == 2) {
43540       V = TLI.getNegatedExpression(V, DAG, LegalOperations, CodeSize);
43541       return true;
43542     }
43543     // Look through extract_vector_elts. If it comes from an FNEG, create a
43544     // new extract from the FNEG input.
43545     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
43546         isNullConstant(V.getOperand(1))) {
43547       SDValue Vec = V.getOperand(0);
43548       if (TLI.isNegatibleForFree(Vec, DAG, LegalOperations, CodeSize) == 2) {
43549         SDValue NegVal =
43550             TLI.getNegatedExpression(Vec, DAG, LegalOperations, CodeSize);
43551         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
43552                         NegVal, V.getOperand(1));
43553         return true;
43554       }
43555     }
43556 
43557     return false;
43558   };
43559 
43560   // Do not convert the passthru input of scalar intrinsics.
43561   // FIXME: We could allow negations of the lower element only.
43562   bool NegA = invertIfNegative(A);
43563   bool NegB = invertIfNegative(B);
43564   bool NegC = invertIfNegative(C);
43565 
43566   if (!NegA && !NegB && !NegC)
43567     return SDValue();
43568 
43569   unsigned NewOpcode =
43570       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
43571 
43572   if (N->getNumOperands() == 4)
43573     return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
43574   return DAG.getNode(NewOpcode, dl, VT, A, B, C);
43575 }
43576 
43577 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
43578 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
combineFMADDSUB(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43579 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
43580                                TargetLowering::DAGCombinerInfo &DCI) {
43581   SDLoc dl(N);
43582   EVT VT = N->getValueType(0);
43583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43584   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
43585   bool LegalOperations = !DCI.isBeforeLegalizeOps();
43586 
43587   SDValue N2 = N->getOperand(2);
43588   if (TLI.isNegatibleForFree(N2, DAG, LegalOperations, CodeSize) != 2)
43589     return SDValue();
43590 
43591   SDValue NegN2 = TLI.getNegatedExpression(N2, DAG, LegalOperations, CodeSize);
43592   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
43593 
43594   if (N->getNumOperands() == 4)
43595     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
43596                        NegN2, N->getOperand(3));
43597   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
43598                      NegN2);
43599 }
43600 
combineZext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43601 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
43602                            TargetLowering::DAGCombinerInfo &DCI,
43603                            const X86Subtarget &Subtarget) {
43604   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
43605   //           (and (i32 x86isd::setcc_carry), 1)
43606   // This eliminates the zext. This transformation is necessary because
43607   // ISD::SETCC is always legalized to i8.
43608   SDLoc dl(N);
43609   SDValue N0 = N->getOperand(0);
43610   EVT VT = N->getValueType(0);
43611 
43612   if (N0.getOpcode() == ISD::AND &&
43613       N0.hasOneUse() &&
43614       N0.getOperand(0).hasOneUse()) {
43615     SDValue N00 = N0.getOperand(0);
43616     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
43617       if (!isOneConstant(N0.getOperand(1)))
43618         return SDValue();
43619       return DAG.getNode(ISD::AND, dl, VT,
43620                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
43621                                      N00.getOperand(0), N00.getOperand(1)),
43622                          DAG.getConstant(1, dl, VT));
43623     }
43624   }
43625 
43626   if (N0.getOpcode() == ISD::TRUNCATE &&
43627       N0.hasOneUse() &&
43628       N0.getOperand(0).hasOneUse()) {
43629     SDValue N00 = N0.getOperand(0);
43630     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
43631       return DAG.getNode(ISD::AND, dl, VT,
43632                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
43633                                      N00.getOperand(0), N00.getOperand(1)),
43634                          DAG.getConstant(1, dl, VT));
43635     }
43636   }
43637 
43638   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
43639     return NewCMov;
43640 
43641   if (DCI.isBeforeLegalizeOps())
43642     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
43643       return V;
43644 
43645   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
43646     return V;
43647 
43648   if (VT.isVector())
43649     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
43650       return R;
43651 
43652   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
43653     return NewAdd;
43654 
43655   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
43656     return R;
43657 
43658   // TODO: Combine with any target/faux shuffle.
43659   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
43660       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
43661     SDValue N00 = N0.getOperand(0);
43662     SDValue N01 = N0.getOperand(1);
43663     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
43664     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
43665     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
43666         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
43667       return concatSubVectors(N00, N01, DAG, dl);
43668     }
43669   }
43670 
43671   return SDValue();
43672 }
43673 
43674 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
43675 /// recognizable memcmp expansion.
isOrXorXorTree(SDValue X,bool Root=true)43676 static bool isOrXorXorTree(SDValue X, bool Root = true) {
43677   if (X.getOpcode() == ISD::OR)
43678     return isOrXorXorTree(X.getOperand(0), false) &&
43679            isOrXorXorTree(X.getOperand(1), false);
43680   if (Root)
43681     return false;
43682   return X.getOpcode() == ISD::XOR;
43683 }
43684 
43685 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
43686 /// expansion.
43687 template<typename F>
emitOrXorXorTree(SDValue X,SDLoc & DL,SelectionDAG & DAG,EVT VecVT,EVT CmpVT,bool HasPT,F SToV)43688 static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
43689                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
43690   SDValue Op0 = X.getOperand(0);
43691   SDValue Op1 = X.getOperand(1);
43692   if (X.getOpcode() == ISD::OR) {
43693     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
43694     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
43695     if (VecVT != CmpVT)
43696       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
43697     if (HasPT)
43698       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
43699     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
43700   } else if (X.getOpcode() == ISD::XOR) {
43701     SDValue A = SToV(Op0);
43702     SDValue B = SToV(Op1);
43703     if (VecVT != CmpVT)
43704       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
43705     if (HasPT)
43706       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
43707     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
43708   }
43709   llvm_unreachable("Impossible");
43710 }
43711 
43712 /// Try to map a 128-bit or larger integer comparison to vector instructions
43713 /// before type legalization splits it up into chunks.
combineVectorSizedSetCCEquality(SDNode * SetCC,SelectionDAG & DAG,const X86Subtarget & Subtarget)43714 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
43715                                                const X86Subtarget &Subtarget) {
43716   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
43717   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
43718 
43719   // We're looking for an oversized integer equality comparison.
43720   SDValue X = SetCC->getOperand(0);
43721   SDValue Y = SetCC->getOperand(1);
43722   EVT OpVT = X.getValueType();
43723   unsigned OpSize = OpVT.getSizeInBits();
43724   if (!OpVT.isScalarInteger() || OpSize < 128)
43725     return SDValue();
43726 
43727   // Ignore a comparison with zero because that gets special treatment in
43728   // EmitTest(). But make an exception for the special case of a pair of
43729   // logically-combined vector-sized operands compared to zero. This pattern may
43730   // be generated by the memcmp expansion pass with oversized integer compares
43731   // (see PR33325).
43732   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
43733   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
43734     return SDValue();
43735 
43736   // Don't perform this combine if constructing the vector will be expensive.
43737   auto IsVectorBitCastCheap = [](SDValue X) {
43738     X = peekThroughBitcasts(X);
43739     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
43740            X.getOpcode() == ISD::LOAD;
43741   };
43742   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
43743       !IsOrXorXorTreeCCZero)
43744     return SDValue();
43745 
43746   EVT VT = SetCC->getValueType(0);
43747   SDLoc DL(SetCC);
43748   bool HasAVX = Subtarget.hasAVX();
43749 
43750   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
43751   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
43752   // Otherwise use PCMPEQ (plus AND) and mask testing.
43753   if ((OpSize == 128 && Subtarget.hasSSE2()) ||
43754       (OpSize == 256 && HasAVX) ||
43755       (OpSize == 512 && Subtarget.useAVX512Regs())) {
43756     bool HasPT = Subtarget.hasSSE41();
43757 
43758     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
43759     // vector registers are essentially free. (Technically, widening registers
43760     // prevents load folding, but the tradeoff is worth it.)
43761     bool PreferKOT = Subtarget.preferMaskRegisters();
43762     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
43763 
43764     EVT VecVT = MVT::v16i8;
43765     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
43766     if (OpSize == 256) {
43767       VecVT = MVT::v32i8;
43768       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
43769     }
43770     EVT CastVT = VecVT;
43771     bool NeedsAVX512FCast = false;
43772     if (OpSize == 512 || NeedZExt) {
43773       if (Subtarget.hasBWI()) {
43774         VecVT = MVT::v64i8;
43775         CmpVT = MVT::v64i1;
43776         if (OpSize == 512)
43777           CastVT = VecVT;
43778       } else {
43779         VecVT = MVT::v16i32;
43780         CmpVT = MVT::v16i1;
43781         CastVT = OpSize == 512 ? VecVT :
43782                  OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
43783         NeedsAVX512FCast = true;
43784       }
43785     }
43786 
43787     auto ScalarToVector = [&](SDValue X) -> SDValue {
43788       bool TmpZext = false;
43789       EVT TmpCastVT = CastVT;
43790       if (X.getOpcode() == ISD::ZERO_EXTEND) {
43791         SDValue OrigX = X.getOperand(0);
43792         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
43793         if (OrigSize < OpSize) {
43794           if (OrigSize == 128) {
43795             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
43796             X = OrigX;
43797             TmpZext = true;
43798           } else if (OrigSize == 256) {
43799             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
43800             X = OrigX;
43801             TmpZext = true;
43802           }
43803         }
43804       }
43805       X = DAG.getBitcast(TmpCastVT, X);
43806       if (!NeedZExt && !TmpZext)
43807         return X;
43808       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43809       MVT VecIdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
43810       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
43811                          DAG.getConstant(0, DL, VecVT), X,
43812                          DAG.getConstant(0, DL, VecIdxVT));
43813     };
43814 
43815     SDValue Cmp;
43816     if (IsOrXorXorTreeCCZero) {
43817       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
43818       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
43819       // Use 2 vector equality compares and 'and' the results before doing a
43820       // MOVMSK.
43821       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
43822     } else {
43823       SDValue VecX = ScalarToVector(X);
43824       SDValue VecY = ScalarToVector(Y);
43825       if (VecVT != CmpVT) {
43826         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
43827       } else if (HasPT) {
43828         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
43829       } else {
43830         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
43831       }
43832     }
43833     // AVX512 should emit a setcc that will lower to kortest.
43834     if (VecVT != CmpVT) {
43835       EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
43836                    CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
43837       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
43838                           DAG.getConstant(0, DL, KRegVT), CC);
43839     }
43840     if (HasPT) {
43841       SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
43842                                      Cmp);
43843       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
43844       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
43845       SDValue SetCC = getSETCC(X86CC, PT, DL, DAG);
43846       return DAG.getNode(ISD::TRUNCATE, DL, VT, SetCC.getValue(0));
43847     }
43848     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
43849     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
43850     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
43851     // setcc i256 X, Y, eq --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, eq
43852     // setcc i256 X, Y, ne --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, ne
43853     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
43854     SDValue FFFFs = DAG.getConstant(OpSize == 128 ? 0xFFFF : 0xFFFFFFFF, DL,
43855                                     MVT::i32);
43856     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
43857   }
43858 
43859   return SDValue();
43860 }
43861 
combineSetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)43862 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
43863                             const X86Subtarget &Subtarget) {
43864   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
43865   const SDValue LHS = N->getOperand(0);
43866   const SDValue RHS = N->getOperand(1);
43867   EVT VT = N->getValueType(0);
43868   EVT OpVT = LHS.getValueType();
43869   SDLoc DL(N);
43870 
43871   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
43872     // 0-x == y --> x+y == 0
43873     // 0-x != y --> x+y != 0
43874     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
43875         LHS.hasOneUse()) {
43876       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, RHS, LHS.getOperand(1));
43877       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
43878     }
43879     // x == 0-y --> x+y == 0
43880     // x != 0-y --> x+y != 0
43881     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
43882         RHS.hasOneUse()) {
43883       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
43884       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
43885     }
43886 
43887     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
43888       return V;
43889   }
43890 
43891   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
43892       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
43893     // Using temporaries to avoid messing up operand ordering for later
43894     // transformations if this doesn't work.
43895     SDValue Op0 = LHS;
43896     SDValue Op1 = RHS;
43897     ISD::CondCode TmpCC = CC;
43898     // Put build_vector on the right.
43899     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
43900       std::swap(Op0, Op1);
43901       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
43902     }
43903 
43904     bool IsSEXT0 =
43905         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
43906         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
43907     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
43908 
43909     if (IsSEXT0 && IsVZero1) {
43910       assert(VT == Op0.getOperand(0).getValueType() &&
43911              "Uexpected operand type");
43912       if (TmpCC == ISD::SETGT)
43913         return DAG.getConstant(0, DL, VT);
43914       if (TmpCC == ISD::SETLE)
43915         return DAG.getConstant(1, DL, VT);
43916       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
43917         return DAG.getNOT(DL, Op0.getOperand(0), VT);
43918 
43919       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
43920              "Unexpected condition code!");
43921       return Op0.getOperand(0);
43922     }
43923   }
43924 
43925   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
43926   // pre-promote its result type since vXi1 vectors don't get promoted
43927   // during type legalization.
43928   // NOTE: The element count check is to ignore operand types that need to
43929   // go through type promotion to a 128-bit vector.
43930   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
43931       VT.getVectorElementType() == MVT::i1 &&
43932       (OpVT.getVectorElementType() == MVT::i8 ||
43933        OpVT.getVectorElementType() == MVT::i16)) {
43934     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
43935     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
43936   }
43937 
43938   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
43939   // to avoid scalarization via legalization because v4i32 is not a legal type.
43940   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
43941       LHS.getValueType() == MVT::v4f32)
43942     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
43943 
43944   return SDValue();
43945 }
43946 
combineMOVMSK(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43947 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
43948                              TargetLowering::DAGCombinerInfo &DCI,
43949                              const X86Subtarget &Subtarget) {
43950   SDValue Src = N->getOperand(0);
43951   MVT SrcVT = Src.getSimpleValueType();
43952   MVT VT = N->getSimpleValueType(0);
43953   unsigned NumBits = VT.getScalarSizeInBits();
43954   unsigned NumElts = SrcVT.getVectorNumElements();
43955 
43956   // Perform constant folding.
43957   if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
43958     assert(VT == MVT::i32 && "Unexpected result type");
43959     APInt Imm(32, 0);
43960     for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
43961       if (!Src.getOperand(Idx).isUndef() &&
43962           Src.getConstantOperandAPInt(Idx).isNegative())
43963         Imm.setBit(Idx);
43964     }
43965     return DAG.getConstant(Imm, SDLoc(N), VT);
43966   }
43967 
43968   // Look through int->fp bitcasts that don't change the element width.
43969   unsigned EltWidth = SrcVT.getScalarSizeInBits();
43970   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
43971       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
43972     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
43973 
43974   // Fold movmsk(not(x)) -> not(movmsk) to improve folding of movmsk results
43975   // with scalar comparisons.
43976   if (SDValue NotSrc = IsNOT(Src, DAG)) {
43977     SDLoc DL(N);
43978     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
43979     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
43980     return DAG.getNode(ISD::XOR, DL, VT,
43981                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
43982                        DAG.getConstant(NotMask, DL, VT));
43983   }
43984 
43985   // Simplify the inputs.
43986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43987   APInt DemandedMask(APInt::getAllOnesValue(NumBits));
43988   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
43989     return SDValue(N, 0);
43990 
43991   return SDValue();
43992 }
43993 
combineX86GatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43994 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
43995                                        TargetLowering::DAGCombinerInfo &DCI) {
43996   // With vector masks we only demand the upper bit of the mask.
43997   SDValue Mask = cast<X86MaskedGatherScatterSDNode>(N)->getMask();
43998   if (Mask.getScalarValueSizeInBits() != 1) {
43999     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44000     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
44001     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
44002       return SDValue(N, 0);
44003   }
44004 
44005   return SDValue();
44006 }
44007 
combineGatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)44008 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
44009                                     TargetLowering::DAGCombinerInfo &DCI) {
44010   SDLoc DL(N);
44011   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
44012   SDValue Chain = GorS->getChain();
44013   SDValue Index = GorS->getIndex();
44014   SDValue Mask = GorS->getMask();
44015   SDValue Base = GorS->getBasePtr();
44016   SDValue Scale = GorS->getScale();
44017 
44018   if (DCI.isBeforeLegalize()) {
44019     unsigned IndexWidth = Index.getScalarValueSizeInBits();
44020 
44021     // Shrink constant indices if they are larger than 32-bits.
44022     // Only do this before legalize types since v2i64 could become v2i32.
44023     // FIXME: We could check that the type is legal if we're after legalize
44024     // types, but then we would need to construct test cases where that happens.
44025     // FIXME: We could support more than just constant vectors, but we need to
44026     // careful with costing. A truncate that can be optimized out would be fine.
44027     // Otherwise we might only want to create a truncate if it avoids a split.
44028     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
44029       if (BV->isConstant() && IndexWidth > 32 &&
44030           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
44031         unsigned NumElts = Index.getValueType().getVectorNumElements();
44032         EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
44033         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
44034         if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
44035           SDValue Ops[] = { Chain, Gather->getPassThru(),
44036                             Mask, Base, Index, Scale } ;
44037           return DAG.getMaskedGather(Gather->getVTList(),
44038                                      Gather->getMemoryVT(), DL, Ops,
44039                                      Gather->getMemOperand(),
44040                                      Gather->getIndexType());
44041         }
44042         auto *Scatter = cast<MaskedScatterSDNode>(GorS);
44043         SDValue Ops[] = { Chain, Scatter->getValue(),
44044                           Mask, Base, Index, Scale };
44045         return DAG.getMaskedScatter(Scatter->getVTList(),
44046                                     Scatter->getMemoryVT(), DL,
44047                                     Ops, Scatter->getMemOperand(),
44048                                     Scatter->getIndexType());
44049       }
44050     }
44051 
44052     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
44053     // there are sufficient sign bits. Only do this before legalize types to
44054     // avoid creating illegal types in truncate.
44055     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
44056          Index.getOpcode() == ISD::ZERO_EXTEND) &&
44057         IndexWidth > 32 &&
44058         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
44059         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
44060       unsigned NumElts = Index.getValueType().getVectorNumElements();
44061       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
44062       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
44063       if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
44064         SDValue Ops[] = { Chain, Gather->getPassThru(),
44065                           Mask, Base, Index, Scale } ;
44066         return DAG.getMaskedGather(Gather->getVTList(),
44067                                    Gather->getMemoryVT(), DL, Ops,
44068                                    Gather->getMemOperand(),
44069                                    Gather->getIndexType());
44070       }
44071       auto *Scatter = cast<MaskedScatterSDNode>(GorS);
44072       SDValue Ops[] = { Chain, Scatter->getValue(),
44073                         Mask, Base, Index, Scale };
44074       return DAG.getMaskedScatter(Scatter->getVTList(),
44075                                   Scatter->getMemoryVT(), DL,
44076                                   Ops, Scatter->getMemOperand(),
44077                                   Scatter->getIndexType());
44078     }
44079   }
44080 
44081   if (DCI.isBeforeLegalizeOps()) {
44082     unsigned IndexWidth = Index.getScalarValueSizeInBits();
44083 
44084     // Make sure the index is either i32 or i64
44085     if (IndexWidth != 32 && IndexWidth != 64) {
44086       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
44087       EVT IndexVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
44088                                    Index.getValueType().getVectorNumElements());
44089       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
44090       if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
44091         SDValue Ops[] = { Chain, Gather->getPassThru(),
44092                           Mask, Base, Index, Scale } ;
44093         return DAG.getMaskedGather(Gather->getVTList(),
44094                                    Gather->getMemoryVT(), DL, Ops,
44095                                    Gather->getMemOperand(),
44096                                    Gather->getIndexType());
44097       }
44098       auto *Scatter = cast<MaskedScatterSDNode>(GorS);
44099       SDValue Ops[] = { Chain, Scatter->getValue(),
44100                         Mask, Base, Index, Scale };
44101       return DAG.getMaskedScatter(Scatter->getVTList(),
44102                                   Scatter->getMemoryVT(), DL,
44103                                   Ops, Scatter->getMemOperand(),
44104                                   Scatter->getIndexType());
44105     }
44106   }
44107 
44108   // With vector masks we only demand the upper bit of the mask.
44109   if (Mask.getScalarValueSizeInBits() != 1) {
44110     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44111     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
44112     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
44113       return SDValue(N, 0);
44114   }
44115 
44116   return SDValue();
44117 }
44118 
44119 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
combineX86SetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44120 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
44121                                const X86Subtarget &Subtarget) {
44122   SDLoc DL(N);
44123   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
44124   SDValue EFLAGS = N->getOperand(1);
44125 
44126   // Try to simplify the EFLAGS and condition code operands.
44127   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
44128     return getSETCC(CC, Flags, DL, DAG);
44129 
44130   return SDValue();
44131 }
44132 
44133 /// Optimize branch condition evaluation.
combineBrCond(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44134 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
44135                              const X86Subtarget &Subtarget) {
44136   SDLoc DL(N);
44137   SDValue EFLAGS = N->getOperand(3);
44138   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
44139 
44140   // Try to simplify the EFLAGS and condition code operands.
44141   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
44142   // RAUW them under us.
44143   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
44144     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
44145     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
44146                        N->getOperand(1), Cond, Flags);
44147   }
44148 
44149   return SDValue();
44150 }
44151 
combineVectorCompareAndMaskUnaryOp(SDNode * N,SelectionDAG & DAG)44152 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
44153                                                   SelectionDAG &DAG) {
44154   // Take advantage of vector comparisons producing 0 or -1 in each lane to
44155   // optimize away operation when it's from a constant.
44156   //
44157   // The general transformation is:
44158   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
44159   //       AND(VECTOR_CMP(x,y), constant2)
44160   //    constant2 = UNARYOP(constant)
44161 
44162   // Early exit if this isn't a vector operation, the operand of the
44163   // unary operation isn't a bitwise AND, or if the sizes of the operations
44164   // aren't the same.
44165   EVT VT = N->getValueType(0);
44166   bool IsStrict = N->isStrictFPOpcode();
44167   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
44168   if (!VT.isVector() || Op0->getOpcode() != ISD::AND ||
44169       Op0->getOperand(0)->getOpcode() != ISD::SETCC ||
44170       VT.getSizeInBits() != Op0.getValueSizeInBits())
44171     return SDValue();
44172 
44173   // Now check that the other operand of the AND is a constant. We could
44174   // make the transformation for non-constant splats as well, but it's unclear
44175   // that would be a benefit as it would not eliminate any operations, just
44176   // perform one more step in scalar code before moving to the vector unit.
44177   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
44178     // Bail out if the vector isn't a constant.
44179     if (!BV->isConstant())
44180       return SDValue();
44181 
44182     // Everything checks out. Build up the new and improved node.
44183     SDLoc DL(N);
44184     EVT IntVT = BV->getValueType(0);
44185     // Create a new constant of the appropriate type for the transformed
44186     // DAG.
44187     SDValue SourceConst;
44188     if (IsStrict)
44189       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
44190                                 {N->getOperand(0), SDValue(BV, 0)});
44191     else
44192       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
44193     // The AND node needs bitcasts to/from an integer vector type around it.
44194     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
44195     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
44196                                  MaskConst);
44197     SDValue Res = DAG.getBitcast(VT, NewAnd);
44198     if (IsStrict)
44199       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
44200     return Res;
44201   }
44202 
44203   return SDValue();
44204 }
44205 
44206 /// If we are converting a value to floating-point, try to replace scalar
44207 /// truncate of an extracted vector element with a bitcast. This tries to keep
44208 /// the sequence on XMM registers rather than moving between vector and GPRs.
combineToFPTruncExtElt(SDNode * N,SelectionDAG & DAG)44209 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
44210   // TODO: This is currently only used by combineSIntToFP, but it is generalized
44211   //       to allow being called by any similar cast opcode.
44212   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
44213   SDValue Trunc = N->getOperand(0);
44214   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
44215     return SDValue();
44216 
44217   SDValue ExtElt = Trunc.getOperand(0);
44218   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44219       !isNullConstant(ExtElt.getOperand(1)))
44220     return SDValue();
44221 
44222   EVT TruncVT = Trunc.getValueType();
44223   EVT SrcVT = ExtElt.getValueType();
44224   unsigned DestWidth = TruncVT.getSizeInBits();
44225   unsigned SrcWidth = SrcVT.getSizeInBits();
44226   if (SrcWidth % DestWidth != 0)
44227     return SDValue();
44228 
44229   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
44230   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
44231   unsigned VecWidth = SrcVecVT.getSizeInBits();
44232   unsigned NumElts = VecWidth / DestWidth;
44233   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
44234   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
44235   SDLoc DL(N);
44236   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
44237                                   BitcastVec, ExtElt.getOperand(1));
44238   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
44239 }
44240 
combineUIntToFP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44241 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
44242                                const X86Subtarget &Subtarget) {
44243   bool IsStrict = N->isStrictFPOpcode();
44244   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
44245   EVT VT = N->getValueType(0);
44246   EVT InVT = Op0.getValueType();
44247 
44248   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
44249   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
44250   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
44251   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
44252     SDLoc dl(N);
44253     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
44254                                  InVT.getVectorNumElements());
44255     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
44256 
44257     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
44258     if (IsStrict)
44259       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
44260                          {N->getOperand(0), P});
44261     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
44262   }
44263 
44264   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
44265   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
44266   // the optimization here.
44267   if (DAG.SignBitIsZero(Op0)) {
44268     if (IsStrict)
44269       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
44270                          {N->getOperand(0), Op0});
44271     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
44272   }
44273 
44274   return SDValue();
44275 }
44276 
combineSIntToFP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44277 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
44278                                TargetLowering::DAGCombinerInfo &DCI,
44279                                const X86Subtarget &Subtarget) {
44280   // First try to optimize away the conversion entirely when it's
44281   // conditionally from a constant. Vectors only.
44282   bool IsStrict = N->isStrictFPOpcode();
44283   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
44284     return Res;
44285 
44286   // Now move on to more general possibilities.
44287   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
44288   EVT VT = N->getValueType(0);
44289   EVT InVT = Op0.getValueType();
44290 
44291   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
44292   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
44293   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
44294   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
44295     SDLoc dl(N);
44296     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
44297                                  InVT.getVectorNumElements());
44298     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
44299     if (IsStrict)
44300       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
44301                          {N->getOperand(0), P});
44302     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
44303   }
44304 
44305   // Without AVX512DQ we only support i64 to float scalar conversion. For both
44306   // vectors and scalars, see if we know that the upper bits are all the sign
44307   // bit, in which case we can truncate the input to i32 and convert from that.
44308   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
44309     unsigned BitWidth = InVT.getScalarSizeInBits();
44310     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
44311     if (NumSignBits >= (BitWidth - 31)) {
44312       EVT TruncVT = MVT::i32;
44313       if (InVT.isVector())
44314         TruncVT = EVT::getVectorVT(*DAG.getContext(), TruncVT,
44315                                    InVT.getVectorNumElements());
44316       SDLoc dl(N);
44317       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
44318         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
44319         if (IsStrict)
44320           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
44321                              {N->getOperand(0), Trunc});
44322         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
44323       }
44324       // If we're after legalize and the type is v2i32 we need to shuffle and
44325       // use CVTSI2P.
44326       assert(InVT == MVT::v2i64 && "Unexpected VT!");
44327       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
44328       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
44329                                           { 0, 2, -1, -1 });
44330       if (IsStrict)
44331         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
44332                            {N->getOperand(0), Shuf});
44333       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
44334     }
44335   }
44336 
44337   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
44338   // a 32-bit target where SSE doesn't support i64->FP operations.
44339   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
44340       Op0.getOpcode() == ISD::LOAD) {
44341     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
44342     EVT LdVT = Ld->getValueType(0);
44343 
44344     // This transformation is not supported if the result type is f16 or f128.
44345     if (VT == MVT::f16 || VT == MVT::f128)
44346       return SDValue();
44347 
44348     // If we have AVX512DQ we can use packed conversion instructions unless
44349     // the VT is f80.
44350     if (Subtarget.hasDQI() && VT != MVT::f80)
44351       return SDValue();
44352 
44353     if (Ld->isSimple() && !VT.isVector() &&
44354         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
44355         !Subtarget.is64Bit() && LdVT == MVT::i64) {
44356       std::pair<SDValue, SDValue> Tmp = Subtarget.getTargetLowering()->BuildFILD(
44357           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
44358       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
44359       return Tmp.first;
44360     }
44361   }
44362 
44363   if (IsStrict)
44364     return SDValue();
44365 
44366   if (SDValue V = combineToFPTruncExtElt(N, DAG))
44367     return V;
44368 
44369   return SDValue();
44370 }
44371 
needCarryOrOverflowFlag(SDValue Flags)44372 static bool needCarryOrOverflowFlag(SDValue Flags) {
44373   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
44374 
44375   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
44376          UI != UE; ++UI) {
44377     SDNode *User = *UI;
44378 
44379     X86::CondCode CC;
44380     switch (User->getOpcode()) {
44381     default:
44382       // Be conservative.
44383       return true;
44384     case X86ISD::SETCC:
44385     case X86ISD::SETCC_CARRY:
44386       CC = (X86::CondCode)User->getConstantOperandVal(0);
44387       break;
44388     case X86ISD::BRCOND:
44389       CC = (X86::CondCode)User->getConstantOperandVal(2);
44390       break;
44391     case X86ISD::CMOV:
44392       CC = (X86::CondCode)User->getConstantOperandVal(2);
44393       break;
44394     }
44395 
44396     switch (CC) {
44397     default: break;
44398     case X86::COND_A: case X86::COND_AE:
44399     case X86::COND_B: case X86::COND_BE:
44400     case X86::COND_O: case X86::COND_NO:
44401     case X86::COND_G: case X86::COND_GE:
44402     case X86::COND_L: case X86::COND_LE:
44403       return true;
44404     }
44405   }
44406 
44407   return false;
44408 }
44409 
onlyZeroFlagUsed(SDValue Flags)44410 static bool onlyZeroFlagUsed(SDValue Flags) {
44411   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
44412 
44413   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
44414          UI != UE; ++UI) {
44415     SDNode *User = *UI;
44416 
44417     unsigned CCOpNo;
44418     switch (User->getOpcode()) {
44419     default:
44420       // Be conservative.
44421       return false;
44422     case X86ISD::SETCC:       CCOpNo = 0; break;
44423     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
44424     case X86ISD::BRCOND:      CCOpNo = 2; break;
44425     case X86ISD::CMOV:        CCOpNo = 2; break;
44426     }
44427 
44428     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
44429     if (CC != X86::COND_E && CC != X86::COND_NE)
44430       return false;
44431   }
44432 
44433   return true;
44434 }
44435 
combineCMP(SDNode * N,SelectionDAG & DAG)44436 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
44437   // Only handle test patterns.
44438   if (!isNullConstant(N->getOperand(1)))
44439     return SDValue();
44440 
44441   // If we have a CMP of a truncated binop, see if we can make a smaller binop
44442   // and use its flags directly.
44443   // TODO: Maybe we should try promoting compares that only use the zero flag
44444   // first if we can prove the upper bits with computeKnownBits?
44445   SDLoc dl(N);
44446   SDValue Op = N->getOperand(0);
44447   EVT VT = Op.getValueType();
44448 
44449   // If we have a constant logical shift that's only used in a comparison
44450   // against zero turn it into an equivalent AND. This allows turning it into
44451   // a TEST instruction later.
44452   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
44453       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
44454       onlyZeroFlagUsed(SDValue(N, 0))) {
44455     unsigned BitWidth = VT.getSizeInBits();
44456     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
44457     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
44458       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
44459       APInt Mask = Op.getOpcode() == ISD::SRL
44460                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
44461                        : APInt::getLowBitsSet(BitWidth, MaskBits);
44462       if (Mask.isSignedIntN(32)) {
44463         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
44464                          DAG.getConstant(Mask, dl, VT));
44465         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
44466                            DAG.getConstant(0, dl, VT));
44467       }
44468     }
44469   }
44470 
44471   // Look for a truncate with a single use.
44472   if (Op.getOpcode() != ISD::TRUNCATE || !Op.hasOneUse())
44473     return SDValue();
44474 
44475   Op = Op.getOperand(0);
44476 
44477   // Arithmetic op can only have one use.
44478   if (!Op.hasOneUse())
44479     return SDValue();
44480 
44481   unsigned NewOpc;
44482   switch (Op.getOpcode()) {
44483   default: return SDValue();
44484   case ISD::AND:
44485     // Skip and with constant. We have special handling for and with immediate
44486     // during isel to generate test instructions.
44487     if (isa<ConstantSDNode>(Op.getOperand(1)))
44488       return SDValue();
44489     NewOpc = X86ISD::AND;
44490     break;
44491   case ISD::OR:  NewOpc = X86ISD::OR;  break;
44492   case ISD::XOR: NewOpc = X86ISD::XOR; break;
44493   case ISD::ADD:
44494     // If the carry or overflow flag is used, we can't truncate.
44495     if (needCarryOrOverflowFlag(SDValue(N, 0)))
44496       return SDValue();
44497     NewOpc = X86ISD::ADD;
44498     break;
44499   case ISD::SUB:
44500     // If the carry or overflow flag is used, we can't truncate.
44501     if (needCarryOrOverflowFlag(SDValue(N, 0)))
44502       return SDValue();
44503     NewOpc = X86ISD::SUB;
44504     break;
44505   }
44506 
44507   // We found an op we can narrow. Truncate its inputs.
44508   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
44509   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
44510 
44511   // Use a X86 specific opcode to avoid DAG combine messing with it.
44512   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
44513   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
44514 
44515   // For AND, keep a CMP so that we can match the test pattern.
44516   if (NewOpc == X86ISD::AND)
44517     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
44518                        DAG.getConstant(0, dl, VT));
44519 
44520   // Return the flags.
44521   return Op.getValue(1);
44522 }
44523 
combineX86AddSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)44524 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
44525                                 TargetLowering::DAGCombinerInfo &DCI) {
44526   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
44527          "Expected X86ISD::ADD or X86ISD::SUB");
44528 
44529   SDLoc DL(N);
44530   SDValue LHS = N->getOperand(0);
44531   SDValue RHS = N->getOperand(1);
44532   MVT VT = LHS.getSimpleValueType();
44533   unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
44534 
44535   // If we don't use the flag result, simplify back to a generic ADD/SUB.
44536   if (!N->hasAnyUseOfValue(1)) {
44537     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
44538     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
44539   }
44540 
44541   // Fold any similar generic ADD/SUB opcodes to reuse this node.
44542   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
44543     SDValue Ops[] = {N0, N1};
44544     SDVTList VTs = DAG.getVTList(N->getValueType(0));
44545     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
44546       SDValue Op(N, 0);
44547       if (Negate)
44548         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
44549       DCI.CombineTo(GenericAddSub, Op);
44550     }
44551   };
44552   MatchGeneric(LHS, RHS, false);
44553   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
44554 
44555   return SDValue();
44556 }
44557 
combineSBB(SDNode * N,SelectionDAG & DAG)44558 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
44559   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
44560     MVT VT = N->getSimpleValueType(0);
44561     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
44562     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
44563                        N->getOperand(0), N->getOperand(1),
44564                        Flags);
44565   }
44566 
44567   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
44568   // iff the flag result is dead.
44569   SDValue Op0 = N->getOperand(0);
44570   SDValue Op1 = N->getOperand(1);
44571   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
44572       !N->hasAnyUseOfValue(1))
44573     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
44574                        Op0.getOperand(1), N->getOperand(2));
44575 
44576   return SDValue();
44577 }
44578 
44579 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
combineADC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)44580 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
44581                           TargetLowering::DAGCombinerInfo &DCI) {
44582   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
44583   // the result is either zero or one (depending on the input carry bit).
44584   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
44585   if (X86::isZeroNode(N->getOperand(0)) &&
44586       X86::isZeroNode(N->getOperand(1)) &&
44587       // We don't have a good way to replace an EFLAGS use, so only do this when
44588       // dead right now.
44589       SDValue(N, 1).use_empty()) {
44590     SDLoc DL(N);
44591     EVT VT = N->getValueType(0);
44592     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
44593     SDValue Res1 =
44594         DAG.getNode(ISD::AND, DL, VT,
44595                     DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
44596                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
44597                                 N->getOperand(2)),
44598                     DAG.getConstant(1, DL, VT));
44599     return DCI.CombineTo(N, Res1, CarryOut);
44600   }
44601 
44602   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
44603     MVT VT = N->getSimpleValueType(0);
44604     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
44605     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
44606                        N->getOperand(0), N->getOperand(1),
44607                        Flags);
44608   }
44609 
44610   return SDValue();
44611 }
44612 
44613 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
44614 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
44615 /// with CMP+{ADC, SBB}.
combineAddOrSubToADCOrSBB(SDNode * N,SelectionDAG & DAG)44616 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
44617   bool IsSub = N->getOpcode() == ISD::SUB;
44618   SDValue X = N->getOperand(0);
44619   SDValue Y = N->getOperand(1);
44620 
44621   // If this is an add, canonicalize a zext operand to the RHS.
44622   // TODO: Incomplete? What if both sides are zexts?
44623   if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
44624       Y.getOpcode() != ISD::ZERO_EXTEND)
44625     std::swap(X, Y);
44626 
44627   // Look through a one-use zext.
44628   bool PeekedThroughZext = false;
44629   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
44630     Y = Y.getOperand(0);
44631     PeekedThroughZext = true;
44632   }
44633 
44634   // If this is an add, canonicalize a setcc operand to the RHS.
44635   // TODO: Incomplete? What if both sides are setcc?
44636   // TODO: Should we allow peeking through a zext of the other operand?
44637   if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
44638       Y.getOpcode() != X86ISD::SETCC)
44639     std::swap(X, Y);
44640 
44641   if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
44642     return SDValue();
44643 
44644   SDLoc DL(N);
44645   EVT VT = N->getValueType(0);
44646   X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
44647 
44648   // If X is -1 or 0, then we have an opportunity to avoid constants required in
44649   // the general case below.
44650   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
44651   if (ConstantX) {
44652     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
44653         (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
44654       // This is a complicated way to get -1 or 0 from the carry flag:
44655       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
44656       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
44657       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
44658                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
44659                          Y.getOperand(1));
44660     }
44661 
44662     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
44663         (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
44664       SDValue EFLAGS = Y->getOperand(1);
44665       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
44666           EFLAGS.getValueType().isInteger() &&
44667           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
44668         // Swap the operands of a SUB, and we have the same pattern as above.
44669         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
44670         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
44671         SDValue NewSub = DAG.getNode(
44672             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
44673             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
44674         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
44675         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
44676                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
44677                            NewEFLAGS);
44678       }
44679     }
44680   }
44681 
44682   if (CC == X86::COND_B) {
44683     // X + SETB Z --> adc X, 0
44684     // X - SETB Z --> sbb X, 0
44685     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
44686                        DAG.getVTList(VT, MVT::i32), X,
44687                        DAG.getConstant(0, DL, VT), Y.getOperand(1));
44688   }
44689 
44690   if (CC == X86::COND_A) {
44691     SDValue EFLAGS = Y->getOperand(1);
44692     // Try to convert COND_A into COND_B in an attempt to facilitate
44693     // materializing "setb reg".
44694     //
44695     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
44696     // cannot take an immediate as its first operand.
44697     //
44698     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
44699         EFLAGS.getValueType().isInteger() &&
44700         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
44701       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
44702                                    EFLAGS.getNode()->getVTList(),
44703                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
44704       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
44705       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
44706                          DAG.getVTList(VT, MVT::i32), X,
44707                          DAG.getConstant(0, DL, VT), NewEFLAGS);
44708     }
44709   }
44710 
44711   if (CC != X86::COND_E && CC != X86::COND_NE)
44712     return SDValue();
44713 
44714   SDValue Cmp = Y.getOperand(1);
44715   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
44716       !X86::isZeroNode(Cmp.getOperand(1)) ||
44717       !Cmp.getOperand(0).getValueType().isInteger())
44718     return SDValue();
44719 
44720   SDValue Z = Cmp.getOperand(0);
44721   EVT ZVT = Z.getValueType();
44722 
44723   // If X is -1 or 0, then we have an opportunity to avoid constants required in
44724   // the general case below.
44725   if (ConstantX) {
44726     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
44727     // fake operands:
44728     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
44729     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
44730     if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
44731         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
44732       SDValue Zero = DAG.getConstant(0, DL, ZVT);
44733       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
44734       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
44735       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
44736                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
44737                          SDValue(Neg.getNode(), 1));
44738     }
44739 
44740     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
44741     // with fake operands:
44742     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
44743     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
44744     if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
44745         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
44746       SDValue One = DAG.getConstant(1, DL, ZVT);
44747       SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
44748       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
44749                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cmp1);
44750     }
44751   }
44752 
44753   // (cmp Z, 1) sets the carry flag if Z is 0.
44754   SDValue One = DAG.getConstant(1, DL, ZVT);
44755   SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
44756 
44757   // Add the flags type for ADC/SBB nodes.
44758   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
44759 
44760   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
44761   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
44762   if (CC == X86::COND_NE)
44763     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
44764                        DAG.getConstant(-1ULL, DL, VT), Cmp1);
44765 
44766   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
44767   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
44768   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
44769                      DAG.getConstant(0, DL, VT), Cmp1);
44770 }
44771 
combineLoopMAddPattern(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44772 static SDValue combineLoopMAddPattern(SDNode *N, SelectionDAG &DAG,
44773                                       const X86Subtarget &Subtarget) {
44774   if (!Subtarget.hasSSE2())
44775     return SDValue();
44776 
44777   EVT VT = N->getValueType(0);
44778 
44779   // If the vector size is less than 128, or greater than the supported RegSize,
44780   // do not use PMADD.
44781   if (!VT.isVector() || VT.getVectorNumElements() < 8)
44782     return SDValue();
44783 
44784   SDValue Op0 = N->getOperand(0);
44785   SDValue Op1 = N->getOperand(1);
44786 
44787   auto UsePMADDWD = [&](SDValue Op) {
44788     ShrinkMode Mode;
44789     return Op.getOpcode() == ISD::MUL &&
44790            canReduceVMulWidth(Op.getNode(), DAG, Mode) &&
44791            Mode != ShrinkMode::MULU16 &&
44792            (!Subtarget.hasSSE41() ||
44793             (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
44794              Op->isOnlyUserOf(Op.getOperand(1).getNode())));
44795   };
44796 
44797   SDValue MulOp, OtherOp;
44798   if (UsePMADDWD(Op0)) {
44799     MulOp = Op0;
44800     OtherOp = Op1;
44801   } else if (UsePMADDWD(Op1)) {
44802     MulOp = Op1;
44803     OtherOp = Op0;
44804   } else
44805    return SDValue();
44806 
44807   SDLoc DL(N);
44808   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
44809                                    VT.getVectorNumElements());
44810   EVT MAddVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
44811                                 VT.getVectorNumElements() / 2);
44812 
44813   // Shrink the operands of mul.
44814   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, MulOp->getOperand(0));
44815   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, MulOp->getOperand(1));
44816 
44817   // Madd vector size is half of the original vector size
44818   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44819                            ArrayRef<SDValue> Ops) {
44820     MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
44821     return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
44822   };
44823   SDValue Madd = SplitOpsAndApply(DAG, Subtarget, DL, MAddVT, { N0, N1 },
44824                                   PMADDWDBuilder);
44825   // Fill the rest of the output with 0
44826   SDValue Zero = DAG.getConstant(0, DL, Madd.getSimpleValueType());
44827   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Madd, Zero);
44828 
44829   // Preserve the reduction flag on the ADD. We may need to revisit for the
44830   // other operand.
44831   SDNodeFlags Flags;
44832   Flags.setVectorReduction(true);
44833   return DAG.getNode(ISD::ADD, DL, VT, Concat, OtherOp, Flags);
44834 }
44835 
combineLoopSADPattern(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44836 static SDValue combineLoopSADPattern(SDNode *N, SelectionDAG &DAG,
44837                                      const X86Subtarget &Subtarget) {
44838   if (!Subtarget.hasSSE2())
44839     return SDValue();
44840 
44841   SDLoc DL(N);
44842   EVT VT = N->getValueType(0);
44843 
44844   // TODO: There's nothing special about i32, any integer type above i16 should
44845   // work just as well.
44846   if (!VT.isVector() || !VT.isSimple() ||
44847       !(VT.getVectorElementType() == MVT::i32))
44848     return SDValue();
44849 
44850   unsigned RegSize = 128;
44851   if (Subtarget.useBWIRegs())
44852     RegSize = 512;
44853   else if (Subtarget.hasAVX())
44854     RegSize = 256;
44855 
44856   // We only handle v16i32 for SSE2 / v32i32 for AVX / v64i32 for AVX512.
44857   // TODO: We should be able to handle larger vectors by splitting them before
44858   // feeding them into several SADs, and then reducing over those.
44859   if (VT.getSizeInBits() / 4 > RegSize)
44860     return SDValue();
44861 
44862   // We know N is a reduction add. To match SAD, we need one of the operands to
44863   // be an ABS.
44864   SDValue AbsOp = N->getOperand(0);
44865   SDValue OtherOp = N->getOperand(1);
44866   if (AbsOp.getOpcode() != ISD::ABS)
44867     std::swap(AbsOp, OtherOp);
44868   if (AbsOp.getOpcode() != ISD::ABS)
44869     return SDValue();
44870 
44871   // Check whether we have an abs-diff pattern feeding into the select.
44872   SDValue SadOp0, SadOp1;
44873   if(!detectZextAbsDiff(AbsOp, SadOp0, SadOp1))
44874     return SDValue();
44875 
44876   // SAD pattern detected. Now build a SAD instruction and an addition for
44877   // reduction. Note that the number of elements of the result of SAD is less
44878   // than the number of elements of its input. Therefore, we could only update
44879   // part of elements in the reduction vector.
44880   SDValue Sad = createPSADBW(DAG, SadOp0, SadOp1, DL, Subtarget);
44881 
44882   // The output of PSADBW is a vector of i64.
44883   // We need to turn the vector of i64 into a vector of i32.
44884   // If the reduction vector is at least as wide as the psadbw result, just
44885   // bitcast. If it's narrower which can only occur for v2i32, bits 127:16 of
44886   // the PSADBW will be zero. If we promote/ narrow vectors, truncate the v2i64
44887   // result to v2i32 which will be removed by type legalization. If we/ widen
44888   // narrow vectors then we bitcast to v4i32 and extract v2i32.
44889   MVT ResVT = MVT::getVectorVT(MVT::i32, Sad.getValueSizeInBits() / 32);
44890   Sad = DAG.getNode(ISD::BITCAST, DL, ResVT, Sad);
44891 
44892   if (VT.getSizeInBits() > ResVT.getSizeInBits()) {
44893     // Fill the upper elements with zero to match the add width.
44894     assert(VT.getSizeInBits() % ResVT.getSizeInBits() == 0 && "Unexpected VTs");
44895     unsigned NumConcats = VT.getSizeInBits() / ResVT.getSizeInBits();
44896     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, DL, ResVT));
44897     Ops[0] = Sad;
44898     Sad = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
44899   } else if (VT.getSizeInBits() < ResVT.getSizeInBits()) {
44900     Sad = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Sad,
44901                       DAG.getIntPtrConstant(0, DL));
44902   }
44903 
44904   // Preserve the reduction flag on the ADD. We may need to revisit for the
44905   // other operand.
44906   SDNodeFlags Flags;
44907   Flags.setVectorReduction(true);
44908   return DAG.getNode(ISD::ADD, DL, VT, Sad, OtherOp, Flags);
44909 }
44910 
matchPMADDWD(SelectionDAG & DAG,SDValue Op0,SDValue Op1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)44911 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
44912                             const SDLoc &DL, EVT VT,
44913                             const X86Subtarget &Subtarget) {
44914   // Example of pattern we try to detect:
44915   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
44916   //(add (build_vector (extract_elt t, 0),
44917   //                   (extract_elt t, 2),
44918   //                   (extract_elt t, 4),
44919   //                   (extract_elt t, 6)),
44920   //     (build_vector (extract_elt t, 1),
44921   //                   (extract_elt t, 3),
44922   //                   (extract_elt t, 5),
44923   //                   (extract_elt t, 7)))
44924 
44925   if (!Subtarget.hasSSE2())
44926     return SDValue();
44927 
44928   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
44929       Op1.getOpcode() != ISD::BUILD_VECTOR)
44930     return SDValue();
44931 
44932   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
44933       VT.getVectorNumElements() < 4 ||
44934       !isPowerOf2_32(VT.getVectorNumElements()))
44935     return SDValue();
44936 
44937   // Check if one of Op0,Op1 is of the form:
44938   // (build_vector (extract_elt Mul, 0),
44939   //               (extract_elt Mul, 2),
44940   //               (extract_elt Mul, 4),
44941   //                   ...
44942   // the other is of the form:
44943   // (build_vector (extract_elt Mul, 1),
44944   //               (extract_elt Mul, 3),
44945   //               (extract_elt Mul, 5),
44946   //                   ...
44947   // and identify Mul.
44948   SDValue Mul;
44949   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
44950     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
44951             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
44952     // TODO: Be more tolerant to undefs.
44953     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44954         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44955         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44956         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
44957       return SDValue();
44958     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
44959     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
44960     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
44961     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
44962     if (!Const0L || !Const1L || !Const0H || !Const1H)
44963       return SDValue();
44964     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
44965              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
44966     // Commutativity of mul allows factors of a product to reorder.
44967     if (Idx0L > Idx1L)
44968       std::swap(Idx0L, Idx1L);
44969     if (Idx0H > Idx1H)
44970       std::swap(Idx0H, Idx1H);
44971     // Commutativity of add allows pairs of factors to reorder.
44972     if (Idx0L > Idx0H) {
44973       std::swap(Idx0L, Idx0H);
44974       std::swap(Idx1L, Idx1H);
44975     }
44976     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
44977         Idx1H != 2 * i + 3)
44978       return SDValue();
44979     if (!Mul) {
44980       // First time an extract_elt's source vector is visited. Must be a MUL
44981       // with 2X number of vector elements than the BUILD_VECTOR.
44982       // Both extracts must be from same MUL.
44983       Mul = Op0L->getOperand(0);
44984       if (Mul->getOpcode() != ISD::MUL ||
44985           Mul.getValueType().getVectorNumElements() != 2 * e)
44986         return SDValue();
44987     }
44988     // Check that the extract is from the same MUL previously seen.
44989     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
44990         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
44991       return SDValue();
44992   }
44993 
44994   // Check if the Mul source can be safely shrunk.
44995   ShrinkMode Mode;
44996   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
44997       Mode == ShrinkMode::MULU16)
44998     return SDValue();
44999 
45000   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45001                          ArrayRef<SDValue> Ops) {
45002     // Shrink by adding truncate nodes and let DAGCombine fold with the
45003     // sources.
45004     EVT InVT = Ops[0].getValueType();
45005     assert(InVT.getScalarType() == MVT::i32 &&
45006            "Unexpected scalar element type");
45007     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
45008     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
45009                                  InVT.getVectorNumElements() / 2);
45010     EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
45011                                    InVT.getVectorNumElements());
45012     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
45013                        DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[0]),
45014                        DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[1]));
45015   };
45016   return SplitOpsAndApply(DAG, Subtarget, DL, VT,
45017                           { Mul.getOperand(0), Mul.getOperand(1) },
45018                           PMADDBuilder);
45019 }
45020 
45021 // Attempt to turn this pattern into PMADDWD.
45022 // (mul (add (sext (build_vector)), (sext (build_vector))),
45023 //      (add (sext (build_vector)), (sext (build_vector)))
matchPMADDWD_2(SelectionDAG & DAG,SDValue N0,SDValue N1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)45024 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
45025                               const SDLoc &DL, EVT VT,
45026                               const X86Subtarget &Subtarget) {
45027   if (!Subtarget.hasSSE2())
45028     return SDValue();
45029 
45030   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
45031     return SDValue();
45032 
45033   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
45034       VT.getVectorNumElements() < 4 ||
45035       !isPowerOf2_32(VT.getVectorNumElements()))
45036     return SDValue();
45037 
45038   SDValue N00 = N0.getOperand(0);
45039   SDValue N01 = N0.getOperand(1);
45040   SDValue N10 = N1.getOperand(0);
45041   SDValue N11 = N1.getOperand(1);
45042 
45043   // All inputs need to be sign extends.
45044   // TODO: Support ZERO_EXTEND from known positive?
45045   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
45046       N01.getOpcode() != ISD::SIGN_EXTEND ||
45047       N10.getOpcode() != ISD::SIGN_EXTEND ||
45048       N11.getOpcode() != ISD::SIGN_EXTEND)
45049     return SDValue();
45050 
45051   // Peek through the extends.
45052   N00 = N00.getOperand(0);
45053   N01 = N01.getOperand(0);
45054   N10 = N10.getOperand(0);
45055   N11 = N11.getOperand(0);
45056 
45057   // Must be extending from vXi16.
45058   EVT InVT = N00.getValueType();
45059   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
45060       N10.getValueType() != InVT || N11.getValueType() != InVT)
45061     return SDValue();
45062 
45063   // All inputs should be build_vectors.
45064   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
45065       N01.getOpcode() != ISD::BUILD_VECTOR ||
45066       N10.getOpcode() != ISD::BUILD_VECTOR ||
45067       N11.getOpcode() != ISD::BUILD_VECTOR)
45068     return SDValue();
45069 
45070   // For each element, we need to ensure we have an odd element from one vector
45071   // multiplied by the odd element of another vector and the even element from
45072   // one of the same vectors being multiplied by the even element from the
45073   // other vector. So we need to make sure for each element i, this operator
45074   // is being performed:
45075   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
45076   SDValue In0, In1;
45077   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
45078     SDValue N00Elt = N00.getOperand(i);
45079     SDValue N01Elt = N01.getOperand(i);
45080     SDValue N10Elt = N10.getOperand(i);
45081     SDValue N11Elt = N11.getOperand(i);
45082     // TODO: Be more tolerant to undefs.
45083     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
45084         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
45085         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
45086         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
45087       return SDValue();
45088     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
45089     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
45090     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
45091     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
45092     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
45093       return SDValue();
45094     unsigned IdxN00 = ConstN00Elt->getZExtValue();
45095     unsigned IdxN01 = ConstN01Elt->getZExtValue();
45096     unsigned IdxN10 = ConstN10Elt->getZExtValue();
45097     unsigned IdxN11 = ConstN11Elt->getZExtValue();
45098     // Add is commutative so indices can be reordered.
45099     if (IdxN00 > IdxN10) {
45100       std::swap(IdxN00, IdxN10);
45101       std::swap(IdxN01, IdxN11);
45102     }
45103     // N0 indices be the even element. N1 indices must be the next odd element.
45104     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
45105         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
45106       return SDValue();
45107     SDValue N00In = N00Elt.getOperand(0);
45108     SDValue N01In = N01Elt.getOperand(0);
45109     SDValue N10In = N10Elt.getOperand(0);
45110     SDValue N11In = N11Elt.getOperand(0);
45111     // First time we find an input capture it.
45112     if (!In0) {
45113       In0 = N00In;
45114       In1 = N01In;
45115     }
45116     // Mul is commutative so the input vectors can be in any order.
45117     // Canonicalize to make the compares easier.
45118     if (In0 != N00In)
45119       std::swap(N00In, N01In);
45120     if (In0 != N10In)
45121       std::swap(N10In, N11In);
45122     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
45123       return SDValue();
45124   }
45125 
45126   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45127                          ArrayRef<SDValue> Ops) {
45128     // Shrink by adding truncate nodes and let DAGCombine fold with the
45129     // sources.
45130     EVT OpVT = Ops[0].getValueType();
45131     assert(OpVT.getScalarType() == MVT::i16 &&
45132            "Unexpected scalar element type");
45133     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
45134     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
45135                                  OpVT.getVectorNumElements() / 2);
45136     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
45137   };
45138   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
45139                           PMADDBuilder);
45140 }
45141 
combineAdd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45142 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
45143                           TargetLowering::DAGCombinerInfo &DCI,
45144                           const X86Subtarget &Subtarget) {
45145   const SDNodeFlags Flags = N->getFlags();
45146   if (Flags.hasVectorReduction()) {
45147     if (SDValue Sad = combineLoopSADPattern(N, DAG, Subtarget))
45148       return Sad;
45149     if (SDValue MAdd = combineLoopMAddPattern(N, DAG, Subtarget))
45150       return MAdd;
45151   }
45152   EVT VT = N->getValueType(0);
45153   SDValue Op0 = N->getOperand(0);
45154   SDValue Op1 = N->getOperand(1);
45155 
45156   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
45157     return MAdd;
45158   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
45159     return MAdd;
45160 
45161   // Try to synthesize horizontal adds from adds of shuffles.
45162   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
45163        VT == MVT::v8i32) &&
45164       Subtarget.hasSSSE3() &&
45165       isHorizontalBinOp(Op0, Op1, DAG, Subtarget, true)) {
45166     auto HADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45167                           ArrayRef<SDValue> Ops) {
45168       return DAG.getNode(X86ISD::HADD, DL, Ops[0].getValueType(), Ops);
45169     };
45170     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
45171                             HADDBuilder);
45172   }
45173 
45174   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
45175   // (sub Y, (sext (vXi1 X))).
45176   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
45177   // generic DAG combine without a legal type check, but adding this there
45178   // caused regressions.
45179   if (VT.isVector()) {
45180     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45181     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
45182         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
45183         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
45184       SDLoc DL(N);
45185       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
45186       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
45187     }
45188 
45189     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
45190         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
45191         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
45192       SDLoc DL(N);
45193       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
45194       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
45195     }
45196   }
45197 
45198   return combineAddOrSubToADCOrSBB(N, DAG);
45199 }
45200 
combineSubToSubus(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45201 static SDValue combineSubToSubus(SDNode *N, SelectionDAG &DAG,
45202                                  const X86Subtarget &Subtarget) {
45203   SDValue Op0 = N->getOperand(0);
45204   SDValue Op1 = N->getOperand(1);
45205   EVT VT = N->getValueType(0);
45206 
45207   if (!VT.isVector())
45208     return SDValue();
45209 
45210   // PSUBUS is supported, starting from SSE2, but truncation for v8i32
45211   // is only worth it with SSSE3 (PSHUFB).
45212   EVT EltVT = VT.getVectorElementType();
45213   if (!(Subtarget.hasSSE2() && (EltVT == MVT::i8 || EltVT == MVT::i16)) &&
45214       !(Subtarget.hasSSSE3() && (VT == MVT::v8i32 || VT == MVT::v8i64)) &&
45215       !(Subtarget.useBWIRegs() && (VT == MVT::v16i32)))
45216     return SDValue();
45217 
45218   SDValue SubusLHS, SubusRHS;
45219   // Try to find umax(a,b) - b or a - umin(a,b) patterns
45220   // they may be converted to subus(a,b).
45221   // TODO: Need to add IR canonicalization for this code.
45222   if (Op0.getOpcode() == ISD::UMAX) {
45223     SubusRHS = Op1;
45224     SDValue MaxLHS = Op0.getOperand(0);
45225     SDValue MaxRHS = Op0.getOperand(1);
45226     if (MaxLHS == Op1)
45227       SubusLHS = MaxRHS;
45228     else if (MaxRHS == Op1)
45229       SubusLHS = MaxLHS;
45230     else
45231       return SDValue();
45232   } else if (Op1.getOpcode() == ISD::UMIN) {
45233     SubusLHS = Op0;
45234     SDValue MinLHS = Op1.getOperand(0);
45235     SDValue MinRHS = Op1.getOperand(1);
45236     if (MinLHS == Op0)
45237       SubusRHS = MinRHS;
45238     else if (MinRHS == Op0)
45239       SubusRHS = MinLHS;
45240     else
45241       return SDValue();
45242   } else
45243     return SDValue();
45244 
45245   // PSUBUS doesn't support v8i32/v8i64/v16i32, but it can be enabled with
45246   // special preprocessing in some cases.
45247   if (EltVT == MVT::i8 || EltVT == MVT::i16)
45248     return DAG.getNode(ISD::USUBSAT, SDLoc(N), VT, SubusLHS, SubusRHS);
45249 
45250   assert((VT == MVT::v8i32 || VT == MVT::v16i32 || VT == MVT::v8i64) &&
45251          "Unexpected VT!");
45252 
45253   // Special preprocessing case can be only applied
45254   // if the value was zero extended from 16 bit,
45255   // so we require first 16 bits to be zeros for 32 bit
45256   // values, or first 48 bits for 64 bit values.
45257   KnownBits Known = DAG.computeKnownBits(SubusLHS);
45258   unsigned NumZeros = Known.countMinLeadingZeros();
45259   if ((VT == MVT::v8i64 && NumZeros < 48) || NumZeros < 16)
45260     return SDValue();
45261 
45262   EVT ExtType = SubusLHS.getValueType();
45263   EVT ShrinkedType;
45264   if (VT == MVT::v8i32 || VT == MVT::v8i64)
45265     ShrinkedType = MVT::v8i16;
45266   else
45267     ShrinkedType = NumZeros >= 24 ? MVT::v16i8 : MVT::v16i16;
45268 
45269   // If SubusLHS is zeroextended - truncate SubusRHS to it's
45270   // size SubusRHS = umin(0xFFF.., SubusRHS).
45271   SDValue SaturationConst =
45272       DAG.getConstant(APInt::getLowBitsSet(ExtType.getScalarSizeInBits(),
45273                                            ShrinkedType.getScalarSizeInBits()),
45274                       SDLoc(SubusLHS), ExtType);
45275   SDValue UMin = DAG.getNode(ISD::UMIN, SDLoc(SubusLHS), ExtType, SubusRHS,
45276                              SaturationConst);
45277   SDValue NewSubusLHS =
45278       DAG.getZExtOrTrunc(SubusLHS, SDLoc(SubusLHS), ShrinkedType);
45279   SDValue NewSubusRHS = DAG.getZExtOrTrunc(UMin, SDLoc(SubusRHS), ShrinkedType);
45280   SDValue Psubus = DAG.getNode(ISD::USUBSAT, SDLoc(N), ShrinkedType,
45281                                NewSubusLHS, NewSubusRHS);
45282 
45283   // Zero extend the result, it may be used somewhere as 32 bit,
45284   // if not zext and following trunc will shrink.
45285   return DAG.getZExtOrTrunc(Psubus, SDLoc(N), ExtType);
45286 }
45287 
combineSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45288 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
45289                           TargetLowering::DAGCombinerInfo &DCI,
45290                           const X86Subtarget &Subtarget) {
45291   SDValue Op0 = N->getOperand(0);
45292   SDValue Op1 = N->getOperand(1);
45293 
45294   // X86 can't encode an immediate LHS of a sub. See if we can push the
45295   // negation into a preceding instruction.
45296   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
45297     // If the RHS of the sub is a XOR with one use and a constant, invert the
45298     // immediate. Then add one to the LHS of the sub so we can turn
45299     // X-Y -> X+~Y+1, saving one register.
45300     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
45301         isa<ConstantSDNode>(Op1.getOperand(1))) {
45302       const APInt &XorC = Op1.getConstantOperandAPInt(1);
45303       EVT VT = Op0.getValueType();
45304       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
45305                                    Op1.getOperand(0),
45306                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
45307       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
45308                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
45309     }
45310   }
45311 
45312   // Try to synthesize horizontal subs from subs of shuffles.
45313   EVT VT = N->getValueType(0);
45314   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
45315        VT == MVT::v8i32) &&
45316       Subtarget.hasSSSE3() &&
45317       isHorizontalBinOp(Op0, Op1, DAG, Subtarget, false)) {
45318     auto HSUBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45319                           ArrayRef<SDValue> Ops) {
45320       return DAG.getNode(X86ISD::HSUB, DL, Ops[0].getValueType(), Ops);
45321     };
45322     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
45323                             HSUBBuilder);
45324   }
45325 
45326   // Try to create PSUBUS if SUB's argument is max/min
45327   if (SDValue V = combineSubToSubus(N, DAG, Subtarget))
45328     return V;
45329 
45330   return combineAddOrSubToADCOrSBB(N, DAG);
45331 }
45332 
combineVectorCompare(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45333 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
45334                                     const X86Subtarget &Subtarget) {
45335   MVT VT = N->getSimpleValueType(0);
45336   SDLoc DL(N);
45337 
45338   if (N->getOperand(0) == N->getOperand(1)) {
45339     if (N->getOpcode() == X86ISD::PCMPEQ)
45340       return DAG.getConstant(-1, DL, VT);
45341     if (N->getOpcode() == X86ISD::PCMPGT)
45342       return DAG.getConstant(0, DL, VT);
45343   }
45344 
45345   return SDValue();
45346 }
45347 
45348 /// Helper that combines an array of subvector ops as if they were the operands
45349 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
45350 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
combineConcatVectorOps(const SDLoc & DL,MVT VT,ArrayRef<SDValue> Ops,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45351 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
45352                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
45353                                       TargetLowering::DAGCombinerInfo &DCI,
45354                                       const X86Subtarget &Subtarget) {
45355   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
45356 
45357   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
45358     return DAG.getUNDEF(VT);
45359 
45360   if (llvm::all_of(Ops, [](SDValue Op) {
45361         return ISD::isBuildVectorAllZeros(Op.getNode());
45362       }))
45363     return getZeroVector(VT, Subtarget, DAG, DL);
45364 
45365   SDValue Op0 = Ops[0];
45366 
45367   // Fold subvector loads into one.
45368   // If needed, look through bitcasts to get to the load.
45369   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
45370     bool Fast;
45371     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
45372     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
45373                                 *FirstLd->getMemOperand(), &Fast) &&
45374         Fast) {
45375       if (SDValue Ld =
45376               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
45377         return Ld;
45378     }
45379   }
45380 
45381   // Repeated subvectors.
45382   if (llvm::all_of(Ops, [Op0](SDValue Op) { return Op == Op0; })) {
45383     // If this broadcast/subv_broadcast is inserted into both halves, use a
45384     // larger broadcast/subv_broadcast.
45385     if (Op0.getOpcode() == X86ISD::VBROADCAST ||
45386         Op0.getOpcode() == X86ISD::SUBV_BROADCAST)
45387       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
45388 
45389     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
45390     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
45391         (Subtarget.hasAVX2() || MayFoldLoad(Op0.getOperand(0))))
45392       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
45393                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
45394                                      Op0.getOperand(0),
45395                                      DAG.getIntPtrConstant(0, DL)));
45396 
45397     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
45398     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
45399         (Subtarget.hasAVX2() ||
45400          (VT.getScalarSizeInBits() >= 32 && MayFoldLoad(Op0.getOperand(0)))) &&
45401         Op0.getOperand(0).getValueType() == VT.getScalarType())
45402       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
45403   }
45404 
45405   bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
45406 
45407   // Repeated opcode.
45408   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
45409   // but it currently struggles with different vector widths.
45410   if (llvm::all_of(Ops, [Op0](SDValue Op) {
45411         return Op.getOpcode() == Op0.getOpcode();
45412       })) {
45413     unsigned NumOps = Ops.size();
45414     switch (Op0.getOpcode()) {
45415     case X86ISD::PSHUFHW:
45416     case X86ISD::PSHUFLW:
45417     case X86ISD::PSHUFD:
45418       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
45419           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
45420         SmallVector<SDValue, 2> Src;
45421         for (unsigned i = 0; i != NumOps; ++i)
45422           Src.push_back(Ops[i].getOperand(0));
45423         return DAG.getNode(Op0.getOpcode(), DL, VT,
45424                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
45425                            Op0.getOperand(1));
45426       }
45427       LLVM_FALLTHROUGH;
45428     case X86ISD::VPERMILPI:
45429       // TODO - add support for vXf64/vXi64 shuffles.
45430       if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
45431           Subtarget.hasAVX() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
45432         SmallVector<SDValue, 2> Src;
45433         for (unsigned i = 0; i != NumOps; ++i)
45434           Src.push_back(DAG.getBitcast(MVT::v4f32, Ops[i].getOperand(0)));
45435         SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f32, Src);
45436         Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
45437                           Op0.getOperand(1));
45438         return DAG.getBitcast(VT, Res);
45439       }
45440       break;
45441     case X86ISD::PACKUS:
45442       if (NumOps == 2 && VT.is256BitVector() && Subtarget.hasInt256()) {
45443         SmallVector<SDValue, 2> LHS, RHS;
45444         for (unsigned i = 0; i != NumOps; ++i) {
45445           LHS.push_back(Ops[i].getOperand(0));
45446           RHS.push_back(Ops[i].getOperand(1));
45447         }
45448         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
45449         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
45450                                  NumOps * SrcVT.getVectorNumElements());
45451         return DAG.getNode(Op0.getOpcode(), DL, VT,
45452                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, LHS),
45453                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, RHS));
45454       }
45455       break;
45456     }
45457   }
45458 
45459   return SDValue();
45460 }
45461 
combineConcatVectors(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45462 static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
45463                                     TargetLowering::DAGCombinerInfo &DCI,
45464                                     const X86Subtarget &Subtarget) {
45465   EVT VT = N->getValueType(0);
45466   EVT SrcVT = N->getOperand(0).getValueType();
45467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45468 
45469   // Don't do anything for i1 vectors.
45470   if (VT.getVectorElementType() == MVT::i1)
45471     return SDValue();
45472 
45473   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
45474     SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
45475     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
45476                                            DCI, Subtarget))
45477       return R;
45478   }
45479 
45480   return SDValue();
45481 }
45482 
combineInsertSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45483 static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
45484                                       TargetLowering::DAGCombinerInfo &DCI,
45485                                       const X86Subtarget &Subtarget) {
45486   if (DCI.isBeforeLegalizeOps())
45487     return SDValue();
45488 
45489   MVT OpVT = N->getSimpleValueType(0);
45490 
45491   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
45492 
45493   SDLoc dl(N);
45494   SDValue Vec = N->getOperand(0);
45495   SDValue SubVec = N->getOperand(1);
45496 
45497   uint64_t IdxVal = N->getConstantOperandVal(2);
45498   MVT SubVecVT = SubVec.getSimpleValueType();
45499 
45500   if (Vec.isUndef() && SubVec.isUndef())
45501     return DAG.getUNDEF(OpVT);
45502 
45503   // Inserting undefs/zeros into zeros/undefs is a zero vector.
45504   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
45505       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
45506     return getZeroVector(OpVT, Subtarget, DAG, dl);
45507 
45508   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
45509     // If we're inserting into a zero vector and then into a larger zero vector,
45510     // just insert into the larger zero vector directly.
45511     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
45512         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
45513       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
45514       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
45515                          getZeroVector(OpVT, Subtarget, DAG, dl),
45516                          SubVec.getOperand(1),
45517                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
45518     }
45519 
45520     // If we're inserting into a zero vector and our input was extracted from an
45521     // insert into a zero vector of the same type and the extraction was at
45522     // least as large as the original insertion. Just insert the original
45523     // subvector into a zero vector.
45524     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
45525         isNullConstant(SubVec.getOperand(1)) &&
45526         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
45527       SDValue Ins = SubVec.getOperand(0);
45528       if (isNullConstant(Ins.getOperand(2)) &&
45529           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
45530           Ins.getOperand(1).getValueSizeInBits() <= SubVecVT.getSizeInBits())
45531         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
45532                            getZeroVector(OpVT, Subtarget, DAG, dl),
45533                            Ins.getOperand(1), N->getOperand(2));
45534     }
45535   }
45536 
45537   // Stop here if this is an i1 vector.
45538   if (IsI1Vector)
45539     return SDValue();
45540 
45541   // If this is an insert of an extract, combine to a shuffle. Don't do this
45542   // if the insert or extract can be represented with a subregister operation.
45543   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45544       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
45545       (IdxVal != 0 || !Vec.isUndef())) {
45546     int ExtIdxVal = SubVec.getConstantOperandVal(1);
45547     if (ExtIdxVal != 0) {
45548       int VecNumElts = OpVT.getVectorNumElements();
45549       int SubVecNumElts = SubVecVT.getVectorNumElements();
45550       SmallVector<int, 64> Mask(VecNumElts);
45551       // First create an identity shuffle mask.
45552       for (int i = 0; i != VecNumElts; ++i)
45553         Mask[i] = i;
45554       // Now insert the extracted portion.
45555       for (int i = 0; i != SubVecNumElts; ++i)
45556         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
45557 
45558       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
45559     }
45560   }
45561 
45562   // Match concat_vector style patterns.
45563   SmallVector<SDValue, 2> SubVectorOps;
45564   if (collectConcatOps(N, SubVectorOps)) {
45565     if (SDValue Fold =
45566             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
45567       return Fold;
45568 
45569     // If we're inserting all zeros into the upper half, change this to
45570     // a concat with zero. We will match this to a move
45571     // with implicit upper bit zeroing during isel.
45572     // We do this here because we don't want combineConcatVectorOps to
45573     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
45574     if (SubVectorOps.size() == 2 &&
45575         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
45576       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
45577                          getZeroVector(OpVT, Subtarget, DAG, dl),
45578                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
45579   }
45580 
45581   // If this is a broadcast insert into an upper undef, use a larger broadcast.
45582   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
45583     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
45584 
45585   // If this is a broadcast load inserted into an upper undef, use a larger
45586   // broadcast load.
45587   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
45588       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
45589     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
45590     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
45591     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
45592     SDValue BcastLd =
45593         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
45594                                 MemIntr->getMemoryVT(),
45595                                 MemIntr->getMemOperand());
45596     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
45597     return BcastLd;
45598   }
45599 
45600   return SDValue();
45601 }
45602 
45603 /// If we are extracting a subvector of a vector select and the select condition
45604 /// is composed of concatenated vectors, try to narrow the select width. This
45605 /// is a common pattern for AVX1 integer code because 256-bit selects may be
45606 /// legal, but there is almost no integer math/logic available for 256-bit.
45607 /// This function should only be called with legal types (otherwise, the calls
45608 /// to get simple value types will assert).
narrowExtractedVectorSelect(SDNode * Ext,SelectionDAG & DAG)45609 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
45610   SDValue Sel = peekThroughBitcasts(Ext->getOperand(0));
45611   SmallVector<SDValue, 4> CatOps;
45612   if (Sel.getOpcode() != ISD::VSELECT ||
45613       !collectConcatOps(Sel.getOperand(0).getNode(), CatOps))
45614     return SDValue();
45615 
45616   // Note: We assume simple value types because this should only be called with
45617   //       legal operations/types.
45618   // TODO: This can be extended to handle extraction to 256-bits.
45619   MVT VT = Ext->getSimpleValueType(0);
45620   if (!VT.is128BitVector())
45621     return SDValue();
45622 
45623   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
45624   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
45625     return SDValue();
45626 
45627   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
45628   MVT SelVT = Sel.getSimpleValueType();
45629   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
45630          "Unexpected vector type with legal operations");
45631 
45632   unsigned SelElts = SelVT.getVectorNumElements();
45633   unsigned CastedElts = WideVT.getVectorNumElements();
45634   unsigned ExtIdx = cast<ConstantSDNode>(Ext->getOperand(1))->getZExtValue();
45635   if (SelElts % CastedElts == 0) {
45636     // The select has the same or more (narrower) elements than the extract
45637     // operand. The extraction index gets scaled by that factor.
45638     ExtIdx *= (SelElts / CastedElts);
45639   } else if (CastedElts % SelElts == 0) {
45640     // The select has less (wider) elements than the extract operand. Make sure
45641     // that the extraction index can be divided evenly.
45642     unsigned IndexDivisor = CastedElts / SelElts;
45643     if (ExtIdx % IndexDivisor != 0)
45644       return SDValue();
45645     ExtIdx /= IndexDivisor;
45646   } else {
45647     llvm_unreachable("Element count of simple vector types are not divisible?");
45648   }
45649 
45650   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
45651   unsigned NarrowElts = SelElts / NarrowingFactor;
45652   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
45653   SDLoc DL(Ext);
45654   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
45655   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
45656   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
45657   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
45658   return DAG.getBitcast(VT, NarrowSel);
45659 }
45660 
combineExtractSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45661 static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
45662                                        TargetLowering::DAGCombinerInfo &DCI,
45663                                        const X86Subtarget &Subtarget) {
45664   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
45665   // eventually get combined/lowered into ANDNP) with a concatenated operand,
45666   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
45667   // We let generic combining take over from there to simplify the
45668   // insert/extract and 'not'.
45669   // This pattern emerges during AVX1 legalization. We handle it before lowering
45670   // to avoid complications like splitting constant vector loads.
45671 
45672   // Capture the original wide type in the likely case that we need to bitcast
45673   // back to this type.
45674   if (!N->getValueType(0).isSimple())
45675     return SDValue();
45676 
45677   MVT VT = N->getSimpleValueType(0);
45678   SDValue InVec = N->getOperand(0);
45679   SDValue InVecBC = peekThroughBitcasts(InVec);
45680   EVT InVecVT = InVec.getValueType();
45681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45682 
45683   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
45684       TLI.isTypeLegal(InVecVT) &&
45685       InVecVT.getSizeInBits() == 256 && InVecBC.getOpcode() == ISD::AND) {
45686     auto isConcatenatedNot = [] (SDValue V) {
45687       V = peekThroughBitcasts(V);
45688       if (!isBitwiseNot(V))
45689         return false;
45690       SDValue NotOp = V->getOperand(0);
45691       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
45692     };
45693     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
45694         isConcatenatedNot(InVecBC.getOperand(1))) {
45695       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
45696       SDValue Concat = split256IntArith(InVecBC, DAG);
45697       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
45698                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
45699     }
45700   }
45701 
45702   if (DCI.isBeforeLegalizeOps())
45703     return SDValue();
45704 
45705   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
45706     return V;
45707 
45708   unsigned IdxVal = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
45709 
45710   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
45711     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
45712 
45713   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
45714     if (VT.getScalarType() == MVT::i1)
45715       return DAG.getConstant(1, SDLoc(N), VT);
45716     return getOnesVector(VT, DAG, SDLoc(N));
45717   }
45718 
45719   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
45720     return DAG.getBuildVector(
45721         VT, SDLoc(N),
45722         InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
45723 
45724   // If we are extracting from an insert into a zero vector, replace with a
45725   // smaller insert into zero if we don't access less than the original
45726   // subvector. Don't do this for i1 vectors.
45727   if (VT.getVectorElementType() != MVT::i1 &&
45728       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && IdxVal == 0 &&
45729       InVec.hasOneUse() && isNullConstant(InVec.getOperand(2)) &&
45730       ISD::isBuildVectorAllZeros(InVec.getOperand(0).getNode()) &&
45731       InVec.getOperand(1).getValueSizeInBits() <= VT.getSizeInBits()) {
45732     SDLoc DL(N);
45733     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
45734                        getZeroVector(VT, Subtarget, DAG, DL),
45735                        InVec.getOperand(1), InVec.getOperand(2));
45736   }
45737 
45738   // If we're extracting from a broadcast then we're better off just
45739   // broadcasting to the smaller type directly, assuming this is the only use.
45740   // As its a broadcast we don't care about the extraction index.
45741   if (InVec.getOpcode() == X86ISD::VBROADCAST && InVec.hasOneUse() &&
45742       InVec.getOperand(0).getValueSizeInBits() <= VT.getSizeInBits())
45743     return DAG.getNode(X86ISD::VBROADCAST, SDLoc(N), VT, InVec.getOperand(0));
45744 
45745   if (InVec.getOpcode() == X86ISD::VBROADCAST_LOAD && InVec.hasOneUse()) {
45746     auto *MemIntr = cast<MemIntrinsicSDNode>(InVec);
45747     if (MemIntr->getMemoryVT().getSizeInBits() <= VT.getSizeInBits()) {
45748       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
45749       SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
45750       SDValue BcastLd =
45751           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
45752                                   MemIntr->getMemoryVT(),
45753                                   MemIntr->getMemOperand());
45754       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
45755       return BcastLd;
45756     }
45757   }
45758 
45759   // If we're extracting the lowest subvector and we're the only user,
45760   // we may be able to perform this with a smaller vector width.
45761   if (IdxVal == 0 && InVec.hasOneUse()) {
45762     unsigned InOpcode = InVec.getOpcode();
45763     if (VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
45764       // v2f64 CVTDQ2PD(v4i32).
45765       if (InOpcode == ISD::SINT_TO_FP &&
45766           InVec.getOperand(0).getValueType() == MVT::v4i32) {
45767         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
45768       }
45769       // v2f64 CVTUDQ2PD(v4i32).
45770       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
45771           InVec.getOperand(0).getValueType() == MVT::v4i32) {
45772         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
45773       }
45774       // v2f64 CVTPS2PD(v4f32).
45775       if (InOpcode == ISD::FP_EXTEND &&
45776           InVec.getOperand(0).getValueType() == MVT::v4f32) {
45777         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
45778       }
45779     }
45780     if ((InOpcode == ISD::ANY_EXTEND ||
45781          InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
45782          InOpcode == ISD::ZERO_EXTEND ||
45783          InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
45784          InOpcode == ISD::SIGN_EXTEND ||
45785          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
45786         VT.is128BitVector() &&
45787         InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
45788       unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
45789       return DAG.getNode(ExtOp, SDLoc(N), VT, InVec.getOperand(0));
45790     }
45791     if (InOpcode == ISD::VSELECT &&
45792         InVec.getOperand(0).getValueType().is256BitVector() &&
45793         InVec.getOperand(1).getValueType().is256BitVector() &&
45794         InVec.getOperand(2).getValueType().is256BitVector()) {
45795       SDLoc DL(N);
45796       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
45797       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
45798       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
45799       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
45800     }
45801   }
45802 
45803   return SDValue();
45804 }
45805 
combineScalarToVector(SDNode * N,SelectionDAG & DAG)45806 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
45807   EVT VT = N->getValueType(0);
45808   SDValue Src = N->getOperand(0);
45809   SDLoc DL(N);
45810 
45811   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
45812   // This occurs frequently in our masked scalar intrinsic code and our
45813   // floating point select lowering with AVX512.
45814   // TODO: SimplifyDemandedBits instead?
45815   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
45816     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
45817       if (C->getAPIntValue().isOneValue())
45818         return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
45819                            Src.getOperand(0));
45820 
45821   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
45822   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
45823       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
45824       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
45825     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
45826       if (C->isNullValue())
45827         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
45828                            Src.getOperand(1));
45829 
45830   // Reduce v2i64 to v4i32 if we don't need the upper bits.
45831   // TODO: Move to DAGCombine?
45832   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::ANY_EXTEND &&
45833       Src.getValueType() == MVT::i64 && Src.hasOneUse() &&
45834       Src.getOperand(0).getScalarValueSizeInBits() <= 32)
45835     return DAG.getBitcast(
45836         VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
45837                         DAG.getAnyExtOrTrunc(Src.getOperand(0), DL, MVT::i32)));
45838 
45839   return SDValue();
45840 }
45841 
45842 // Simplify PMULDQ and PMULUDQ operations.
combinePMULDQ(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45843 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
45844                              TargetLowering::DAGCombinerInfo &DCI,
45845                              const X86Subtarget &Subtarget) {
45846   SDValue LHS = N->getOperand(0);
45847   SDValue RHS = N->getOperand(1);
45848 
45849   // Canonicalize constant to RHS.
45850   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
45851       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
45852     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
45853 
45854   // Multiply by zero.
45855   // Don't return RHS as it may contain UNDEFs.
45856   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
45857     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
45858 
45859   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
45860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45861   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
45862     return SDValue(N, 0);
45863 
45864   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
45865   // convert it to any_extend_invec, due to the LegalOperations check, do the
45866   // conversion directly to a vector shuffle manually. This exposes combine
45867   // opportunities missed by combineExtInVec not calling
45868   // combineX86ShufflesRecursively on SSE4.1 targets.
45869   // FIXME: This is basically a hack around several other issues related to
45870   // ANY_EXTEND_VECTOR_INREG.
45871   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
45872       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
45873        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
45874       LHS.getOperand(0).getValueType() == MVT::v4i32) {
45875     SDLoc dl(N);
45876     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
45877                                LHS.getOperand(0), { 0, -1, 1, -1 });
45878     LHS = DAG.getBitcast(MVT::v2i64, LHS);
45879     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
45880   }
45881   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
45882       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
45883        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
45884       RHS.getOperand(0).getValueType() == MVT::v4i32) {
45885     SDLoc dl(N);
45886     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
45887                                RHS.getOperand(0), { 0, -1, 1, -1 });
45888     RHS = DAG.getBitcast(MVT::v2i64, RHS);
45889     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
45890   }
45891 
45892   return SDValue();
45893 }
45894 
combineExtInVec(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45895 static SDValue combineExtInVec(SDNode *N, SelectionDAG &DAG,
45896                                TargetLowering::DAGCombinerInfo &DCI,
45897                                const X86Subtarget &Subtarget) {
45898   EVT VT = N->getValueType(0);
45899   SDValue In = N->getOperand(0);
45900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45901 
45902   // Try to merge vector loads and extend_inreg to an extload.
45903   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
45904       In.hasOneUse()) {
45905     auto *Ld = cast<LoadSDNode>(In);
45906     if (Ld->isSimple()) {
45907       MVT SVT = In.getSimpleValueType().getVectorElementType();
45908       ISD::LoadExtType Ext = N->getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
45909       EVT MemVT = EVT::getVectorVT(*DAG.getContext(), SVT,
45910                                    VT.getVectorNumElements());
45911       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
45912         SDValue Load =
45913             DAG.getExtLoad(Ext, SDLoc(N), VT, Ld->getChain(), Ld->getBasePtr(),
45914                            Ld->getPointerInfo(), MemVT, Ld->getAlignment(),
45915                            Ld->getMemOperand()->getFlags());
45916         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
45917         return Load;
45918       }
45919     }
45920   }
45921 
45922   // Attempt to combine as a shuffle.
45923   // TODO: SSE41 support
45924   if (Subtarget.hasAVX() && N->getOpcode() != ISD::SIGN_EXTEND_VECTOR_INREG) {
45925     SDValue Op(N, 0);
45926     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
45927       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45928         return Res;
45929   }
45930 
45931   return SDValue();
45932 }
45933 
combineKSHIFT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)45934 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
45935                              TargetLowering::DAGCombinerInfo &DCI) {
45936   EVT VT = N->getValueType(0);
45937 
45938   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
45939     return DAG.getConstant(0, SDLoc(N), VT);
45940 
45941   APInt KnownUndef, KnownZero;
45942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45943   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
45944   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
45945                                      KnownZero, DCI))
45946     return SDValue(N, 0);
45947 
45948   return SDValue();
45949 }
45950 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const45951 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
45952                                              DAGCombinerInfo &DCI) const {
45953   SelectionDAG &DAG = DCI.DAG;
45954   switch (N->getOpcode()) {
45955   default: break;
45956   case ISD::SCALAR_TO_VECTOR:
45957     return combineScalarToVector(N, DAG);
45958   case ISD::EXTRACT_VECTOR_ELT:
45959   case X86ISD::PEXTRW:
45960   case X86ISD::PEXTRB:
45961     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
45962   case ISD::CONCAT_VECTORS:
45963     return combineConcatVectors(N, DAG, DCI, Subtarget);
45964   case ISD::INSERT_SUBVECTOR:
45965     return combineInsertSubvector(N, DAG, DCI, Subtarget);
45966   case ISD::EXTRACT_SUBVECTOR:
45967     return combineExtractSubvector(N, DAG, DCI, Subtarget);
45968   case ISD::VSELECT:
45969   case ISD::SELECT:
45970   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
45971   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
45972   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
45973   case X86ISD::CMP:         return combineCMP(N, DAG);
45974   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
45975   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
45976   case X86ISD::ADD:
45977   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
45978   case X86ISD::SBB:         return combineSBB(N, DAG);
45979   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
45980   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
45981   case ISD::SHL:            return combineShiftLeft(N, DAG);
45982   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG);
45983   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI);
45984   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
45985   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
45986   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
45987   case X86ISD::BEXTR:       return combineBEXTR(N, DAG, DCI, Subtarget);
45988   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
45989   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
45990   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
45991   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
45992   case ISD::SINT_TO_FP:
45993   case ISD::STRICT_SINT_TO_FP:
45994     return combineSIntToFP(N, DAG, DCI, Subtarget);
45995   case ISD::UINT_TO_FP:
45996   case ISD::STRICT_UINT_TO_FP:
45997     return combineUIntToFP(N, DAG, Subtarget);
45998   case ISD::FADD:
45999   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
46000   case ISD::FNEG:           return combineFneg(N, DAG, Subtarget);
46001   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
46002   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG);
46003   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
46004   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
46005   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
46006   case X86ISD::FXOR:
46007   case X86ISD::FOR:         return combineFOr(N, DAG, Subtarget);
46008   case X86ISD::FMIN:
46009   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
46010   case ISD::FMINNUM:
46011   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
46012   case X86ISD::CVTSI2P:
46013   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
46014   case X86ISD::CVTP2SI:
46015   case X86ISD::CVTP2UI:
46016   case X86ISD::CVTTP2SI:
46017   case X86ISD::CVTTP2UI:    return combineCVTP2I_CVTTP2I(N, DAG, DCI);
46018   case X86ISD::BT:          return combineBT(N, DAG, DCI);
46019   case ISD::ANY_EXTEND:
46020   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
46021   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
46022   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
46023   case ISD::ANY_EXTEND_VECTOR_INREG:
46024   case ISD::SIGN_EXTEND_VECTOR_INREG:
46025   case ISD::ZERO_EXTEND_VECTOR_INREG: return combineExtInVec(N, DAG, DCI,
46026                                                              Subtarget);
46027   case ISD::SETCC:          return combineSetCC(N, DAG, Subtarget);
46028   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
46029   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
46030   case X86ISD::PACKSS:
46031   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
46032   case X86ISD::VSHL:
46033   case X86ISD::VSRA:
46034   case X86ISD::VSRL:
46035     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
46036   case X86ISD::VSHLI:
46037   case X86ISD::VSRAI:
46038   case X86ISD::VSRLI:
46039     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
46040   case X86ISD::PINSRB:
46041   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
46042   case X86ISD::SHUFP:       // Handle all target specific shuffles
46043   case X86ISD::INSERTPS:
46044   case X86ISD::EXTRQI:
46045   case X86ISD::INSERTQI:
46046   case X86ISD::PALIGNR:
46047   case X86ISD::VSHLDQ:
46048   case X86ISD::VSRLDQ:
46049   case X86ISD::BLENDI:
46050   case X86ISD::UNPCKH:
46051   case X86ISD::UNPCKL:
46052   case X86ISD::MOVHLPS:
46053   case X86ISD::MOVLHPS:
46054   case X86ISD::PSHUFB:
46055   case X86ISD::PSHUFD:
46056   case X86ISD::PSHUFHW:
46057   case X86ISD::PSHUFLW:
46058   case X86ISD::MOVSHDUP:
46059   case X86ISD::MOVSLDUP:
46060   case X86ISD::MOVDDUP:
46061   case X86ISD::MOVSS:
46062   case X86ISD::MOVSD:
46063   case X86ISD::VBROADCAST:
46064   case X86ISD::VPPERM:
46065   case X86ISD::VPERMI:
46066   case X86ISD::VPERMV:
46067   case X86ISD::VPERMV3:
46068   case X86ISD::VPERMIL2:
46069   case X86ISD::VPERMILPI:
46070   case X86ISD::VPERMILPV:
46071   case X86ISD::VPERM2X128:
46072   case X86ISD::SHUF128:
46073   case X86ISD::VZEXT_MOVL:
46074   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
46075   case X86ISD::FMADD_RND:
46076   case X86ISD::FMSUB:
46077   case X86ISD::FMSUB_RND:
46078   case X86ISD::FNMADD:
46079   case X86ISD::FNMADD_RND:
46080   case X86ISD::FNMSUB:
46081   case X86ISD::FNMSUB_RND:
46082   case ISD::FMA: return combineFMA(N, DAG, DCI, Subtarget);
46083   case X86ISD::FMADDSUB_RND:
46084   case X86ISD::FMSUBADD_RND:
46085   case X86ISD::FMADDSUB:
46086   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
46087   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
46088   case X86ISD::MGATHER:
46089   case X86ISD::MSCATTER:    return combineX86GatherScatter(N, DAG, DCI);
46090   case ISD::MGATHER:
46091   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
46092   case X86ISD::PCMPEQ:
46093   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
46094   case X86ISD::PMULDQ:
46095   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
46096   case X86ISD::KSHIFTL:
46097   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
46098   }
46099 
46100   return SDValue();
46101 }
46102 
isTypeDesirableForOp(unsigned Opc,EVT VT) const46103 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
46104   if (!isTypeLegal(VT))
46105     return false;
46106 
46107   // There are no vXi8 shifts.
46108   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
46109     return false;
46110 
46111   // TODO: Almost no 8-bit ops are desirable because they have no actual
46112   //       size/speed advantages vs. 32-bit ops, but they do have a major
46113   //       potential disadvantage by causing partial register stalls.
46114   //
46115   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
46116   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
46117   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
46118   // check for a constant operand to the multiply.
46119   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
46120     return false;
46121 
46122   // i16 instruction encodings are longer and some i16 instructions are slow,
46123   // so those are not desirable.
46124   if (VT == MVT::i16) {
46125     switch (Opc) {
46126     default:
46127       break;
46128     case ISD::LOAD:
46129     case ISD::SIGN_EXTEND:
46130     case ISD::ZERO_EXTEND:
46131     case ISD::ANY_EXTEND:
46132     case ISD::SHL:
46133     case ISD::SRA:
46134     case ISD::SRL:
46135     case ISD::SUB:
46136     case ISD::ADD:
46137     case ISD::MUL:
46138     case ISD::AND:
46139     case ISD::OR:
46140     case ISD::XOR:
46141       return false;
46142     }
46143   }
46144 
46145   // Any legal type not explicitly accounted for above here is desirable.
46146   return true;
46147 }
46148 
expandIndirectJTBranch(const SDLoc & dl,SDValue Value,SDValue Addr,SelectionDAG & DAG) const46149 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
46150                                                   SDValue Value, SDValue Addr,
46151                                                   SelectionDAG &DAG) const {
46152   const Module *M = DAG.getMachineFunction().getMMI().getModule();
46153   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
46154   if (IsCFProtectionSupported) {
46155     // In case control-flow branch protection is enabled, we need to add
46156     // notrack prefix to the indirect branch.
46157     // In order to do that we create NT_BRIND SDNode.
46158     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
46159     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
46160   }
46161 
46162   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
46163 }
46164 
IsDesirableToPromoteOp(SDValue Op,EVT & PVT) const46165 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
46166   EVT VT = Op.getValueType();
46167   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
46168                              isa<ConstantSDNode>(Op.getOperand(1));
46169 
46170   // i16 is legal, but undesirable since i16 instruction encodings are longer
46171   // and some i16 instructions are slow.
46172   // 8-bit multiply-by-constant can usually be expanded to something cheaper
46173   // using LEA and/or other ALU ops.
46174   if (VT != MVT::i16 && !Is8BitMulByConstant)
46175     return false;
46176 
46177   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
46178     if (!Op.hasOneUse())
46179       return false;
46180     SDNode *User = *Op->use_begin();
46181     if (!ISD::isNormalStore(User))
46182       return false;
46183     auto *Ld = cast<LoadSDNode>(Load);
46184     auto *St = cast<StoreSDNode>(User);
46185     return Ld->getBasePtr() == St->getBasePtr();
46186   };
46187 
46188   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
46189     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
46190       return false;
46191     if (!Op.hasOneUse())
46192       return false;
46193     SDNode *User = *Op->use_begin();
46194     if (User->getOpcode() != ISD::ATOMIC_STORE)
46195       return false;
46196     auto *Ld = cast<AtomicSDNode>(Load);
46197     auto *St = cast<AtomicSDNode>(User);
46198     return Ld->getBasePtr() == St->getBasePtr();
46199   };
46200 
46201   bool Commute = false;
46202   switch (Op.getOpcode()) {
46203   default: return false;
46204   case ISD::SIGN_EXTEND:
46205   case ISD::ZERO_EXTEND:
46206   case ISD::ANY_EXTEND:
46207     break;
46208   case ISD::SHL:
46209   case ISD::SRA:
46210   case ISD::SRL: {
46211     SDValue N0 = Op.getOperand(0);
46212     // Look out for (store (shl (load), x)).
46213     if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
46214       return false;
46215     break;
46216   }
46217   case ISD::ADD:
46218   case ISD::MUL:
46219   case ISD::AND:
46220   case ISD::OR:
46221   case ISD::XOR:
46222     Commute = true;
46223     LLVM_FALLTHROUGH;
46224   case ISD::SUB: {
46225     SDValue N0 = Op.getOperand(0);
46226     SDValue N1 = Op.getOperand(1);
46227     // Avoid disabling potential load folding opportunities.
46228     if (MayFoldLoad(N1) &&
46229         (!Commute || !isa<ConstantSDNode>(N0) ||
46230          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
46231       return false;
46232     if (MayFoldLoad(N0) &&
46233         ((Commute && !isa<ConstantSDNode>(N1)) ||
46234          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
46235       return false;
46236     if (IsFoldableAtomicRMW(N0, Op) ||
46237         (Commute && IsFoldableAtomicRMW(N1, Op)))
46238       return false;
46239   }
46240   }
46241 
46242   PVT = MVT::i32;
46243   return true;
46244 }
46245 
46246 bool X86TargetLowering::
isDesirableToCombineBuildVectorToShuffleTruncate(ArrayRef<int> ShuffleMask,EVT SrcVT,EVT TruncVT) const46247     isDesirableToCombineBuildVectorToShuffleTruncate(
46248         ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
46249 
46250   assert(SrcVT.getVectorNumElements() == ShuffleMask.size() &&
46251          "Element count mismatch");
46252   assert(
46253       Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) &&
46254       "Shuffle Mask expected to be legal");
46255 
46256   // For 32-bit elements VPERMD is better than shuffle+truncate.
46257   // TODO: After we improve lowerBuildVector, add execption for VPERMW.
46258   if (SrcVT.getScalarSizeInBits() == 32 || !Subtarget.hasAVX2())
46259     return false;
46260 
46261   if (is128BitLaneCrossingShuffleMask(SrcVT.getSimpleVT(), ShuffleMask))
46262     return false;
46263 
46264   return true;
46265 }
46266 
46267 //===----------------------------------------------------------------------===//
46268 //                           X86 Inline Assembly Support
46269 //===----------------------------------------------------------------------===//
46270 
46271 // Helper to match a string separated by whitespace.
matchAsm(StringRef S,ArrayRef<const char * > Pieces)46272 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
46273   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
46274 
46275   for (StringRef Piece : Pieces) {
46276     if (!S.startswith(Piece)) // Check if the piece matches.
46277       return false;
46278 
46279     S = S.substr(Piece.size());
46280     StringRef::size_type Pos = S.find_first_not_of(" \t");
46281     if (Pos == 0) // We matched a prefix.
46282       return false;
46283 
46284     S = S.substr(Pos);
46285   }
46286 
46287   return S.empty();
46288 }
46289 
clobbersFlagRegisters(const SmallVector<StringRef,4> & AsmPieces)46290 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
46291 
46292   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
46293     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
46294         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
46295         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
46296 
46297       if (AsmPieces.size() == 3)
46298         return true;
46299       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
46300         return true;
46301     }
46302   }
46303   return false;
46304 }
46305 
ExpandInlineAsm(CallInst * CI) const46306 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
46307   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
46308 
46309   const std::string &AsmStr = IA->getAsmString();
46310 
46311   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
46312   if (!Ty || Ty->getBitWidth() % 16 != 0)
46313     return false;
46314 
46315   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
46316   SmallVector<StringRef, 4> AsmPieces;
46317   SplitString(AsmStr, AsmPieces, ";\n");
46318 
46319   switch (AsmPieces.size()) {
46320   default: return false;
46321   case 1:
46322     // FIXME: this should verify that we are targeting a 486 or better.  If not,
46323     // we will turn this bswap into something that will be lowered to logical
46324     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
46325     // lower so don't worry about this.
46326     // bswap $0
46327     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
46328         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
46329         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
46330         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
46331         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
46332         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
46333       // No need to check constraints, nothing other than the equivalent of
46334       // "=r,0" would be valid here.
46335       return IntrinsicLowering::LowerToByteSwap(CI);
46336     }
46337 
46338     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
46339     if (CI->getType()->isIntegerTy(16) &&
46340         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
46341         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
46342          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
46343       AsmPieces.clear();
46344       StringRef ConstraintsStr = IA->getConstraintString();
46345       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
46346       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
46347       if (clobbersFlagRegisters(AsmPieces))
46348         return IntrinsicLowering::LowerToByteSwap(CI);
46349     }
46350     break;
46351   case 3:
46352     if (CI->getType()->isIntegerTy(32) &&
46353         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
46354         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
46355         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
46356         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
46357       AsmPieces.clear();
46358       StringRef ConstraintsStr = IA->getConstraintString();
46359       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
46360       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
46361       if (clobbersFlagRegisters(AsmPieces))
46362         return IntrinsicLowering::LowerToByteSwap(CI);
46363     }
46364 
46365     if (CI->getType()->isIntegerTy(64)) {
46366       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
46367       if (Constraints.size() >= 2 &&
46368           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
46369           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
46370         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
46371         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
46372             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
46373             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
46374           return IntrinsicLowering::LowerToByteSwap(CI);
46375       }
46376     }
46377     break;
46378   }
46379   return false;
46380 }
46381 
parseConstraintCode(llvm::StringRef Constraint)46382 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
46383   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
46384                            .Case("{@cca}", X86::COND_A)
46385                            .Case("{@ccae}", X86::COND_AE)
46386                            .Case("{@ccb}", X86::COND_B)
46387                            .Case("{@ccbe}", X86::COND_BE)
46388                            .Case("{@ccc}", X86::COND_B)
46389                            .Case("{@cce}", X86::COND_E)
46390                            .Case("{@ccz}", X86::COND_E)
46391                            .Case("{@ccg}", X86::COND_G)
46392                            .Case("{@ccge}", X86::COND_GE)
46393                            .Case("{@ccl}", X86::COND_L)
46394                            .Case("{@ccle}", X86::COND_LE)
46395                            .Case("{@ccna}", X86::COND_BE)
46396                            .Case("{@ccnae}", X86::COND_B)
46397                            .Case("{@ccnb}", X86::COND_AE)
46398                            .Case("{@ccnbe}", X86::COND_A)
46399                            .Case("{@ccnc}", X86::COND_AE)
46400                            .Case("{@ccne}", X86::COND_NE)
46401                            .Case("{@ccnz}", X86::COND_NE)
46402                            .Case("{@ccng}", X86::COND_LE)
46403                            .Case("{@ccnge}", X86::COND_L)
46404                            .Case("{@ccnl}", X86::COND_GE)
46405                            .Case("{@ccnle}", X86::COND_G)
46406                            .Case("{@ccno}", X86::COND_NO)
46407                            .Case("{@ccnp}", X86::COND_P)
46408                            .Case("{@ccns}", X86::COND_NS)
46409                            .Case("{@cco}", X86::COND_O)
46410                            .Case("{@ccp}", X86::COND_P)
46411                            .Case("{@ccs}", X86::COND_S)
46412                            .Default(X86::COND_INVALID);
46413   return Cond;
46414 }
46415 
46416 /// Given a constraint letter, return the type of constraint for this target.
46417 X86TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const46418 X86TargetLowering::getConstraintType(StringRef Constraint) const {
46419   if (Constraint.size() == 1) {
46420     switch (Constraint[0]) {
46421     case 'R':
46422     case 'q':
46423     case 'Q':
46424     case 'f':
46425     case 't':
46426     case 'u':
46427     case 'y':
46428     case 'x':
46429     case 'v':
46430     case 'Y':
46431     case 'l':
46432     case 'k': // AVX512 masking registers.
46433       return C_RegisterClass;
46434     case 'a':
46435     case 'b':
46436     case 'c':
46437     case 'd':
46438     case 'S':
46439     case 'D':
46440     case 'A':
46441       return C_Register;
46442     case 'I':
46443     case 'J':
46444     case 'K':
46445     case 'N':
46446     case 'G':
46447     case 'L':
46448     case 'M':
46449       return C_Immediate;
46450     case 'C':
46451     case 'e':
46452     case 'Z':
46453       return C_Other;
46454     default:
46455       break;
46456     }
46457   }
46458   else if (Constraint.size() == 2) {
46459     switch (Constraint[0]) {
46460     default:
46461       break;
46462     case 'Y':
46463       switch (Constraint[1]) {
46464       default:
46465         break;
46466       case 'z':
46467       case '0':
46468         return C_Register;
46469       case 'i':
46470       case 'm':
46471       case 'k':
46472       case 't':
46473       case '2':
46474         return C_RegisterClass;
46475       }
46476     }
46477   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
46478     return C_Other;
46479   return TargetLowering::getConstraintType(Constraint);
46480 }
46481 
46482 /// Examine constraint type and operand type and determine a weight value.
46483 /// This object must already have been set up with the operand type
46484 /// and the current alternative constraint selected.
46485 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const46486   X86TargetLowering::getSingleConstraintMatchWeight(
46487     AsmOperandInfo &info, const char *constraint) const {
46488   ConstraintWeight weight = CW_Invalid;
46489   Value *CallOperandVal = info.CallOperandVal;
46490     // If we don't have a value, we can't do a match,
46491     // but allow it at the lowest weight.
46492   if (!CallOperandVal)
46493     return CW_Default;
46494   Type *type = CallOperandVal->getType();
46495   // Look at the constraint type.
46496   switch (*constraint) {
46497   default:
46498     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
46499     LLVM_FALLTHROUGH;
46500   case 'R':
46501   case 'q':
46502   case 'Q':
46503   case 'a':
46504   case 'b':
46505   case 'c':
46506   case 'd':
46507   case 'S':
46508   case 'D':
46509   case 'A':
46510     if (CallOperandVal->getType()->isIntegerTy())
46511       weight = CW_SpecificReg;
46512     break;
46513   case 'f':
46514   case 't':
46515   case 'u':
46516     if (type->isFloatingPointTy())
46517       weight = CW_SpecificReg;
46518     break;
46519   case 'y':
46520     if (type->isX86_MMXTy() && Subtarget.hasMMX())
46521       weight = CW_SpecificReg;
46522     break;
46523   case 'Y': {
46524     unsigned Size = StringRef(constraint).size();
46525     // Pick 'i' as the next char as 'Yi' and 'Y' are synonymous, when matching 'Y'
46526     char NextChar = Size == 2 ? constraint[1] : 'i';
46527     if (Size > 2)
46528       break;
46529     switch (NextChar) {
46530       default:
46531         return CW_Invalid;
46532       // XMM0
46533       case 'z':
46534       case '0':
46535         if ((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1())
46536           return CW_SpecificReg;
46537         return CW_Invalid;
46538       // Conditional OpMask regs (AVX512)
46539       case 'k':
46540         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
46541           return CW_Register;
46542         return CW_Invalid;
46543       // Any MMX reg
46544       case 'm':
46545         if (type->isX86_MMXTy() && Subtarget.hasMMX())
46546           return weight;
46547         return CW_Invalid;
46548       // Any SSE reg when ISA >= SSE2, same as 'Y'
46549       case 'i':
46550       case 't':
46551       case '2':
46552         if (!Subtarget.hasSSE2())
46553           return CW_Invalid;
46554         break;
46555     }
46556     // Fall through (handle "Y" constraint).
46557     LLVM_FALLTHROUGH;
46558   }
46559   case 'v':
46560     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
46561       weight = CW_Register;
46562     LLVM_FALLTHROUGH;
46563   case 'x':
46564     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
46565         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
46566       weight = CW_Register;
46567     break;
46568   case 'k':
46569     // Enable conditional vector operations using %k<#> registers.
46570     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
46571       weight = CW_Register;
46572     break;
46573   case 'I':
46574     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
46575       if (C->getZExtValue() <= 31)
46576         weight = CW_Constant;
46577     }
46578     break;
46579   case 'J':
46580     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46581       if (C->getZExtValue() <= 63)
46582         weight = CW_Constant;
46583     }
46584     break;
46585   case 'K':
46586     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46587       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
46588         weight = CW_Constant;
46589     }
46590     break;
46591   case 'L':
46592     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46593       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
46594         weight = CW_Constant;
46595     }
46596     break;
46597   case 'M':
46598     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46599       if (C->getZExtValue() <= 3)
46600         weight = CW_Constant;
46601     }
46602     break;
46603   case 'N':
46604     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46605       if (C->getZExtValue() <= 0xff)
46606         weight = CW_Constant;
46607     }
46608     break;
46609   case 'G':
46610   case 'C':
46611     if (isa<ConstantFP>(CallOperandVal)) {
46612       weight = CW_Constant;
46613     }
46614     break;
46615   case 'e':
46616     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46617       if ((C->getSExtValue() >= -0x80000000LL) &&
46618           (C->getSExtValue() <= 0x7fffffffLL))
46619         weight = CW_Constant;
46620     }
46621     break;
46622   case 'Z':
46623     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
46624       if (C->getZExtValue() <= 0xffffffff)
46625         weight = CW_Constant;
46626     }
46627     break;
46628   }
46629   return weight;
46630 }
46631 
46632 /// Try to replace an X constraint, which matches anything, with another that
46633 /// has more specific requirements based on the type of the corresponding
46634 /// operand.
46635 const char *X86TargetLowering::
LowerXConstraint(EVT ConstraintVT) const46636 LowerXConstraint(EVT ConstraintVT) const {
46637   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
46638   // 'f' like normal targets.
46639   if (ConstraintVT.isFloatingPoint()) {
46640     if (Subtarget.hasSSE2())
46641       return "Y";
46642     if (Subtarget.hasSSE1())
46643       return "x";
46644   }
46645 
46646   return TargetLowering::LowerXConstraint(ConstraintVT);
46647 }
46648 
46649 // Lower @cc targets via setcc.
LowerAsmOutputForConstraint(SDValue & Chain,SDValue & Flag,SDLoc DL,const AsmOperandInfo & OpInfo,SelectionDAG & DAG) const46650 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
46651     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
46652     SelectionDAG &DAG) const {
46653   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
46654   if (Cond == X86::COND_INVALID)
46655     return SDValue();
46656   // Check that return type is valid.
46657   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
46658       OpInfo.ConstraintVT.getSizeInBits() < 8)
46659     report_fatal_error("Flag output operand is of invalid type");
46660 
46661   // Get EFLAGS register. Only update chain when copyfrom is glued.
46662   if (Flag.getNode()) {
46663     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
46664     Chain = Flag.getValue(1);
46665   } else
46666     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
46667   // Extract CC code.
46668   SDValue CC = getSETCC(Cond, Flag, DL, DAG);
46669   // Extend to 32-bits
46670   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
46671 
46672   return Result;
46673 }
46674 
46675 /// Lower the specified operand into the Ops vector.
46676 /// If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const46677 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
46678                                                      std::string &Constraint,
46679                                                      std::vector<SDValue>&Ops,
46680                                                      SelectionDAG &DAG) const {
46681   SDValue Result;
46682 
46683   // Only support length 1 constraints for now.
46684   if (Constraint.length() > 1) return;
46685 
46686   char ConstraintLetter = Constraint[0];
46687   switch (ConstraintLetter) {
46688   default: break;
46689   case 'I':
46690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46691       if (C->getZExtValue() <= 31) {
46692         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46693                                        Op.getValueType());
46694         break;
46695       }
46696     }
46697     return;
46698   case 'J':
46699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46700       if (C->getZExtValue() <= 63) {
46701         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46702                                        Op.getValueType());
46703         break;
46704       }
46705     }
46706     return;
46707   case 'K':
46708     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46709       if (isInt<8>(C->getSExtValue())) {
46710         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46711                                        Op.getValueType());
46712         break;
46713       }
46714     }
46715     return;
46716   case 'L':
46717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46718       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
46719           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
46720         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
46721                                        Op.getValueType());
46722         break;
46723       }
46724     }
46725     return;
46726   case 'M':
46727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46728       if (C->getZExtValue() <= 3) {
46729         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46730                                        Op.getValueType());
46731         break;
46732       }
46733     }
46734     return;
46735   case 'N':
46736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46737       if (C->getZExtValue() <= 255) {
46738         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46739                                        Op.getValueType());
46740         break;
46741       }
46742     }
46743     return;
46744   case 'O':
46745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46746       if (C->getZExtValue() <= 127) {
46747         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46748                                        Op.getValueType());
46749         break;
46750       }
46751     }
46752     return;
46753   case 'e': {
46754     // 32-bit signed value
46755     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46756       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
46757                                            C->getSExtValue())) {
46758         // Widen to 64 bits here to get it sign extended.
46759         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
46760         break;
46761       }
46762     // FIXME gcc accepts some relocatable values here too, but only in certain
46763     // memory models; it's complicated.
46764     }
46765     return;
46766   }
46767   case 'Z': {
46768     // 32-bit unsigned value
46769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
46770       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
46771                                            C->getZExtValue())) {
46772         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
46773                                        Op.getValueType());
46774         break;
46775       }
46776     }
46777     // FIXME gcc accepts some relocatable values here too, but only in certain
46778     // memory models; it's complicated.
46779     return;
46780   }
46781   case 'i': {
46782     // Literal immediates are always ok.
46783     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
46784       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
46785       BooleanContent BCont = getBooleanContents(MVT::i64);
46786       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
46787                                     : ISD::SIGN_EXTEND;
46788       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
46789                                                   : CST->getSExtValue();
46790       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
46791       break;
46792     }
46793 
46794     // In any sort of PIC mode addresses need to be computed at runtime by
46795     // adding in a register or some sort of table lookup.  These can't
46796     // be used as immediates.
46797     if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
46798       return;
46799 
46800     // If we are in non-pic codegen mode, we allow the address of a global (with
46801     // an optional displacement) to be used with 'i'.
46802     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
46803       // If we require an extra load to get this address, as in PIC mode, we
46804       // can't accept it.
46805       if (isGlobalStubReference(
46806               Subtarget.classifyGlobalReference(GA->getGlobal())))
46807         return;
46808     break;
46809   }
46810   }
46811 
46812   if (Result.getNode()) {
46813     Ops.push_back(Result);
46814     return;
46815   }
46816   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
46817 }
46818 
46819 /// Check if \p RC is a general purpose register class.
46820 /// I.e., GR* or one of their variant.
isGRClass(const TargetRegisterClass & RC)46821 static bool isGRClass(const TargetRegisterClass &RC) {
46822   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
46823          RC.hasSuperClassEq(&X86::GR16RegClass) ||
46824          RC.hasSuperClassEq(&X86::GR32RegClass) ||
46825          RC.hasSuperClassEq(&X86::GR64RegClass) ||
46826          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
46827 }
46828 
46829 /// Check if \p RC is a vector register class.
46830 /// I.e., FR* / VR* or one of their variant.
isFRClass(const TargetRegisterClass & RC)46831 static bool isFRClass(const TargetRegisterClass &RC) {
46832   return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
46833          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
46834          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
46835          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
46836          RC.hasSuperClassEq(&X86::VR512RegClass);
46837 }
46838 
46839 /// Check if \p RC is a mask register class.
46840 /// I.e., VK* or one of their variant.
isVKClass(const TargetRegisterClass & RC)46841 static bool isVKClass(const TargetRegisterClass &RC) {
46842   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
46843          RC.hasSuperClassEq(&X86::VK2RegClass) ||
46844          RC.hasSuperClassEq(&X86::VK4RegClass) ||
46845          RC.hasSuperClassEq(&X86::VK8RegClass) ||
46846          RC.hasSuperClassEq(&X86::VK16RegClass) ||
46847          RC.hasSuperClassEq(&X86::VK32RegClass) ||
46848          RC.hasSuperClassEq(&X86::VK64RegClass);
46849 }
46850 
46851 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const46852 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
46853                                                 StringRef Constraint,
46854                                                 MVT VT) const {
46855   // First, see if this is a constraint that directly corresponds to an LLVM
46856   // register class.
46857   if (Constraint.size() == 1) {
46858     // GCC Constraint Letters
46859     switch (Constraint[0]) {
46860     default: break;
46861     // 'A' means [ER]AX + [ER]DX.
46862     case 'A':
46863       if (Subtarget.is64Bit())
46864         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
46865       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
46866              "Expecting 64, 32 or 16 bit subtarget");
46867       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
46868 
46869       // TODO: Slight differences here in allocation order and leaving
46870       // RIP in the class. Do they matter any more here than they do
46871       // in the normal allocation?
46872     case 'k':
46873       if (Subtarget.hasAVX512()) {
46874         if (VT == MVT::i1)
46875           return std::make_pair(0U, &X86::VK1RegClass);
46876         if (VT == MVT::i8)
46877           return std::make_pair(0U, &X86::VK8RegClass);
46878         if (VT == MVT::i16)
46879           return std::make_pair(0U, &X86::VK16RegClass);
46880       }
46881       if (Subtarget.hasBWI()) {
46882         if (VT == MVT::i32)
46883           return std::make_pair(0U, &X86::VK32RegClass);
46884         if (VT == MVT::i64)
46885           return std::make_pair(0U, &X86::VK64RegClass);
46886       }
46887       break;
46888     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
46889       if (Subtarget.is64Bit()) {
46890         if (VT == MVT::i32 || VT == MVT::f32)
46891           return std::make_pair(0U, &X86::GR32RegClass);
46892         if (VT == MVT::i16)
46893           return std::make_pair(0U, &X86::GR16RegClass);
46894         if (VT == MVT::i8 || VT == MVT::i1)
46895           return std::make_pair(0U, &X86::GR8RegClass);
46896         if (VT == MVT::i64 || VT == MVT::f64)
46897           return std::make_pair(0U, &X86::GR64RegClass);
46898         break;
46899       }
46900       LLVM_FALLTHROUGH;
46901       // 32-bit fallthrough
46902     case 'Q':   // Q_REGS
46903       if (VT == MVT::i32 || VT == MVT::f32)
46904         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
46905       if (VT == MVT::i16)
46906         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
46907       if (VT == MVT::i8 || VT == MVT::i1)
46908         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
46909       if (VT == MVT::i64)
46910         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
46911       break;
46912     case 'r':   // GENERAL_REGS
46913     case 'l':   // INDEX_REGS
46914       if (VT == MVT::i8 || VT == MVT::i1)
46915         return std::make_pair(0U, &X86::GR8RegClass);
46916       if (VT == MVT::i16)
46917         return std::make_pair(0U, &X86::GR16RegClass);
46918       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
46919         return std::make_pair(0U, &X86::GR32RegClass);
46920       return std::make_pair(0U, &X86::GR64RegClass);
46921     case 'R':   // LEGACY_REGS
46922       if (VT == MVT::i8 || VT == MVT::i1)
46923         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
46924       if (VT == MVT::i16)
46925         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
46926       if (VT == MVT::i32 || !Subtarget.is64Bit())
46927         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
46928       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
46929     case 'f':  // FP Stack registers.
46930       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
46931       // value to the correct fpstack register class.
46932       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
46933         return std::make_pair(0U, &X86::RFP32RegClass);
46934       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
46935         return std::make_pair(0U, &X86::RFP64RegClass);
46936       return std::make_pair(0U, &X86::RFP80RegClass);
46937     case 'y':   // MMX_REGS if MMX allowed.
46938       if (!Subtarget.hasMMX()) break;
46939       return std::make_pair(0U, &X86::VR64RegClass);
46940     case 'Y':   // SSE_REGS if SSE2 allowed
46941       if (!Subtarget.hasSSE2()) break;
46942       LLVM_FALLTHROUGH;
46943     case 'v':
46944     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
46945       if (!Subtarget.hasSSE1()) break;
46946       bool VConstraint = (Constraint[0] == 'v');
46947 
46948       switch (VT.SimpleTy) {
46949       default: break;
46950       // Scalar SSE types.
46951       case MVT::f32:
46952       case MVT::i32:
46953         if (VConstraint && Subtarget.hasVLX())
46954           return std::make_pair(0U, &X86::FR32XRegClass);
46955         return std::make_pair(0U, &X86::FR32RegClass);
46956       case MVT::f64:
46957       case MVT::i64:
46958         if (VConstraint && Subtarget.hasVLX())
46959           return std::make_pair(0U, &X86::FR64XRegClass);
46960         return std::make_pair(0U, &X86::FR64RegClass);
46961       // TODO: Handle i128 in FR128RegClass after it is tested well.
46962       // Vector types and fp128.
46963       case MVT::f128:
46964       case MVT::v16i8:
46965       case MVT::v8i16:
46966       case MVT::v4i32:
46967       case MVT::v2i64:
46968       case MVT::v4f32:
46969       case MVT::v2f64:
46970         if (VConstraint && Subtarget.hasVLX())
46971           return std::make_pair(0U, &X86::VR128XRegClass);
46972         return std::make_pair(0U, &X86::VR128RegClass);
46973       // AVX types.
46974       case MVT::v32i8:
46975       case MVT::v16i16:
46976       case MVT::v8i32:
46977       case MVT::v4i64:
46978       case MVT::v8f32:
46979       case MVT::v4f64:
46980         if (VConstraint && Subtarget.hasVLX())
46981           return std::make_pair(0U, &X86::VR256XRegClass);
46982         if (Subtarget.hasAVX())
46983           return std::make_pair(0U, &X86::VR256RegClass);
46984         break;
46985       case MVT::v8f64:
46986       case MVT::v16f32:
46987       case MVT::v16i32:
46988       case MVT::v8i64:
46989         if (!Subtarget.hasAVX512()) break;
46990         if (VConstraint)
46991           return std::make_pair(0U, &X86::VR512RegClass);
46992         return std::make_pair(0U, &X86::VR512_0_15RegClass);
46993       }
46994       break;
46995     }
46996   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
46997     switch (Constraint[1]) {
46998     default:
46999       break;
47000     case 'i':
47001     case 't':
47002     case '2':
47003       return getRegForInlineAsmConstraint(TRI, "Y", VT);
47004     case 'm':
47005       if (!Subtarget.hasMMX()) break;
47006       return std::make_pair(0U, &X86::VR64RegClass);
47007     case 'z':
47008     case '0':
47009       if (!Subtarget.hasSSE1()) break;
47010       return std::make_pair(X86::XMM0, &X86::VR128RegClass);
47011     case 'k':
47012       // This register class doesn't allocate k0 for masked vector operation.
47013       if (Subtarget.hasAVX512()) {
47014         if (VT == MVT::i1)
47015           return std::make_pair(0U, &X86::VK1WMRegClass);
47016         if (VT == MVT::i8)
47017           return std::make_pair(0U, &X86::VK8WMRegClass);
47018         if (VT == MVT::i16)
47019           return std::make_pair(0U, &X86::VK16WMRegClass);
47020       }
47021       if (Subtarget.hasBWI()) {
47022         if (VT == MVT::i32)
47023           return std::make_pair(0U, &X86::VK32WMRegClass);
47024         if (VT == MVT::i64)
47025           return std::make_pair(0U, &X86::VK64WMRegClass);
47026       }
47027       break;
47028     }
47029   }
47030 
47031   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
47032     return std::make_pair(0U, &X86::GR32RegClass);
47033 
47034   // Use the default implementation in TargetLowering to convert the register
47035   // constraint into a member of a register class.
47036   std::pair<unsigned, const TargetRegisterClass*> Res;
47037   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
47038 
47039   // Not found as a standard register?
47040   if (!Res.second) {
47041     // Map st(0) -> st(7) -> ST0
47042     if (Constraint.size() == 7 && Constraint[0] == '{' &&
47043         tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
47044         Constraint[3] == '(' &&
47045         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
47046         Constraint[5] == ')' && Constraint[6] == '}') {
47047       // st(7) is not allocatable and thus not a member of RFP80. Return
47048       // singleton class in cases where we have a reference to it.
47049       if (Constraint[4] == '7')
47050         return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
47051       return std::make_pair(X86::FP0 + Constraint[4] - '0',
47052                             &X86::RFP80RegClass);
47053     }
47054 
47055     // GCC allows "st(0)" to be called just plain "st".
47056     if (StringRef("{st}").equals_lower(Constraint))
47057       return std::make_pair(X86::FP0, &X86::RFP80RegClass);
47058 
47059     // flags -> EFLAGS
47060     if (StringRef("{flags}").equals_lower(Constraint))
47061       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
47062 
47063     // dirflag -> DF
47064     if (StringRef("{dirflag}").equals_lower(Constraint))
47065       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
47066 
47067     // fpsr -> FPSW
47068     if (StringRef("{fpsr}").equals_lower(Constraint))
47069       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
47070 
47071     return Res;
47072   }
47073 
47074   // Make sure it isn't a register that requires 64-bit mode.
47075   if (!Subtarget.is64Bit() &&
47076       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
47077       TRI->getEncodingValue(Res.first) >= 8) {
47078     // Register requires REX prefix, but we're in 32-bit mode.
47079     return std::make_pair(0, nullptr);
47080   }
47081 
47082   // Make sure it isn't a register that requires AVX512.
47083   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
47084       TRI->getEncodingValue(Res.first) & 0x10) {
47085     // Register requires EVEX prefix.
47086     return std::make_pair(0, nullptr);
47087   }
47088 
47089   // Otherwise, check to see if this is a register class of the wrong value
47090   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
47091   // turn into {ax},{dx}.
47092   // MVT::Other is used to specify clobber names.
47093   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
47094     return Res;   // Correct type already, nothing to do.
47095 
47096   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
47097   // return "eax". This should even work for things like getting 64bit integer
47098   // registers when given an f64 type.
47099   const TargetRegisterClass *Class = Res.second;
47100   // The generic code will match the first register class that contains the
47101   // given register. Thus, based on the ordering of the tablegened file,
47102   // the "plain" GR classes might not come first.
47103   // Therefore, use a helper method.
47104   if (isGRClass(*Class)) {
47105     unsigned Size = VT.getSizeInBits();
47106     if (Size == 1) Size = 8;
47107     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
47108     if (DestReg > 0) {
47109       bool is64Bit = Subtarget.is64Bit();
47110       const TargetRegisterClass *RC =
47111           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
47112         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
47113         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
47114         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
47115         : nullptr;
47116       if (Size == 64 && !is64Bit) {
47117         // Model GCC's behavior here and select a fixed pair of 32-bit
47118         // registers.
47119         switch (DestReg) {
47120         case X86::RAX:
47121           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
47122         case X86::RDX:
47123           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
47124         case X86::RCX:
47125           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
47126         case X86::RBX:
47127           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
47128         case X86::RSI:
47129           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
47130         case X86::RDI:
47131           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
47132         case X86::RBP:
47133           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
47134         default:
47135           return std::make_pair(0, nullptr);
47136         }
47137       }
47138       if (RC && RC->contains(DestReg))
47139         return std::make_pair(DestReg, RC);
47140       return Res;
47141     }
47142     // No register found/type mismatch.
47143     return std::make_pair(0, nullptr);
47144   } else if (isFRClass(*Class)) {
47145     // Handle references to XMM physical registers that got mapped into the
47146     // wrong class.  This can happen with constraints like {xmm0} where the
47147     // target independent register mapper will just pick the first match it can
47148     // find, ignoring the required type.
47149 
47150     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
47151     if (VT == MVT::f32 || VT == MVT::i32)
47152       Res.second = &X86::FR32XRegClass;
47153     else if (VT == MVT::f64 || VT == MVT::i64)
47154       Res.second = &X86::FR64XRegClass;
47155     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
47156       Res.second = &X86::VR128XRegClass;
47157     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
47158       Res.second = &X86::VR256XRegClass;
47159     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
47160       Res.second = &X86::VR512RegClass;
47161     else {
47162       // Type mismatch and not a clobber: Return an error;
47163       Res.first = 0;
47164       Res.second = nullptr;
47165     }
47166   } else if (isVKClass(*Class)) {
47167     if (VT == MVT::i1)
47168       Res.second = &X86::VK1RegClass;
47169     else if (VT == MVT::i8)
47170       Res.second = &X86::VK8RegClass;
47171     else if (VT == MVT::i16)
47172       Res.second = &X86::VK16RegClass;
47173     else if (VT == MVT::i32)
47174       Res.second = &X86::VK32RegClass;
47175     else if (VT == MVT::i64)
47176       Res.second = &X86::VK64RegClass;
47177     else {
47178       // Type mismatch and not a clobber: Return an error;
47179       Res.first = 0;
47180       Res.second = nullptr;
47181     }
47182   }
47183 
47184   return Res;
47185 }
47186 
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const47187 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
47188                                             const AddrMode &AM, Type *Ty,
47189                                             unsigned AS) const {
47190   // Scaling factors are not free at all.
47191   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
47192   // will take 2 allocations in the out of order engine instead of 1
47193   // for plain addressing mode, i.e. inst (reg1).
47194   // E.g.,
47195   // vaddps (%rsi,%rdx), %ymm0, %ymm1
47196   // Requires two allocations (one for the load, one for the computation)
47197   // whereas:
47198   // vaddps (%rsi), %ymm0, %ymm1
47199   // Requires just 1 allocation, i.e., freeing allocations for other operations
47200   // and having less micro operations to execute.
47201   //
47202   // For some X86 architectures, this is even worse because for instance for
47203   // stores, the complex addressing mode forces the instruction to use the
47204   // "load" ports instead of the dedicated "store" port.
47205   // E.g., on Haswell:
47206   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
47207   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
47208   if (isLegalAddressingMode(DL, AM, Ty, AS))
47209     // Scale represents reg2 * scale, thus account for 1
47210     // as soon as we use a second register.
47211     return AM.Scale != 0;
47212   return -1;
47213 }
47214 
isIntDivCheap(EVT VT,AttributeList Attr) const47215 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
47216   // Integer division on x86 is expensive. However, when aggressively optimizing
47217   // for code size, we prefer to use a div instruction, as it is usually smaller
47218   // than the alternative sequence.
47219   // The exception to this is vector division. Since x86 doesn't have vector
47220   // integer division, leaving the division as-is is a loss even in terms of
47221   // size, because it will have to be scalarized, while the alternative code
47222   // sequence can be performed in vector form.
47223   bool OptSize =
47224       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
47225   return OptSize && !VT.isVector();
47226 }
47227 
initializeSplitCSR(MachineBasicBlock * Entry) const47228 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
47229   if (!Subtarget.is64Bit())
47230     return;
47231 
47232   // Update IsSplitCSR in X86MachineFunctionInfo.
47233   X86MachineFunctionInfo *AFI =
47234       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
47235   AFI->setIsSplitCSR(true);
47236 }
47237 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const47238 void X86TargetLowering::insertCopiesSplitCSR(
47239     MachineBasicBlock *Entry,
47240     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
47241   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
47242   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
47243   if (!IStart)
47244     return;
47245 
47246   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
47247   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
47248   MachineBasicBlock::iterator MBBI = Entry->begin();
47249   for (const MCPhysReg *I = IStart; *I; ++I) {
47250     const TargetRegisterClass *RC = nullptr;
47251     if (X86::GR64RegClass.contains(*I))
47252       RC = &X86::GR64RegClass;
47253     else
47254       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
47255 
47256     Register NewVR = MRI->createVirtualRegister(RC);
47257     // Create copy from CSR to a virtual register.
47258     // FIXME: this currently does not emit CFI pseudo-instructions, it works
47259     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
47260     // nounwind. If we want to generalize this later, we may need to emit
47261     // CFI pseudo-instructions.
47262     assert(
47263         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
47264         "Function should be nounwind in insertCopiesSplitCSR!");
47265     Entry->addLiveIn(*I);
47266     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
47267         .addReg(*I);
47268 
47269     // Insert the copy-back instructions right before the terminator.
47270     for (auto *Exit : Exits)
47271       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
47272               TII->get(TargetOpcode::COPY), *I)
47273           .addReg(NewVR);
47274   }
47275 }
47276 
supportSwiftError() const47277 bool X86TargetLowering::supportSwiftError() const {
47278   return Subtarget.is64Bit();
47279 }
47280 
47281 /// Returns the name of the symbol used to emit stack probes or the empty
47282 /// string if not applicable.
47283 StringRef
getStackProbeSymbolName(MachineFunction & MF) const47284 X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
47285   // If the function specifically requests stack probes, emit them.
47286   if (MF.getFunction().hasFnAttribute("probe-stack"))
47287     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
47288 
47289   // Generally, if we aren't on Windows, the platform ABI does not include
47290   // support for stack probes, so don't emit them.
47291   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
47292       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
47293     return "";
47294 
47295   // We need a stack probe to conform to the Windows ABI. Choose the right
47296   // symbol.
47297   if (Subtarget.is64Bit())
47298     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
47299   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
47300 }
47301 
47302 unsigned
getStackProbeSize(MachineFunction & MF) const47303 X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
47304   // The default stack probe size is 4096 if the function has no stackprobesize
47305   // attribute.
47306   unsigned StackProbeSize = 4096;
47307   const Function &Fn = MF.getFunction();
47308   if (Fn.hasFnAttribute("stack-probe-size"))
47309     Fn.getFnAttribute("stack-probe-size")
47310         .getValueAsString()
47311         .getAsInteger(0, StackProbeSize);
47312   return StackProbeSize;
47313 }
47314